@@ -21,32 +21,26 @@ import ServiceLifecycle
21
21
struct LambdaFunction {
22
22
23
23
static func main( ) async throws {
24
+ LambdaFunction ( ) . main ( )
25
+ }
24
26
25
- var logger = Logger ( label: " ServiceLifecycleExample " )
27
+ private let pgClient : PostgresClient
28
+ private var logger : Logger
29
+ private init ( ) throws {
30
+ self . logger = Logger ( label: " ServiceLifecycleExample " )
26
31
logger. logLevel = . trace
27
32
28
- let pgClient = try preparePostgresClient (
33
+ self . pgClient = try preparePostgresClient (
29
34
host: Lambda . env ( " DB_HOST " ) ?? " localhost " ,
30
35
user: Lambda . env ( " DB_USER " ) ?? " postgres " ,
31
36
password: Lambda . env ( " DB_PASSWORD " ) ?? " secret " ,
32
37
dbName: Lambda . env ( " DB_NAME " ) ?? " test "
33
38
)
39
+ }
40
+ private func main( ) {
34
41
35
42
/// Instantiate LambdaRuntime with a closure handler implementing the business logic of the Lambda function
36
- let runtime = LambdaRuntimeService ( logger: logger) { ( event: String , context: LambdaContext ) in
37
-
38
- do {
39
- // Use initialized service within the handler
40
- // IMPORTANT - CURRENTLY WHEN THERE IS AN ERROR, THIS CALL HANGS WHEN DB IS NOT REACHABLE
41
- // https://github.com/vapor/postgres-nio/issues/489
42
- let rows = try await pgClient. query ( " SELECT id, username FROM users " )
43
- for try await (id, username) in rows. decode ( ( Int, String) . self) {
44
- logger. debug ( " \( id) : \( username) " )
45
- }
46
- } catch {
47
- logger. error ( " PG Error: \( error) " )
48
- }
49
- }
43
+ let runtime = LambdaRuntime ( logger: logger, body: handler)
50
44
51
45
/// Use ServiceLifecycle to manage the initialization and termination
52
46
/// of the PGClient together with the LambdaRuntime
@@ -59,9 +53,24 @@ struct LambdaFunction {
59
53
try await serviceGroup. run ( )
60
54
61
55
// perform any cleanup here
56
+
57
+ }
58
+
59
+ private func handler( event: String , context: LambdaContext ) -> String {
60
+ do {
61
+ // Use initialized service within the handler
62
+ // IMPORTANT - CURRENTLY WHEN THERE IS AN ERROR, THIS CALL HANGS WHEN DB IS NOT REACHABLE
63
+ // https://github.com/vapor/postgres-nio/issues/489
64
+ let rows = try await pgClient. query ( " SELECT id, username FROM users " )
65
+ for try await (id, username) in rows. decode ( ( Int, String) . self) {
66
+ logger. debug ( " \( id) : \( username) " )
67
+ }
68
+ } catch {
69
+ logger. error ( " PG Error: \( error) " )
70
+ }
62
71
}
63
72
64
- private static func preparePostgresClient(
73
+ private func preparePostgresClient(
65
74
host: String ,
66
75
user: String ,
67
76
password: String ,
@@ -89,4 +98,4 @@ struct LambdaFunction {
89
98
90
99
return PostgresClient ( configuration: config)
91
100
}
92
- }
101
+ }
0 commit comments