我正在编写一个 Vapor 3 项目,该项目以键:值对的形式写入 FoundationDB 数据库。我有以下代码,使用一个名为 Country 的结构来扩展 Content。我想将国家/地区数据保存为 JSON 字符串,然后将其转换为要保存的字节。
func createCountry(req: Request, country: Country) throws -> Future<Country>{
return try req.content.decode(Country.self).map(to: Country.self) { country in
let dbConnection = FDBConnector()
let CountryKey = Tuple("iVendor", "Country", country.country_name).pack()
let countryValue = COUNTRY_TO_JSON_TO_STRING_FUNCTION
let success = dbConnection.writeRecord(pathKey: CountryKey, value: countryValue )
if success {
return country
} //else {
return country
}
}
}
Run Code Online (Sandbox Code Playgroud)
如何将结构转换为以字符串形式存储的 JSON?
我正在使用Vapor 3并链接到FoundationDB数据库,因此我不使用Fluent.我有一个搜索记录的方法,但如果它没有返回记录,它会明显崩溃(因为我强制解包该值).
我想保护数据库中的读数,如果没有找到记录则返回响应.然而,这将不是未来预期的记录.我在想我应该返回一个不同的响应,但我不确定如何更改预期的结果.
//creates a specific country
func getCountry( req: Request) throws -> Future<Country> {
// get Country name from get parameter string
let countryString = try req.parameters.next(String.self)
// get record from Database. This could fail and so needs to be guarded. What response should be returned as the Future requires a Country datatype?
let record = FDBConnector().getRecord(path: Subspace("iVendor").subspace(["Countries", countryString]))
let newCountry = try JSONDecoder().decode(Country.self, from: record!)
// return Country Struct
return Future.map(on: req) {return newCountry }
}
Run Code Online (Sandbox Code Playgroud) 我虽然固守了这个观念!
我正在发送包含双精度的JSON。
{"elementName":"Security:Driver","element_Cost":"650"}
Run Code Online (Sandbox Code Playgroud)
我已经创建了CodingKeys和一个解码器扩展,但是在发送数据时仍然出现Type Mismatch错误。
struct ElementCosts: Content {
let elementName: String
let elementCost: Double
enum CodingKeys: String, CodingKey {
case elementCost = "element_Cost"
case elementName
}
}
extension ElementCosts: Decodable {
public init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
elementCost = try values.decode(Double.self, forKey: .elementCost)
elementName = try values.decode(String.self, forKey: .elementName)
}
}
Run Code Online (Sandbox Code Playgroud)
在这里查看其他一些帖子,我看不到我做错了什么。
我试图将数据类型更改为Int,但仍然存在相同的问题。
有任何想法吗?