Skip to content

Instantly share code, notes, and snippets.

@cweinberger
Last active January 19, 2021 22:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cweinberger/81e692eb7a07c434e118ab0ddc1ef884 to your computer and use it in GitHub Desktop.
Save cweinberger/81e692eb7a07c434e118ab0ddc1ef884 to your computer and use it in GitHub Desktop.
Vapor 4 EventLoopFutureQueue
/**
Assuming the route handler is attached to `http://localhost:8080/import-data` you can test the implementation with this request (cURL):
```
curl -X "POST" "http://localhost:8080/import-data" \
-H 'Content-Type: application/json; charset=utf-8' \
-d $'{ "values": ["first", "foo", "bar", "last"] }'
```
Prints:
```
Start importing data: ["first", "foo", "bar", "last"]
processing 'first' - sleeping for '0' seconds
processing 'foo' - sleeping for '2' seconds
processing 'bar' - sleeping for '1' seconds
processing 'last' - sleeping for '1' seconds
Finished processing data: ["first", "foo", "bar", "last"]
```
Learn more about `EventLoopFutureQueue` by studying the tests here: https://github.com/vapor/async-kit/blob/master/Tests/AsyncKitTests/EventLoopFutureQueueTests.swift
*/
/// Sample struct to demonstrate the case
struct ImportData: Content {
let values: [String]
}
/// Sample import data handler that runs synchronously using `EventLoopFutureQueue`
func importData(_ req: Request) throws -> EventLoopFuture<HTTPStatus> {
let data = try req.content.decode(ImportData.self)
let queue = EventLoopFutureQueue(eventLoop: req.eventLoop)
print("Start importing data: \(data.values)")
return data.values.map { value in
queue.append(self.importValue(value, on: req.eventLoop))
}
.flatten(on: req.eventLoop).map { res in
print("Finished processing data: \(res)")
}
.transform(to: .ok)
}
/// Mock implementation of importValue(_:on:) that takes randomly 0-3 seconds for processing the data
func importValue(_ value: String, on eventLoop: EventLoop) -> EventLoopFuture<String> {
let sleepValue = UInt32.random(in: 0...3)
print("processing '\(value)' - sleeping for '\(sleepValue)' seconds")
sleep(sleepValue)
return eventLoop.future(value)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment