question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

apollo-server-lambda v2: expose gateway event and context

See original GitHub issue

Feature Request

Problem

There’re a few usecases I can think of when developing an AWS Lambda with apollo-server where the developer needs access to the original APIGatewayEvent and Context. The current way to develop a lambda in apollo-server v2 is as follows:

exports.graphqlHandler = server.createHandler({
  cors: {
    origin: '*',
    credentials: true
  }
})

create handler takes care of creating the incoming handler that uses the original ApiGatewayEvent and Context. While we can use the context property of ApolloServer for authroization logic to have access to the incoming gateway event and context, there’re some cases where we need the original gateway event before that on the handler level, some of the usecases I can think of is

Usecases

  1. Database connection caching To be more specific with Mongoose the recommended way to cache the db connection is by checking it on the handler level as explained here https://mongoosejs.com/docs/lambda.html

  2. Warming up the lambda to avoid cold starts and skipping execution if its a warmup check To be more specific using the serverless-plugin-warmup to avoid executing the handler if its a warmup request and do an early return.

  3. setting context.callbackWaitsForEmptyEventLoop = false , I believe the created handler by apollo-server already adds this?

  4. other initialisation logic like defining a mongoose/database schema, models, etc…

Current Version

apollo-server-lambda v2.9.3

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:7
  • Comments:8 (1 by maintainers)

github_iconTop GitHub Comments

3reactions
FlorinDavidcommented, Oct 19, 2019

@khaledosman thank you for context.callbackWaitsForEmptyEventLoop = false hint. My lambda function was hanging in browser GET request when I was training to load the playground page. And I think that was because of the asynchronous MongoDB connection time

I avoided to create the handler on every request and to reconnect to MongoDB so I have done something similar to:


const connect = initConnection() // initConnection() will return a promise

const graphQLHandler = server.createHandler()

exports.handler = (event, context, callback) => {
  context.callbackWaitsForEmptyEventLoop = false

  // initConnection will run only once and after that the promise is fulfilled
  connect.then(() => graphQLHandler(event, context, callback))
}

2reactions
khaledosmancommented, Nov 1, 2019

@FlorinDavid Right in mycase I also wanted to share the db connection before hitting graphql’s context to check if the user is authenticated and share him across the resolvers, so I had to do something like this

//handler.js
 connect.then((connection) => graphQLHandler(event, {...context, mongooseConnection: connection}, callback))

then use the db connection in apollo server’s context to have the user or the authentication error accessible from resolvers

//apollo-server.js
 context: async ({ event, context }) => {
    const mongooseConnection = context.mongooseConnection
    try {
      const decodedToken = await validateAuthHeader(event.headers.Authorization)
      // try to retrieve a user with the token
      const User = mongooseConnection.model('User')
      const user = await User.findById(decodedToken._id).lean()
      // add the user to the context
      return { user, mongooseConnection }
    } catch (err) {
      // console.log(err)
      return { mongooseConnection, err }
    }
  },
Read more comments on GitHub >

github_iconTop Results From Across the Web

Deploying with AWS Lambda - Apollo GraphQL Docs
The event object contains the API Gateway event (HTTP headers, HTTP method, body, path, etc.). The context object (not to be confused with...
Read more >
Deploying with AWS Lambda - Apollo GraphQL Docs
This guide explains how to setup Apollo Server 2 to run on AWS Lambda. ... To read information about the current request from...
Read more >
API Reference: ApolloServer - Apollo GraphQL Docs
This article documents the ApolloServer class from the @apollo/server package. You can use the ApolloServer class to create an instance of Apollo Server...
Read more >
API Reference: apollo-server - Apollo GraphQL Docs
This API reference documents the exports from the apollo-server package. class ApolloServer. The core of an Apollo Server implementation.
Read more >
Migrating to Apollo Server 4 - Apollo GraphQL Docs
Below are a few high-level changes for using framework integrations: You can pass your context initialization function directly to your framework's integration ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found