serverless-components / express

âš¡ Take existing Express.js apps and host them easily on cheap, auto-scaling, serverless infrastructure (AWS Lambda and AWS HTTP API).
https://serverless.com/components
Apache License 2.0
375 stars 34 forks source link

Async initialisation strategy #74

Open TreeMan360 opened 3 years ago

TreeMan360 commented 3 years ago

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 commented 3 years ago

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.

vitalii-kyktov commented 3 years ago

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?

mtebele commented 3 years ago

Same issue here. Any workaround?