func createPoll(on req: Request) throws -> String {
let poll = try req.content.decode(Poll.self)
return poll.save(on: req).map(to: Poll.self) {
return poll
}
}
这只适用于在json对象下发送的数据
{
"title": "Once Poll",
"option1": "Black finish",
"option2": "Dark Gray finish",
"votes1": 10,
"votes2": 0
}
但是如果对象是这样发送的,并且带有一个键:poll,我就无法解析它!
{
"poll": {
"title": "Once Poll",
"option1": "Black finish",
"option2": "Dark Gray finish",
"votes1": 10,
"votes2": 0
}
}
这是我使用以下答案的解决方案:
struct PollRequestObject: Content {
let poll: Poll?
}
func createPoll(on req: Request) throws -> Future<Poll> {
guard let poll = try req.content.decode(PollRequestObject.self).poll else {
throw Abort(.badRequest)
}
return poll.save(on: req).map(to: Poll.self) {
return poll
}
}