-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.swift
73 lines (55 loc) · 2.16 KB
/
main.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import Foundation
import Swift_Express
import NIO
import Swift_Coroutine_NIO2
let threadPool: NIOThreadPool = {
let tp = NIOThreadPool(numberOfThreads: System.coreCount)
tp.start()
return tp
}()
let app = Express()
// Logging
app.use { req, res, next in
print("\(req.header.method):", req.header.uri)
next() // continue processing
}
app.use(querystring, cors(allowOrigin: "*")) // parse query params
app.get("/hello") { req, res, _ in
//res.send("Hello")
let eventLoopOfRequest = req._channel.eventLoop
EventLoopFuture<Void>.coroutine(eventLoop: eventLoopOfRequest, scheduler: eventLoopOfRequest) { co in
print("workflow - before")
print("coDelay - start \(Thread.current)")
let start = Date.timeIntervalSinceReferenceDate
try co.delay(.milliseconds(2000))
let end = Date.timeIntervalSinceReferenceDate
print("coDelay - end \(Thread.current) in \((end - start) * 1000) ms")
print("co.delay - Thread.current - \(Thread.current)")
// switch to IO thread for some expensive work!
// -----------------------------------------------
try co.continueOn(threadPool)
print("co.continueOn(threadPool) - Thread.current - \(Thread.current)")
try co.yield()
print("co.continueOn(threadPool) after co.yield() - Thread.current - \(Thread.current)")
// remember switch back to request's eventLoop for `Response # send`,
// keep in mind that `Request` and `Response` must be running in the same eventloop to ensure the correctness of the timing sequence
// -----------------------------------------------
try co.continueOn(eventLoopOfRequest) // switch to IO thread for some expensive work!
print("co.continueOn(eventLoop) - Thread.current - \(Thread.current)")
res.send("Hello - delay 2000 ms")
print("workflow - end")
}
}
app.get("/moo") { _, res, _ in
res.send("Moo!")
}
app.get("/todomvc") { _, res, _ in
// send JSON to the browser
res.json(todos)
}
app.get { req, res, _ in
let text = req.param("text")
?? "Schwifty"
res.send("Hello, \(text) world!")
}
app.listen(1337)