-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
routes.swift
356 lines (305 loc) · 11.3 KB
/
routes.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
import class Foundation.Bundle
import Vapor
import NIOCore
import NIOHTTP1
import NIOConcurrencyHelpers
struct Creds: Content {
var email: String
var password: String
}
public func routes(_ app: Application) throws {
app.on(.GET, "ping") { req -> StaticString in
return "123" as StaticString
}
// ( echo -e 'POST /slow-stream HTTP/1.1\r\nContent-Length: 1000000000\r\n\r\n'; dd if=/dev/zero; ) | nc localhost 8080
app.on(.POST, "slow-stream", body: .stream) { req -> EventLoopFuture<String> in
let done = req.eventLoop.makePromise(of: String.self)
let totalBox = NIOLoopBoundBox(0, eventLoop: req.eventLoop)
req.body.drain { result in
let promise = req.eventLoop.makePromise(of: Void.self)
switch result {
case .buffer(let buffer):
req.eventLoop.scheduleTask(in: .milliseconds(1000)) {
totalBox.value += buffer.readableBytes
promise.succeed(())
}
case .error(let error):
done.fail(error)
case .end:
promise.succeed(())
done.succeed(totalBox.value.description)
}
// manually return pre-completed future
// this should balloon in memory
// return req.eventLoop.makeSucceededFuture(())
// return real future that indicates bytes were handled
// this should use very little memory
return promise.futureResult
}
return done.futureResult
}
app.get("test", "head") { req -> String in
return "OK!"
}
app.post("test", "head") { req -> String in
return "OK!"
}
app.post("login") { req -> String in
let creds = try req.content.decode(Creds.self)
return "\(creds)"
}
app.on(.POST, "large-file", body: .collect(maxSize: 1_000_000_000)) { req -> String in
return req.body.data?.readableBytes.description ?? "none"
}
app.get("json") { req -> [String: String] in
return ["foo": "bar"]
}.description("returns some test json")
app.webSocket("ws") { req, ws in
ws.onText { ws, text in
ws.send(text.reversed())
if text == "close" {
ws.close(promise: nil)
}
}
let ip = req.remoteAddress?.description ?? "<no ip>"
ws.send("Hello 👋 \(ip)")
}
app.on(.POST, "file", body: .stream) { req -> EventLoopFuture<String> in
let promise = req.eventLoop.makePromise(of: String.self)
req.body.drain { result in
switch result {
case .buffer(let buffer):
debugPrint(buffer)
case .error(let error):
promise.fail(error)
case .end:
promise.succeed("Done")
}
return req.eventLoop.makeSucceededFuture(())
}
return promise.futureResult
}
app.get("shutdown") { req -> HTTPStatus in
guard let running = req.application.running else {
throw Abort(.internalServerError)
}
running.stop()
return .ok
}
let cache = MemoryCache()
app.get("cache", "get", ":key") { req -> String in
guard let key = req.parameters.get("key") else {
throw Abort(.internalServerError)
}
return "\(key) = \(await cache.get(key) ?? "nil")"
}
app.get("cache", "set", ":key", ":value") { req -> String in
guard let key = req.parameters.get("key") else {
throw Abort(.internalServerError)
}
guard let value = req.parameters.get("value") else {
throw Abort(.internalServerError)
}
await cache.set(key, to: value)
return "\(key) = \(value)"
}
app.get("hello", ":name") { req in
return req.parameters.get("name") ?? "<nil>"
}
app.get("search") { req in
return req.query["q"] ?? "none"
}
let sessions = app.grouped("sessions")
.grouped(app.sessions.middleware)
sessions.get("set", ":value") { req -> HTTPStatus in
req.session.data["name"] = req.parameters.get("value")
return .ok
}
sessions.get("get") { req -> String in
req.session.data["name"] ?? "n/a"
}
sessions.get("del") { req -> String in
req.session.destroy()
return "done"
}
app.get("client") { req in
return req.client.get("http://httpbin.org/status/201").map { $0.description }
}
app.get("client-json") { req -> EventLoopFuture<String> in
struct HTTPBinResponse: Decodable {
struct Slideshow: Decodable {
var title: String
}
var slideshow: Slideshow
}
return req.client.get("http://httpbin.org/json")
.flatMapThrowing { try $0.content.decode(HTTPBinResponse.self) }
.map { $0.slideshow.title }
}
let users = app.grouped("users")
users.get { req in
return "users"
}
users.get(":userID") { req in
return req.parameters.get("userID") ?? "no id"
}
app.directory.viewsDirectory = "/Users/tanner/Desktop"
app.get("view") { req in
req.view.render("hello.txt", ["name": "world"])
}
app.get("error") { req -> String in
throw TestError()
}
app.get("secret") { (req) -> EventLoopFuture<String> in
return Environment
.secret(key: "PASSWORD_SECRET", fileIO: req.application.fileio, on: req.eventLoop)
.unwrap(or: Abort(.badRequest))
}
app.on(.POST, "max-256", body: .collect(maxSize: 256)) { req -> HTTPStatus in
print("in route")
return .ok
}
app.on(.POST, "upload", body: .stream) { req -> EventLoopFuture<HTTPStatus> in
enum BodyStreamWritingToDiskError: Error {
case streamFailure(Error)
case fileHandleClosedFailure(Error)
case multipleFailures([BodyStreamWritingToDiskError])
}
return req.application.fileio.openFile(
path: Bundle.module.url(forResource: "Resources/fileio", withExtension: "txt")?.path ?? "",
mode: .write,
flags: .allowFileCreation(),
eventLoop: req.eventLoop
).flatMap { fileHandle in
let promise = req.eventLoop.makePromise(of: HTTPStatus.self)
let fileHandleBox = NIOLoopBound(fileHandle, eventLoop: req.eventLoop)
req.body.drain { part in
let fileHandle = fileHandleBox.value
switch part {
case .buffer(let buffer):
return req.application.fileio.write(
fileHandle: fileHandle,
buffer: buffer,
eventLoop: req.eventLoop
)
case .error(let drainError):
do {
try fileHandle.close()
promise.fail(BodyStreamWritingToDiskError.streamFailure(drainError))
} catch {
promise.fail(BodyStreamWritingToDiskError.multipleFailures([
.fileHandleClosedFailure(error),
.streamFailure(drainError)
]))
}
return req.eventLoop.makeSucceededFuture(())
case .end:
do {
try fileHandle.close()
promise.succeed(.ok)
} catch {
promise.fail(BodyStreamWritingToDiskError.fileHandleClosedFailure(error))
}
return req.eventLoop.makeSucceededFuture(())
}
}
return promise.futureResult
}
}
let asyncRoutes = app.grouped("async").grouped(TestAsyncMiddleware(number: 1))
asyncRoutes.get("client") { req async throws -> String in
let response = try await req.client.get("https://www.google.com")
guard let body = response.body else {
throw Abort(.internalServerError)
}
return String(buffer: body)
}
asyncRoutes.get("client2") { req -> String in
let response = try await req.client.get("https://www.google.com")
guard let body = response.body else {
throw Abort(.internalServerError)
}
return String(buffer: body)
}
asyncRoutes.get("content") { req in
Creds(email: "name", password: "password")
}
asyncRoutes.get("content2") { req async throws -> Creds in
return Creds(email: "name", password: "password")
}
asyncRoutes.get("contentArray") { req async throws -> [Creds] in
let cred1 = Creds(email: "name", password: "password")
return [cred1]
}
@Sendable
func opaqueRouteTester(_ req: Request) async throws -> some AsyncResponseEncodable {
"Hello World"
}
asyncRoutes.get("opaque", use: opaqueRouteTester)
// Make sure jumping between multiple different types of middleware works
asyncRoutes.grouped(TestAsyncMiddleware(number: 2), TestMiddleware(number: 3), TestAsyncMiddleware(number: 4), TestMiddleware(number: 5)).get("middleware") { req async throws -> String in
return "OK"
}
let basicAuthRoutes = asyncRoutes.grouped(Test.authenticator(), Test.guardMiddleware())
basicAuthRoutes.get("auth") { req async throws -> String in
return try req.auth.require(Test.self).name
}
struct Test: Authenticatable {
static func authenticator() -> AsyncAuthenticator {
TestAuthenticator()
}
var name: String
}
struct TestAuthenticator: AsyncBasicAuthenticator {
typealias User = Test
func authenticate(basic: BasicAuthorization, for request: Request) async throws {
if basic.username == "test" && basic.password == "secret" {
let test = Test(name: "Vapor")
request.auth.login(test)
}
}
}
}
struct TestError: AbortError, DebuggableError {
var status: HTTPResponseStatus {
.internalServerError
}
var reason: String {
"This is a test."
}
var source: ErrorSource?
init(
file: String = #fileID,
function: String = #function,
line: UInt = #line,
column: UInt = #column,
range: Range<UInt>? = nil
) {
self.source = .init(
file: file,
function: function,
line: line,
column: column,
range: range
)
}
}
struct TestAsyncMiddleware: AsyncMiddleware {
let number: Int
func respond(to request: Request, chainingTo next: AsyncResponder) async throws -> Response {
request.logger.debug("In async middleware - \(number)")
let response = try await next.respond(to: request)
request.logger.debug("In async middleware way out - \(number)")
return response
}
}
struct TestMiddleware: Middleware {
let number: Int
func respond(to request: Request, chainingTo next: Responder) -> EventLoopFuture<Response> {
request.logger.debug("In non-async middleware - \(number)")
return next.respond(to: request).map { response in
request.logger.debug("In non-async middleware way out - \(self.number)")
return response
}
}
}