forked from vapor/vapor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Application+Responder.swift
72 lines (59 loc) 路 2.04 KB
/
Application+Responder.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
extension Application {
public var responder: Responder {
.init(application: self)
}
public struct Responder {
public struct Provider {
public static var `default`: Self {
.init {
$0.responder.use { $0.responder.default }
}
}
let run: (Application) -> ()
public init(_ run: @escaping (Application) -> ()) {
self.run = run
}
}
final class Storage {
var factory: ((Application) -> Vapor.Responder)?
init() { }
}
struct Key: StorageKey {
typealias Value = Storage
}
public let application: Application
public var current: Vapor.Responder {
guard let factory = self.storage.factory else {
fatalError("No responder configured. Configure with app.responder.use(...)")
}
return factory(self.application)
}
public var `default`: Vapor.Responder {
DefaultResponder(
routes: self.application.routes,
middleware: self.application.middleware.resolve(),
reportMetrics: self.application.http.server.configuration.reportMetrics
)
}
public func use(_ provider: Provider) {
provider.run(self.application)
}
public func use(_ factory: @escaping (Application) -> (Vapor.Responder)) {
self.storage.factory = factory
}
var storage: Storage {
guard let storage = self.application.storage[Key.self] else {
fatalError("Responder not configured. Configure with app.responder.initialize()")
}
return storage
}
func initialize() {
self.application.storage[Key.self] = .init()
}
}
}
extension Application.Responder: Responder {
public func respond(to request: Request) -> EventLoopFuture<Response> {
self.current.respond(to: request)
}
}