87kangsw
(Kanz)
1
Hello, everyone. I'm Vapor beginner.
I'm interested in Vapor 4 recently, started to make a toy project with it.
But having trouble with few things. Please help out if you have some ideas on it.
Here's what I want to create ;
-
Define POST routes with one parameters.
-
Asyncronous job with 3rd party library.
-
Save to Database
func createHandler(_ req: Request) throws -> EventLoopFuture<CustomModel> {
// 1.
let param = try req.content.decode(ParamModel.self)
// 2. Asyncronous
ThirdPartyLibrary.request(with: param) { result in
// 3. How to save model and return EventLoopFuture
let saveModel = CustomModel(title: result.title,
description: result.description)
saveModel.save(on: req.db)
}
}
I found external API like this..
req.client.get(...)
req.client.post(...)
However, it is confused with the previous case.
Any idea how I can make this work?
Thank you.
bzamayo
(Benjamin Mayo)
2
Presumably, your third-party library does not return an EventLoopFuture and is just a 'normal' completion handler API. In that case, you need to bridge the two worlds by making a EventLoopPromise which is resolved in the body of the completion block. The NIO docs has a nice example of the pattern.
If you need to call this closure API many times, you can make an extension that is implemented with a promise, but only expose a future-based API to the rest of your project.
87kangsw
(Kanz)
3
Hi, @bzamayo
Thanks for the reply.
I will study more with the information you informed.
Thank you! 