@@ -11,24 +11,18 @@ struct HelloWorld: Content {
11
11
struct APIGatewayProxyLambda : LambdaHandler {
12
12
typealias Event = APIGatewayRequest
13
13
typealias Output = APIGatewayResponse
14
-
14
+
15
15
init ( context: LambdaInitializationContext ) async throws {
16
16
print ( " Serverless Swift cold started! " )
17
17
18
- Task {
19
- // instanciate the vapor application
20
- let vaporApp = Vapor . Application ( )
21
-
22
- // define the routes for the vapor app
23
- vaporApp. get { req in
18
+ let vaporProxy = VaporProxy . shared
19
+ if !vaporProxy. isRunning ( ) {
20
+ let app = vaporProxy. app
21
+ app. get { req in
24
22
return HelloWorld ( message: " Hello, world! " )
25
23
}
26
-
27
- // run the app locally, so we can proxy to it
28
- let vaporAddress = BindAddress . hostname ( " 127.0.0.1 " , port: 8585 )
29
- vaporApp. http. server. configuration. address = vaporAddress
30
-
31
- try ? vaporApp. run ( )
24
+
25
+ vaporProxy. start ( )
32
26
}
33
27
}
34
28
@@ -37,40 +31,6 @@ struct APIGatewayProxyLambda: LambdaHandler {
37
31
by executing the Vapor application and returning the json response
38
32
*/
39
33
func handle( _ request: APIGatewayRequest , context: LambdaContext ) async throws -> APIGatewayResponse {
40
- // perform an http request to the vapor app
41
- let client = HTTPClient ( )
42
- var url = " http://127.0.0.1:8585 " + request. path
43
- var headers = HTTPHeaders ( )
44
- var body : HTTPClient . Body ?
45
-
46
- let httpMethod = HTTPMethod ( rawValue: request. requestContext. httpMethod)
47
-
48
- if let queryString = request. queryStringParameters {
49
- url += " ? " + queryString. map { " \( $0. key) = \( $0. value) " } . joined ( separator: " & " )
50
- }
51
-
52
- if let bodyString = request. body {
53
- let bodyData = Data ( bodyString. utf8)
54
- body = . byteBuffer( ByteBuffer ( data: bodyData) )
55
- headers. add ( name: " Content-Length " , value: " \( bodyData. count) " )
56
- headers. add ( name: " Content-Type " , value: " application/json " )
57
- }
58
-
59
- for (key, value) in request. headers {
60
- headers. add ( name: key, value: value)
61
- }
62
-
63
- let httpRequest = try HTTPClient . Request ( url: url, method: httpMethod, headers: headers, body: body)
64
- let response = try await client. execute ( request: httpRequest) . get ( )
65
-
66
- let bodyString = response. body!. getString ( at: 0 , length: response. body!. readableBytes)
67
-
68
- var gatewayResponse = APIGatewayResponse ( statusCode: . init( code: response. status. code) )
69
- gatewayResponse. body = bodyString
70
- for (key, value) in response. headers {
71
- gatewayResponse. headers ? [ key] = value
72
- }
73
-
74
- return gatewayResponse
34
+ return try ! await VaporProxy . shared. handle ( request: request)
75
35
}
76
36
}
0 commit comments