express icon indicating copy to clipboard operation
express copied to clipboard

Async initialisation strategy

Open TreeMan360 opened this issue 4 years ago • 3 comments

Hi,

I am trying to correctly boostrap the lambda so that it waits until the server is ready. I am using apollo-server-express to host a GraphQL endpoint.

With an app.ts similar to:

const app = express()

const startApolloServer = async () => {
  const driver = neo4j.driver(
    NEO4J_URL,
    neo4j.auth.basic(NEO4J_USERNAME, NEO4J_PASSWORD)
  )

  const neoSchema = new Neo4jGraphQL({
    typeDefs,
    driver,
  })

  const server = new ApolloServer({
    schema: neoSchema.schema,
    context: ({ req }) => ({ req }),
  })

  await server.start()

  server.applyMiddleware({ app })

  await new Promise((resolve: (reason?: any) => void) =>
    app.listen({ port: 4000 }, resolve)
  )

  console.log(
    `🚀 Server ready at http://localhost:${PORT}${server.graphqlPath}`
  )

  return { server, app }
}

module.exports = app

This works but obviously when there is a cold start the lambda is not initially ready as startApolloServer has not completed.

I need to await startApolloServer() during module initialisation. Everything I have tried has not achieved the desired result. What is the recommended best practice in this scenario?

Thanks, Mark

TreeMan360 avatar Apr 22 '21 09:04 TreeMan360

Looking at the synchronous approach taken here: https://github.com/serverless-components/express/blob/master/src/_express/handler.js

I don't see this being a possibility without a PR / fork.

TreeMan360 avatar Apr 22 '21 09:04 TreeMan360

I am currently got the same case. I'd like to perform async setup before returning app. I am also thinking to fork and to add required logic. Maybe this: https://github.com/dougmoscrop/serverless-http/blob/f72fdeaa0d25844257e01ff1078585a92752f53a/serverless-http.js#L14 could be resolved asynchronously. It could be enough just to move that line into async handler. But then I have some doubts on how to use updated version of serverless-http?

vitalii-kyktov avatar May 09 '21 21:05 vitalii-kyktov

Same issue here. Any workaround?

mtebele avatar Sep 06 '21 17:09 mtebele