节省字节蒸气 Swift

Saving Bytes Vapor Swift

我需要一些关于在 Vapor 中保存字节的帮助: 我有这张图片 class :

class Image: Model {
var id: Node?
var datas: Bytes
var name: String
var exists: Bool = false

init(name: String, datas: Bytes) {
    self.name = name
    self.datas = datas
}

// NodeInitializable
required init(node: Node, in context: Context) throws {
    self.id = try node.extract("id")
    self.datas = try node.extract("datas")
    self.name = try node.extract("name")
}

// NodeRepresentable
func makeNode(context: Context) throws -> Node {
    return try Node(node: ["id": id,
                           "name": name,
                           "datas": datas.string()
                           ])
}

// Preparation
static func prepare(_ database: Database) throws {


    try database.create("images") { categories in
        categories.id()
        categories.string("name")
        categories.data("datas")
    }


}

static func revert(_ database: Database) throws {
    try database.delete("images")
}

}

我正在通过 Postman 发送 POST 请求,正文为:

{ "name": "politique.jpg", "datas": [122, 122] }

然后它在我的数据库中用数据创建了一个新行。

但是当我在这张图片上尝试 GET 时,我在提取对象时遇到了这个错误:

Could not initialize Image, skipping: unableToConvert(node: Optional(Node.Node.bytes([101, 110, 111, 61])), expected: "UInt8")

我做错了什么?谢谢大家。

extract 方法不支持在 Vapor 1 中初始化数组。您需要使用以下方法手动提取数据:

self.datas = node["datas"]?.bytes ?? []

为什么?

问题在于,我们很难判断 [1,2,3] 之类的东西何时是单个 JSON 数字的数组,以及何时表示数据集合。例如:

scores: [1, 10, 44, 5]

可能希望成为 JSON 的数组,其中类似:

image: [1, 10, 44, 5] 

表示原始数据。

一般来说,因为单个对象更常见,所以我们优先考虑它,并且用户必须选择加入以通过我们像上面的代码那样的便利来访问字节和东西。