@@ -21,32 +21,26 @@ import ServiceLifecycle
2121struct LambdaFunction {
2222
2323 static func main( ) async throws {
24+ LambdaFunction ( ) . main ( )
25+ }
2426
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 " )
2631 logger. logLevel = . trace
2732
28- let pgClient = try preparePostgresClient (
33+ self . pgClient = try preparePostgresClient (
2934 host: Lambda . env ( " DB_HOST " ) ?? " localhost " ,
3035 user: Lambda . env ( " DB_USER " ) ?? " postgres " ,
3136 password: Lambda . env ( " DB_PASSWORD " ) ?? " secret " ,
3237 dbName: Lambda . env ( " DB_NAME " ) ?? " test "
3338 )
39+ }
40+ private func main( ) {
3441
3542 /// 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)
5044
5145 /// Use ServiceLifecycle to manage the initialization and termination
5246 /// of the PGClient together with the LambdaRuntime
@@ -59,9 +53,24 @@ struct LambdaFunction {
5953 try await serviceGroup. run ( )
6054
6155 // 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+ }
6271 }
6372
64- private static func preparePostgresClient(
73+ private func preparePostgresClient(
6574 host: String ,
6675 user: String ,
6776 password: String ,
@@ -89,4 +98,4 @@ struct LambdaFunction {
8998
9099 return PostgresClient ( configuration: config)
91100 }
92- }
101+ }
0 commit comments