-
Notifications
You must be signed in to change notification settings - Fork 495
/
CodableRouter.swift
1005 lines (908 loc) · 45.8 KB
/
CodableRouter.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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright IBM Corporation 2017
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
import LoggerAPI
import KituraNet
import KituraContracts
/// Bridge [RequestError](https://ibm-swift.github.io/KituraContracts/Structs/RequestError.html)
/// from [KituraContracts](https://ibm-swift.github.io/KituraContracts) so that you only need to import
/// `Kitura` to access it.
public typealias RequestError = KituraContracts.RequestError
// Codable router
extension Router {
// MARK: Codable Routing
/**
Setup a CodableArrayClosure on the provided route which will be invoked when a request comes to the server.
### Usage Example: ###
````
//User is a struct object that conforms to Codable
router.get("/users") { (respondWith: ([User]?, RequestError?) -> Void) in
...
respondWith(users, nil)
}
````
- Parameter route: A String specifying the pattern that needs to be matched, in order for the handler to be invoked.
- Parameter handler: A CodableArrayClosure that gets invoked when a request comes to the server.
*/
public func get<O: Codable>(_ route: String, handler: @escaping CodableArrayClosure<O>) {
getSafely(route, handler: handler)
}
/**
Setup a SimpleCodableClosure on the provided route which will be invoked when a request comes to the server.
### Usage Example: ###
````
//Status is a struct object that conforms to Codable
router.get("/status") { (respondWith: (Status?, RequestError?) -> Void) in
...
respondWith(status, nil)
}
````
- Parameter route: A String specifying the pattern that needs to be matched, in order for the handler to be invoked.
- Parameter handler: A SimpleCodableClosure that gets invoked when a request comes to the server.
*/
public func get<O: Codable>(_ route: String, handler: @escaping SimpleCodableClosure<O>) {
getSafely(route, handler: handler)
}
/**
Setup a IdentifierSimpleCodableClosure on the provided route which will be invoked when a request comes to the server.
### Usage Example: ###
````
//User is a struct object that conforms to Codable
router.get("/users") { (id: Int, respondWith: (User?, RequestError?) -> Void) in
...
respondWith(user, nil)
}
````
- Parameter route: A String specifying the pattern that needs to be matched, in order for the handler to be invoked.
- Parameter handler: An IdentifierSimpleCodableClosure that gets invoked when a request comes to the server.
*/
public func get<Id: Identifier, O: Codable>(_ route: String, handler: @escaping IdentifierSimpleCodableClosure<Id, O>) {
getSafely(route, handler: handler)
}
/**
Setup a IdentifierCodableArrayClosure on the provided route which will be invoked when a request comes to the server.
### Usage Example: ###
````
//User is a struct object that conforms to Codable
router.get("/users") { (respondWith: ([(Int, User)]?, RequestError?) -> Void) in
...
respondWith([(Int, User)], nil)
}
````
- Parameter route: A String specifying the pattern that needs to be matched, in order for the handler to be invoked.
- Parameter handler: A IdentifierCodableArrayClosure that gets invoked when a request comes to the server.
*/
public func get<Id: Identifier, O: Codable>(_ route: String, handler: @escaping IdentifierCodableArrayClosure<Id, O>) {
getSafely(route, handler: handler)
}
/**
Setup a (QueryParams, CodableArrayResultClosure) -> Void on the provided route which will be invoked when a request comes to the server.
### Usage Example: ###
````
// MyQuery is a codable struct defining the supported query parameters
// User is a struct object that conforms to Codable
router.get("/query") { (query: MyQuery, respondWith: ([User]?, RequestError?) -> Void) in
...
respondWith(users, nil)
}
````
- Parameter route: A String specifying the pattern that needs to be matched, in order for the handler to be invoked.
- Parameter handler: A (QueryParams, CodableArrayResultClosure) -> Void that gets invoked when a request comes to the server.
*/
public func get<Q: QueryParams, O: Codable>(_ route: String, handler: @escaping (Q, @escaping CodableArrayResultClosure<O>) -> Void) {
getSafely(route, handler: handler)
}
/**
Setup a (QueryParams, CodableResultClosure) -> Void on the provided route which will be invoked when a request comes to the server.
### Usage Example: ###
````
// MyQuery is a codable struct defining the supported query parameters
// User is a struct object that conforms to Codable
router.get("/query") { (query: MyQuery, respondWith: (User?, RequestError?) -> Void) in
...
respondWith(user, nil)
}
````
- Parameter route: A String specifying the pattern that needs to be matched, in order for the handler to be invoked.
- Parameter handler: A (QueryParams, CodableResultClosure) -> Void that gets invoked when a request comes to the server.
*/
public func get<Q: QueryParams, O: Codable>(_ route: String, handler: @escaping (Q, @escaping CodableResultClosure<O>) -> Void) {
getSafely(route, handler: handler)
}
/**
Setup a (QueryParams?, CodableArrayResultClosure) -> Void on the provided route which will be invoked when a request comes to the server.
### Usage Example: ###
````
// MyQuery is a codable struct defining the supported query parameters
// User is a struct object that conforms to Codable
router.get("/query") { (query: MyQuery?, respondWith: ([User]?, RequestError?) -> Void) in
...
respondWith(users, nil)
}
````
- Parameter route: A String specifying the pattern that needs to be matched, in order for the handler to be invoked.
- Parameter handler: A (QueryParams?, CodableArrayResultClosure) -> Void that gets invoked when a request comes to the server.
*/
public func get<Q: QueryParams, O: Codable>(_ route: String, handler: @escaping (Q?, @escaping CodableArrayResultClosure<O>) -> Void) {
getSafely(route, handler: handler)
}
/**
Setup a (QueryParams?, CodableResultClosure) -> Void on the provided route which will be invoked when a request comes to the server.
### Usage Example: ###
````
// MyQuery is a codable struct defining the supported query parameters
// User is a struct object that conforms to Codable
router.get("/query") { (query: MyQuery?, respondWith: (User?, RequestError?) -> Void) in
...
respondWith(user, nil)
}
````
- Parameter route: A String specifying the pattern that needs to be matched, in order for the handler to be invoked.
- Parameter handler: A (QueryParams?, CodableResultClosure) -> Void that gets invoked when a request comes to the server.
*/
public func get<Q: QueryParams, O: Codable>(_ route: String, handler: @escaping (Q?, @escaping CodableResultClosure<O>) -> Void) {
getSafely(route, handler: handler)
}
/**
Setup a NonCodableClosure on the provided route which will be invoked when a request comes to the server.
### Usage Example: ###
````
router.delete("/users") { (respondWith: (RequestError?) -> Void) in
...
respondWith(nil)
}
````
- Parameter route: A String specifying the pattern that needs to be matched, in order for the handler to be invoked.
- Parameter handler: An NonCodableClosure that gets invoked when a request comes to the server.
*/
public func delete(_ route: String, handler: @escaping NonCodableClosure) {
deleteSafely(route, handler: handler)
}
/**
Setup a IdentifierNonCodableClosure on the provided route which will be invoked when a request comes to the server.
### Usage Example: ###
````
router.delete("/users") { (id: Int, respondWith: (RequestError?) -> Void) in
...
respondWith(nil)
}
````
- Parameter route: A String specifying the pattern that needs to be matched, in order for the handler to be invoked.
- Parameter handler: An IdentifierNonCodableClosure that gets invoked when a request comes to the server.
*/
public func delete<Id: Identifier>(_ route: String, handler: @escaping IdentifierNonCodableClosure<Id>) {
deleteSafely(route, handler: handler)
}
/**
Setup a (QueryParams, ResultClosure) -> Void on the provided route which will be invoked when a request comes to the server.
### Usage Example: ###
````
// MyQuery is a codable struct defining the supported query parameters
router.delete("/query") { (query: MyQuery, respondWith: (RequestError?) -> Void) in
...
respondWith(nil)
}
````
- Parameter route: A String specifying the pattern that needs to be matched, in order for the handler to be invoked.
- Parameter handler: A (QueryParams, ResultClosure) -> Void that gets invoked when a request comes to the server.
*/
public func delete<Q: QueryParams>(_ route: String, handler: @escaping (Q, @escaping ResultClosure) -> Void) {
deleteSafely(route, handler: handler)
}
/**
Setup a (QueryParams?, ResultClosure) -> Void on the provided route which will be invoked when a request comes to the server.
### Usage Example: ###
````
// MyQuery is a codable struct defining the supported query parameters
router.delete("/query") { (query: MyQuery?, respondWith: (RequestError?) -> Void) in
...
respondWith(nil)
}
````
- Parameter route: A String specifying the pattern that needs to be matched, in order for the handler to be invoked.
- Parameter handler: A (QueryParams?, ResultClosure) -> Void that gets invoked when a request comes to the server.
*/
public func delete<Q: QueryParams>(_ route: String, handler: @escaping (Q?, @escaping ResultClosure) -> Void) {
deleteSafely(route, handler: handler)
}
/**
Setup a CodableClosure on the provided route which will be invoked when a POST request comes to the server.
In this scenario, the ID (i.e. unique identifier) is a field in the Codable instance.
### Usage Example: ###
````
//User is a struct object that conforms to Codable
router.post("/users") { (user: User, respondWith: (User?, RequestError?) -> Void) in
...
respondWith(user, nil)
}
````
- Parameter route: A String specifying the pattern that needs to be matched, in order for the handler to be invoked.
- Parameter handler: A Codable closure that gets invoked when a request comes to the server.
*/
public func post<I: Codable, O: Codable>(_ route: String, handler: @escaping CodableClosure<I, O>) {
postSafely(route, handler: handler)
}
/**
Setup a CodableIdentifierClosure on the provided route which will be invoked when a POST request comes to the server.
In this scenario, the ID (i.e. unique identifier) for the Codable instance is a separate field (which is sent back to the client
in the location HTTP header).
### Usage Example: ###
````
//User is a struct object that conforms to Codable
router.post("/users") { (user: User, respondWith: (Int?, User?, RequestError?) -> Void) in
...
respondWith(id, user, nil)
}
````
- Parameter route: A String specifying the pattern that needs to be matched, in order for the handler to be invoked.
- Parameter handler: A Codable closure that gets invoked when a request comes to the server.
*/
public func post<I: Codable, Id: Identifier, O: Codable>(_ route: String, handler: @escaping CodableIdentifierClosure<I, Id, O>) {
postSafelyWithId(route, handler: handler)
}
/**
Setup a IdentifierCodableClosure on the provided route which will be invoked when a request comes to the server.
### Usage Example: ###
````
//User is a struct object that conforms to Codable
router.put("/users") { (id: Int, user: User, respondWith: (User?, RequestError?) -> Void) in
...
respondWith(user, nil)
}
````
- Parameter route: A String specifying the pattern that needs to be matched, in order for the handler to be invoked.
- Parameter handler: An Identifier Codable closure that gets invoked when a request comes to the server.
*/
public func put<Id: Identifier, I: Codable, O: Codable>(_ route: String, handler: @escaping IdentifierCodableClosure<Id, I, O>) {
putSafely(route, handler: handler)
}
/**
Setup a IdentifierCodableClosure on the provided route which will be invoked when a request comes to the server.
### Usage Example: ###
````
//User is a struct object that conforms to Codable
//OptionalUser is a struct object that conforms to Codable where all properties are optional
router.patch("/users") { (id: Int, patchUser: OptionalUser, respondWith: (User?, RequestError?) -> Void) -> Void in
...
respondWith(user, nil)
}
````
- Parameter route: A String specifying the pattern that needs to be matched, in order for the handler to be invoked.
- Parameter handler: An Identifier Codable closure that gets invoked when a request comes to the server.
*/
public func patch<Id: Identifier, I: Codable, O: Codable>(_ route: String, handler: @escaping IdentifierCodableClosure<Id, I, O>) {
patchSafely(route, handler: handler)
}
// POST
fileprivate func postSafely<I: Codable, O: Codable>(_ route: String, handler: @escaping CodableClosure<I, O>) {
registerPostRoute(route: route, inputType: I.self, outputType: O.self)
post(route) { request, response, next in
Log.verbose("Received POST type-safe request")
guard let codableInput = CodableHelpers.readCodableOrSetResponseStatus(I.self, from: request, response: response) else {
next()
return
}
handler(codableInput, CodableHelpers.constructOutResultHandler(successStatus: .created, response: response, completion: next))
}
}
// POST
fileprivate func postSafelyWithId<I: Codable, Id: Identifier, O: Codable>(_ route: String, handler: @escaping CodableIdentifierClosure<I, Id, O>) {
registerPostRoute(route: route, id: Id.self, inputType: I.self, outputType: O.self)
post(route) { request, response, next in
Log.verbose("Received POST type-safe request")
guard let codableInput = CodableHelpers.readCodableOrSetResponseStatus(I.self, from: request, response: response) else {
next()
return
}
handler(codableInput, CodableHelpers.constructIdentOutResultHandler(successStatus: .created, response: response, completion: next))
}
}
// PUT with Identifier
fileprivate func putSafely<Id: Identifier, I: Codable, O: Codable>(_ route: String, handler: @escaping IdentifierCodableClosure<Id, I, O>) {
if !pathSyntaxIsValid(route, identifierExpected: true) {
return
}
registerPutRoute(route: route, id: Id.self, inputType: I.self, outputType: O.self)
put(join(path: route, with: ":id")) { request, response, next in
Log.verbose("Received PUT type-safe request")
guard let identifier = CodableHelpers.parseIdOrSetResponseStatus(Id.self, from: request, response: response),
let codableInput = CodableHelpers.readCodableOrSetResponseStatus(I.self, from: request, response: response)
else {
next()
return
}
handler(identifier, codableInput, CodableHelpers.constructOutResultHandler(response: response, completion: next))
}
}
// PATCH
fileprivate func patchSafely<Id: Identifier, I: Codable, O: Codable>(_ route: String, handler: @escaping IdentifierCodableClosure<Id, I, O>) {
if !pathSyntaxIsValid(route, identifierExpected: true) {
return
}
registerPatchRoute(route: route, id: Id.self, inputType: I.self, outputType: O.self)
patch(join(path: route, with: ":id")) { request, response, next in
Log.verbose("Received PATCH type-safe request")
guard let identifier = CodableHelpers.parseIdOrSetResponseStatus(Id.self, from: request, response: response),
let codableInput = CodableHelpers.readCodableOrSetResponseStatus(I.self, from: request, response: response)
else {
next()
return
}
handler(identifier, codableInput, CodableHelpers.constructOutResultHandler(response: response, completion: next))
}
}
// Get single
fileprivate func getSafely<O: Codable>(_ route: String, handler: @escaping SimpleCodableClosure<O>) {
registerGetRoute(route: route, outputType: O.self)
get(route) { request, response, next in
Log.verbose("Received GET (single no-identifier) type-safe request")
handler(CodableHelpers.constructOutResultHandler(response: response, completion: next))
}
}
// Get array
fileprivate func getSafely<O: Codable>(_ route: String, handler: @escaping CodableArrayClosure<O>) {
registerGetRoute(route: route, outputType: O.self)
get(route) { request, response, next in
Log.verbose("Received GET (plural) type-safe request")
handler(CodableHelpers.constructOutResultHandler(response: response, completion: next))
}
}
// Get array of (Id, Codable) tuples
fileprivate func getSafely<Id: Identifier, O: Codable>(_ route: String, handler: @escaping IdentifierCodableArrayClosure<Id, O>) {
registerGetRoute(route: route, id: Id.self, outputType: O.self)
get(route) { request, response, next in
Log.verbose("Received GET (plural with identifier) type-safe request")
handler(CodableHelpers.constructTupleArrayOutResultHandler(response: response, completion: next))
}
}
// Get w/Query Parameters
fileprivate func getSafely<Q: QueryParams, O: Codable>(_ route: String, handler: @escaping (Q, @escaping CodableArrayResultClosure<O>) -> Void) {
registerGetRoute(route: route, queryParams: Q.self, optionalQParam: false, outputType: O.self)
get(route) { request, response, next in
Log.verbose("Received GET (plural) type-safe request with Query Parameters")
Log.verbose("Query Parameters: \(request.queryParameters)")
do {
let query: Q = try QueryDecoder(dictionary: request.queryParameters).decode(Q.self)
handler(query, CodableHelpers.constructOutResultHandler(response: response, completion: next))
} catch {
// Http 400 error
response.status(.badRequest)
next()
}
}
}
// Get w/Query Parameters with CodableResultClosure
fileprivate func getSafely<Q: QueryParams, O: Codable>(_ route: String, handler: @escaping (Q, @escaping CodableResultClosure<O>) -> Void) {
registerGetRoute(route: route, queryParams: Q.self, optionalQParam: false, outputType: O.self)
get(route) { request, response, next in
Log.verbose("Received GET (singular) type-safe request with Query Parameters")
Log.verbose("Query Parameters: \(request.queryParameters)")
// Define result handler
do {
let query: Q = try QueryDecoder(dictionary: request.queryParameters).decode(Q.self)
handler(query, CodableHelpers.constructOutResultHandler(response: response, completion: next))
} catch {
// Http 400 error
response.status(.badRequest)
next()
}
}
}
// Get w/Optional Query Parameters
fileprivate func getSafely<Q: QueryParams, O: Codable>(_ route: String, handler: @escaping (Q?, @escaping CodableArrayResultClosure<O>) -> Void) {
registerGetRoute(route: route, queryParams: Q.self, optionalQParam: true, outputType: O.self)
get(route) { request, response, next in
Log.verbose("Received GET (plural) type-safe request with Query Parameters")
Log.verbose("Query Parameters: \(request.queryParameters)")
do {
var query: Q? = nil
let queryParameters = request.queryParameters
if queryParameters.count > 0 {
query = try QueryDecoder(dictionary: queryParameters).decode(Q.self)
}
handler(query, CodableHelpers.constructOutResultHandler(response: response, completion: next))
} catch {
// Http 400 error
response.status(.badRequest)
next()
}
}
}
// Get w/Optional Query Parameters with CodableResultClosure
fileprivate func getSafely<Q: QueryParams, O: Codable>(_ route: String, handler: @escaping (Q?, @escaping CodableResultClosure<O>) -> Void) {
registerGetRoute(route: route, queryParams: Q.self, optionalQParam: true, outputType: O.self)
get(route) { request, response, next in
Log.verbose("Received GET (singular) type-safe request with Query Parameters")
Log.verbose("Query Parameters: \(request.queryParameters)")
// Define result handler
do {
var query: Q? = nil
let queryParameters = request.queryParameters
if queryParameters.count > 0 {
query = try QueryDecoder(dictionary: queryParameters).decode(Q.self)
}
handler(query, CodableHelpers.constructOutResultHandler(response: response, completion: next))
} catch {
// Http 400 error
response.status(.badRequest)
next()
}
}
}
// GET single identified element
fileprivate func getSafely<Id: Identifier, O: Codable>(_ route: String, handler: @escaping IdentifierSimpleCodableClosure<Id, O>) {
if !pathSyntaxIsValid(route, identifierExpected: true) {
return
}
registerGetRoute(route: route, id: Id.self, outputType: O.self)
get(join(path: route, with: ":id")) { request, response, next in
Log.verbose("Received GET (singular with identifier) type-safe request")
guard let identifier = CodableHelpers.parseIdOrSetResponseStatus(Id.self, from: request, response: response) else {
next()
return
}
handler(identifier, CodableHelpers.constructOutResultHandler(response: response, completion: next))
}
}
// DELETE
fileprivate func deleteSafely(_ route: String, handler: @escaping NonCodableClosure) {
if !pathSyntaxIsValid(route, identifierExpected: false) {
return
}
registerDeleteRoute(route: route)
delete(route) { request, response, next in
Log.verbose("Received DELETE (plural) type-safe request")
handler(CodableHelpers.constructResultHandler(response: response, completion: next))
}
}
// DELETE single element
fileprivate func deleteSafely<Id: Identifier>(_ route: String, handler: @escaping IdentifierNonCodableClosure<Id>) {
if !pathSyntaxIsValid(route, identifierExpected: true) {
return
}
registerDeleteRoute(route: route, id: Id.self)
delete(join(path: route, with: ":id")) { request, response, next in
Log.verbose("Received DELETE (singular) type-safe request")
guard let identifier = CodableHelpers.parseIdOrSetResponseStatus(Id.self, from: request, response: response) else {
next()
return
}
handler(identifier, CodableHelpers.constructResultHandler(response: response, completion: next))
}
}
// DELETE w/Query Parameters
fileprivate func deleteSafely<Q: QueryParams>(_ route: String, handler: @escaping (Q, @escaping ResultClosure) -> Void) {
registerDeleteRoute(route: route, queryParams: Q.self, optionalQParam: false)
delete(route) { request, response, next in
Log.verbose("Received DELETE type-safe request with Query Parameters")
Log.verbose("Query Parameters: \(request.queryParameters)")
do {
let query: Q = try QueryDecoder(dictionary: request.queryParameters).decode(Q.self)
handler(query, CodableHelpers.constructResultHandler(response: response, completion: next))
} catch {
// Http 400 error
response.status(.badRequest)
next()
}
}
}
// DELETE w/Optional Query Parameters
fileprivate func deleteSafely<Q: QueryParams>(_ route: String, handler: @escaping (Q?, @escaping ResultClosure) -> Void) {
registerDeleteRoute(route: route, queryParams: Q.self, optionalQParam: true)
delete(route) { request, response, next in
Log.verbose("Received DELETE type-safe request with Query Parameters")
Log.verbose("Query Parameters: \(request.queryParameters)")
do {
var query: Q? = nil
let queryParameters = request.queryParameters
if queryParameters.count > 0 {
query = try QueryDecoder(dictionary: queryParameters).decode(Q.self)
}
handler(query, CodableHelpers.constructResultHandler(response: response, completion: next))
} catch {
// Http 400 error
response.status(.badRequest)
next()
}
}
}
func pathSyntaxIsValid(_ path: String, identifierExpected: Bool) -> Bool {
let identifierSupplied = path.contains(":")
switch (identifierExpected, identifierSupplied) {
case (false, true):
Log.error("Path '\(path)' is not allowed: Codable routes do not allow path parameters.")
return false
case (true, false):
Log.warning("Identifier expected for '\(path)'. :id will be automatically appended to the path.")
return true
case (true, true):
/// Precondition: Path is known to contain a : character
func pathHasSingleParamIdAsSuffix(_ path: String) -> Bool {
let pathArray = path.split(separator: ":", maxSplits: 1)
if pathArray.count > 1 {
return parameter == "id"
}
return false
}
guard pathHasSingleParamIdAsSuffix(path) else {
Log.error("Erroneous path '\(path)' is not allowed. Codable routes support a trailing id parameter only.")
return false
}
return true
case (false, false):
return true
}
}
internal func join(path base: String, with component: String) -> String {
let strippedBase = base.hasSuffix("/") ? String(base.dropLast()) : base
let strippedComponent = component.hasPrefix("/") ? String(component.dropFirst()) : component
return "\(strippedBase)/\(strippedComponent)"
}
}
//
// Building blocks for Codable routing
//
public struct CodableHelpers {
/**
* Check if the given request has content type JSON
*
* - Parameter request: The RouterRequest to check
* - Returns: True if the content type of the request is application/json, false otherwise
*/
public static func isContentTypeJSON(_ request: RouterRequest) -> Bool {
// FIXME: This should be a simple lookup of content type cached on the RouterRequest
guard let contentType = request.headers["Content-Type"] else {
return false
}
return contentType.hasPrefix("application/json")
}
/**
* Check if the given request has content type x-www-form-urlencoded
*
* - Parameter request: The RouterRequest to check
* - Returns: True if the content type of the request is application/x-www-form-urlencoded, false otherwise
*/
public static func isContentTypeURLEncoded(_ request: RouterRequest) -> Bool {
// FIXME: This should be a simple lookup of content type cached on the RouterRequest
guard let contentType = request.headers["Content-Type"] else {
return false
}
return contentType.hasPrefix("application/x-www-form-urlencoded")
}
/**
* Get the HTTPStatusCode corresponding to the provided RequestError
*
* - Parameter from: The RequestError to map to a HTTPStatusCode
* - Returns: A HTTPStatusCode corresponding to the RequestError http code
* if valid, or HTTPStatusCode.unknown otherwise
*/
public static func httpStatusCode(from error: RequestError) -> HTTPStatusCode {
// ORM status code 7XX mapped to internalServerError 500
if error.httpCode >= 700 && error.httpCode < 800 { return HTTPStatusCode.internalServerError }
return HTTPStatusCode(rawValue: error.rawValue) ?? HTTPStatusCode.unknown
}
/**
* Create a closure that can be called by a codable route handler that
* provides only an optional `RequestError`
*
* - Note: This function is intended for use by the codable router or extensions
* thereof. It will create a closure that can be passed to the registered
* route handler.
*
* - Parameter response: The `RouterResponse` to which the codable response error and
* status code will be written
* - Parameter completion: The completion to be called after the returned
* closure completes execution.
* - Returns: The closure to pass to the codable route handler. The closure takes one argument
* `(RequestError?)`.
* If the argument is `nil` then the response will be considered successful, otherwise
* it will be considered failed.
*
* If successful, the HTTP status code will be set to `HTTPStatusCode.noContent` and no
* body will be sent.
*
* If failed, the HTTP status code used for the response will be set to either the
* `httpCode` of the `RequestError`, if that is a valid HTTP status code, or
* `HTTPStatusCode.unknown` otherwise. If the `RequestError` has a codable `body` then
* it will be encoded and sent as the body of the response.
*/
public static func constructResultHandler(response: RouterResponse, completion: @escaping () -> Void) -> ResultClosure {
return { error in
if let error = error {
response.status(httpStatusCode(from: error))
do {
if let bodyData = try error.encodeBody(.json) {
response.headers.setType("json")
response.send(data: bodyData)
}
} catch {
Log.error("Could not encode error: \(error)")
response.status(.internalServerError)
}
} else {
response.status(.noContent)
}
completion()
}
}
/**
* Create a closure that can be called by a codable route handler that
* provides an optional `Codable` body and an optional `RequestError`
*
* - Note: This function is intended for use by the codable router or extensions
* thereof. It will create a closure that can be passed to the registered
* route handler.
*
* - Parameter successStatus: The `HTTPStatusCode` to use for a successful response (see below)
* - Parameter response: The `RouterResponse` to which the codable response body (or codable
* error) and status code will be written
* - Parameter completion: The completion to be called after the returned
* closure completes execution.
* - Returns: The closure to pass to the codable route handler. The closure takes two arguments
* `(OutputType?, RequestError?)`.
* If the second (error) argument is `nil` then the first (body) argument should be non-`nil`
* and the response will be considered successful. If the second (error) argument is non-`nil`
* then the first argument is ignored and the response is considered failed.
*
* If successful, the HTTP status code will be set to `successStatus` and the `CodableResultClosure` output
* will be JSON encoded and sent as the body of the response.
*
* If failed, the HTTP status code used for the response will be set to either the
* `httpCode` of the `RequestError`, if that is a valid HTTP status code, or
* `HTTPStatusCode.unknown` otherwise. If the `RequestError` has a codable `body` then
* it will be encoded and sent as the body of the response.
*/
public static func constructOutResultHandler<OutputType: Codable>(successStatus: HTTPStatusCode = .OK, response: RouterResponse, completion: @escaping () -> Void) -> CodableResultClosure<OutputType> {
return { codableOutput, error in
var status = successStatus
if let error = error {
status = httpStatusCode(from: error)
}
response.status(status)
if status.class != .successful, let error = error {
do {
if let bodyData = try error.encodeBody(.json) {
response.headers.setType("json")
response.send(data: bodyData)
}
} catch {
Log.error("Could not encode error: \(error)")
response.status(.internalServerError)
}
} else {
if let codableOutput = codableOutput {
response.send(codableOutput)
} else {
Log.debug("Note: successful response ('\(status)') delivers no data.")
}
}
completion()
}
}
/**
* Create a closure that can be called by a codable route handler that
* provides an array of tuples of (Identifier, Codable) and an optional `RequestError`
*
* - Note: This function is intended for use by the codable router or extensions
* thereof. It will create a closure that can be passed to the registered
* route handler.
*
* - Parameter successStatus: The `HTTPStatusCode` to use for a successful response (see below)
* - Parameter response: The `RouterResponse` to which the codable response body (or codable
* error) and status code will be written
* - Parameter completion: The completion to be called after the returned
* closure completes execution.
* - Returns: The closure to pass to the codable route handler. The closure takes two arguments
* `([(Id, OutputType)]?, RequestError?)`.
* If the second (error) argument is `nil` then the first argument (body) should be non-`nil`
* and the response will be considered successful. If the second (error) argument is non-`nil`
* then the first argument is ignored and the response is considered failed.
*
* If successful, the HTTP status code will be set to `successStatus` and the `IdentifierCodableArrayResultClosure` output
* will be JSON encoded as an array of dictionaries, which is then sent as the body of the response.
*
* If failed, the HTTP status code used for the response will be set to either the
* `httpCode` of the `RequestError`, if that is a valid HTTP status code, or
* `HTTPStatusCode.unknown` otherwise. If the `RequestError` has a codable `body` then
* it will be encoded and sent as the body of the response.
*/
public static func constructTupleArrayOutResultHandler<Id: Identifier, OutputType: Codable>(successStatus: HTTPStatusCode = .OK, response: RouterResponse, completion: @escaping () -> Void) -> IdentifierCodableArrayResultClosure<Id, OutputType> {
return { codableOutput, error in
var status = successStatus
if let error = error {
status = httpStatusCode(from: error)
}
response.status(status)
if status.class != .successful, let error = error {
do {
if let bodyData = try error.encodeBody(.json) {
response.headers.setType("json")
response.send(data: bodyData)
}
} catch {
Log.error("Could not encode error: \(error)")
response.status(.internalServerError)
}
} else {
if let codableOutput = codableOutput {
let entries = codableOutput.map({ [$0.value: $1] })
response.send(entries)
} else {
Log.debug("Note: successful response ('\(status)') delivers no data.")
}
}
completion()
}
}
/**
* Create a closure that can be called by a codable route handler that
* provides an optional `Identifier` id, optional `Codable` body and an optional `RequestError`
*
* - Note: This function is intended for use by the codable router or extensions
* thereof. It will create a closure that can be passed to the registered
* route handler.
*
* - Parameter successStatus: The `HTTPStatusCode` to use for a successful response (see below)
* - Parameter response: The `RouterResponse` to which the id, codable response body (or codable
* error) and status code will be written
* - Parameter completion: The completion to be called after the returned
* closure completes execution.
* - Returns: The closure to pass to the codable route handler. The closure takes three arguments
* `(IdType?, OutputType?, RequestError?)`.
* If the third (error) argument is `nil` then the first (id) and second (body) arguments
* should both be non-`nil` and the response will be considered successful. If the third
* (error) argument is non-`nil` then the first and second arguments are ignored and the
* response is considered failed.
*
* If successful, the HTTP status code will be set to `successStatus`, the `IdentifierCodableResultClosure` output
* will be JSON encoded and sent as the body of the response, and the `Location` header of the
* response will be set to the id (by converting it to a `String` using its `value` property).
*
* If failed, the HTTP status code used for the response will be set to either the
* `httpCode` of the `RequestError`, if that is a valid HTTP status code, or
* `HTTPStatusCode.unknown` otherwise. If the `RequestError` has a codable `body` then
* it will be encoded and sent as the body of the response.
*/
public static func constructIdentOutResultHandler<IdType: Identifier, OutputType: Codable>(successStatus: HTTPStatusCode = .OK, response: RouterResponse, completion: @escaping () -> Void) -> IdentifierCodableResultClosure<IdType, OutputType> {
return { id, codableOutput, error in
var status = successStatus
if let error = error {
status = httpStatusCode(from: error)
}
response.status(status)
if status.class != .successful, let error = error {
do {
if let bodyData = try error.encodeBody(.json) {
response.headers.setType("json")
response.send(data: bodyData)
}
} catch {
Log.error("Could not encode error: \(error)")
response.status(.internalServerError)
}
} else if let id = id {
response.headers["Location"] = String(id.value)
if let codableOutput = codableOutput {
response.send(codableOutput)
} else {
Log.debug("Note: successful response ('\(status)') delivers no data.")
}
} else {
Log.error("No id (unique identifier) value provided.")
response.status(.internalServerError)
}
completion()
}
}
/**
* Read data from the request body and decode as the given `InputType`, setting an error
* status on the given response in the case of failure.
*
* - Note: This function is intended for use by the codable router or extensions
* thereof. It will read the codable input object from the request that can be passed
* to a codable route handler.
*
* - Parameter inputCodableType: The `InputType.Type` (a concrete type complying to `Codable`)
* to use to represent the decoded body data.
* - Parameter request: The `RouterRequest` from which to read the body data.
* - Parameter response: The `RouterResponse` on which to set any error HTTP status codes in
* cases where reading or decoding the data fails.
* - Returns: An instance of `InputType` representing the decoded body data.
*/
public static func readCodableOrSetResponseStatus<InputType: Codable>(_ inputCodableType: InputType.Type, from request: RouterRequest, response: RouterResponse) -> InputType? {
guard request.decoder != nil else {
response.status(.unsupportedMediaType)
return nil
}
guard !request.hasBodyParserBeenUsed else {
Log.error("No data in request. Codable routes do not allow the use of BodyParser.")
response.status(.internalServerError)
return nil
}
do {
return try request.read(as: InputType.self)
} catch {
Log.error("Failed to read Codable input from request: \(error)")
response.status(.unprocessableEntity)
if let decodingError = error as? DecodingError {
response.send("Could not decode received data: \(decodingError.humanReadableDescription)")
} else {
// Linux Swift does not send a DecodingError when the JSON is invalid, instead it sends Error "The operation could not be completed"
response.send("Could not decode received data.")
}
return nil
}
}
/**
* Read an id from the request URL, setting an error status on the given response in the case of failure.
*
* - Note: This function is intended for use by the codable router or extensions
* thereof. It will read and id from the request that can be passed
* to a codable route handler.
*
* - Parameter idType: The `IdType.Type` (a concrete type complying to `Identifier`) to use
* to represent the id.
* - Parameter request: The `RouterRequest` from which to read the URL.
* - Parameter response: The `RouterResponse` on which to set any error HTTP status codes in
* cases where reading or decoding the data fails.
* - Returns: An instance of `IdType` representing the id.
*/
public static func parseIdOrSetResponseStatus<IdType: Identifier>(_ idType: IdType.Type, from request: RouterRequest, response: RouterResponse) -> IdType? {
guard let idParameter = request.parameters["id"],
let id = try? IdType(value: idParameter)
else {
// TODO: Should this be .notFound?
response.status(.unprocessableEntity)
return nil
}
return id
}
}
//extension Router {
// // CRUD API codable routing
// // (URL path and HTTP verb are inferred by the framework)
// public func register<I: Persistable>(api: I.Type) {
// api.registerHandlers(router: self)
// Log.verbose("Registered API: \(api)")
// }
//}
// Persistable extension
//extension Persistable {
// static func registerHandlers(router: Router) {
// router.postSafely(route, handler: self.create)
// Log.verbose("Registered POST for: \(self)")
//
// // Register update
// router.putSafely(route, handler: self.update)
// Log.verbose("Registered PUT for: \(self)")
//
// // Register read ALL
// router.getSafely(route, handler: self.read as Router.CodableArrayClosure)
// Log.verbose("Registered GET for: \(self)")
//
// // Register read Single
// router.getSafely(route, handler: self.read as Router.IdentifierSimpleCodableClosure)
// Log.verbose("Registered single GET for: \(self)")
//
// // Register delete all
// router.deleteSafely(route, handler: self.delete as Router.NonCodableClosure)
// Log.verbose("Registered DELETE for: \(self)")
//