With apollo-server-lambda 2.0 I am unable to get any code to run after the lambda callback. My use case for this is to disconnect my local MongoDB so connections don't pile up during local development. In production the connection is created outside the handler per: https://www.mongodb.com/blog/post/optimizing-aws-lambda-performance-with-mongodb-atlas-and-nodejs
In 1.x this was possible by using graphqlLambda from apollo-server-lambda like this:
export async function lambdaHandler(event, lambdaContext, callback) {
function callbackFilter(error, output) {
output.headers = output.headers || {};
output.headers["Access-Control-Allow-Origin"] = "*";
callback(error, output);
}
// Performance optimization Step 2: set context.callbackWaitsForEmptyEventLoop to false to prevent the Lambda
// function from waiting for all resources (such as the database connection) to be released before returning it
lambdaContext.callbackWaitsForEmptyEventLoop = false;
const connection = await getCachedConnection();
const context = await getContext(event);
const handler = graphqlLambda({ schema: myGraphQLSchema, context });
return handler(event, lambdaContext, callbackFilter).then(() => {
if (process.env.NODE_ENV === "development") connection.disconnect();
});
}
Now with v2 there is more abstraction above graphqlLambda with createHandler but no way to get anything to run after the callback. Perhaps the best course would be to add a hook option under createHandler to run any needed function after the callback for situations like this?
Open to thoughts / opinions.
Hi,
I am facing same situation, kindly provide a way to create database connection before running actual lambda/graphql code and also a hook to close connection on completion.
Having the same issue. Would it be possible to apply middleware so that we can handle connection closing before we respond back?
also need to be able to add this property before the callback callbackWaitsForEmptyEventLoop = false; This property is essential for an RDS connection or else it's timing out. I had to downgrade to 1.x to make this work. Thanks!
@ekdev2
When you create your server, you should be able to set callbackWaitsForEmptyEventLoop
const server = new ApolloServer({
context: ({ context, event }) => {
context. callbackWaitsForEmptyEventLoop = false;
}
})
@Prefinem Thanks it worked!
Closing this issue now since it sounds like @Prefinem's suggestion worked. Please reopen if the issue still exists!
Most helpful comment
@Prefinem Thanks it worked!