13
13
//===----------------------------------------------------------------------===//
14
14
15
15
import AWSLambdaEvents
16
- import Foundation
16
+ import class Foundation. JSONEncoder
17
+ import class Foundation. JSONDecoder
17
18
18
19
extension APIGateway . V2 . Request {
19
- public func object< T: Codable > ( ) throws -> T {
20
- let decoder = JSONDecoder ( )
20
+
21
+ static private let decoder = JSONDecoder ( )
22
+
23
+ public func bodyObject< T: Codable > ( ) throws -> T {
21
24
guard let body = self . body,
22
25
let dataBody = body. data ( using: . utf8)
23
26
else {
24
27
throw APIError . invalidRequest
25
28
}
26
- return try decoder. decode ( T . self, from: dataBody)
29
+ return try Self . decoder. decode ( T . self, from: dataBody)
27
30
}
28
31
}
29
32
30
33
extension APIGateway . V2 . Response {
31
34
32
- static let defaultHeaders = [
35
+ private static let encoder = JSONEncoder ( )
36
+
37
+ public static let defaultHeaders = [
33
38
" Content-Type " : " application/json " ,
39
+ //Security warning: XSS are enabled
34
40
" Access-Control-Allow-Origin " : " * " ,
35
41
" Access-Control-Allow-Methods " : " OPTIONS,GET,POST,PUT,DELETE " ,
36
42
" Access-Control-Allow-Credentials " : " true " ,
37
43
]
38
44
39
- init ( with error: Error , statusCode: AWSLambdaEvents . HTTPResponseStatus ) {
45
+ public init ( with error: Error , statusCode: AWSLambdaEvents . HTTPResponseStatus ) {
40
46
self . init (
41
47
statusCode: statusCode,
42
48
headers: APIGateway . V2. Response. defaultHeaders,
@@ -46,10 +52,9 @@ extension APIGateway.V2.Response {
46
52
)
47
53
}
48
54
49
- init < Out: Encodable > ( with object: Out , statusCode: AWSLambdaEvents . HTTPResponseStatus ) {
50
- let encoder = JSONEncoder ( )
55
+ public init < Out: Encodable > ( with object: Out , statusCode: AWSLambdaEvents . HTTPResponseStatus ) {
51
56
var body : String = " {} "
52
- if let data = try ? encoder. encode ( object) {
57
+ if let data = try ? Self . encoder. encode ( object) {
53
58
body = String ( data: data, encoding: . utf8) ?? body
54
59
}
55
60
self . init (
@@ -60,13 +65,4 @@ extension APIGateway.V2.Response {
60
65
isBase64Encoded: false
61
66
)
62
67
}
63
-
64
- init < Out: Encodable > ( with result: Result < Out , Error > , statusCode: AWSLambdaEvents . HTTPResponseStatus ) {
65
- switch result {
66
- case . success( let value) :
67
- self . init ( with: value, statusCode: statusCode)
68
- case . failure( let error) :
69
- self . init ( with: error, statusCode: statusCode)
70
- }
71
- }
72
68
}
0 commit comments