@@ -47,12 +47,21 @@ struct LambdaFunction {
4747 private func main( ) async throws {
4848
4949 // Instantiate LambdaRuntime with a handler implementing the business logic of the Lambda function
50- let runtime = LambdaRuntime ( logger: self . logger, body: self . handler)
50+ let lambdaRuntime = LambdaRuntime ( logger: self . logger, body: self . handler)
51+
52+ // Use a prelude service to execute PG code before setting up the Lambda service
53+ // the PG code will run only once and will create the database schema and populate it with initial data
54+ let preludeService = PreludeService (
55+ service: lambdaRuntime,
56+ prelude: {
57+ try await prepareDatabase ( )
58+ }
59+ )
5160
5261 /// Use ServiceLifecycle to manage the initialization and termination
5362 /// of the PGClient together with the LambdaRuntime
5463 let serviceGroup = ServiceGroup (
55- services: [ self . pgClient, runtime ] ,
64+ services: [ self . pgClient, preludeService ] ,
5665 gracefulShutdownSignals: [ . sigterm] ,
5766 cancellationSignals: [ . sigint] ,
5867 logger: self . logger
@@ -76,12 +85,6 @@ struct LambdaFunction {
7685 // This is why there is a timeout, as suggested Fabian
7786 // See: https://github.com/vapor/postgres-nio/issues/489#issuecomment-2186509773
7887 result = try await timeout ( deadline: . seconds( 3 ) ) {
79- // check if table exists
80- // TODO: ideally, I want to do this once, after serviceGroup.run() is done
81- // but before the handler is called
82- logger. trace ( " Checking database " )
83- try await prepareDatabase ( )
84-
8588 // query users
8689 logger. trace ( " Querying database " )
8790 return try await self . queryUsers ( )
0 commit comments