Reputation: 75
I need some help about saving bytes in Vapor : I have this Image 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")
}
}
I'm sending with Postman a POST request with this body :
{
"name": "politique.jpg",
"datas": [122, 122]
}
Then It creates a new line in my Database with datas.
But when i try a GET on this image, i have this error when extracting object :
Could not initialize Image, skipping: unableToConvert(node: Optional(Node.Node.bytes([101, 110, 111, 61])), expected: "UInt8")
What i'm doing wrong here ? Thanks for all.
Upvotes: 2
Views: 462
Reputation: 4065
The extract
method does not support initializing arrays in Vapor 1. You'll need to manually pull out the data using something like:
self.datas = node["datas"]?.bytes ?? []
The issue is that it's pretty difficult for us to tell when something like [1,2,3]
is an array of individual JSON numbers, and when it's meant to represent a collection of data. For example:
scores: [1, 10, 44, 5]
Would likely want to be an array of JSON where something like:
image: [1, 10, 44, 5]
represents raw data.
In general, because individual objects are more common, we prioritize that and users must opt-in to access bytes and things through the conveniences we have like the code above.
Upvotes: 1