Apollo server context initialization function parameter?

Issue

In Apollo server docs, Apollo server constructor run with some configurations, one of them is a context initialization function that is called with every request, and according to the docs, this function parameter is an object that get the request (req) automatically as one field of that object.

const server = new ApolloServer({
  typeDefs,
  resolvers,
  context: ({ req }) => ({
    authScope: getScope(req.headers.authorization)
  }),
});

This is ok for me, but in one project i got from Github that creates a what’s app clone, the parameter object is different which i couldn’t relate, something i searched for and i couldn’t find anything can relate

export const server = new ApolloServer({
  schema: rootModule.schema,
  context: (session: any) => {
    if (session.connection) {
      const req = session.connection.context.session.request;
      const cookies = req.headers.cookie;

      if (cookies) {
        req.cookies = cookie.parse(cookies);
      }
    }

    return rootModule.context(session);
  },
});

The context function parameter is a session object, and the developer need to get the request from that session object using that verbose code:

 const req = session.connection.context.session.request;

I searched about that session parameter but couldn’t find anything in the docs or anywhere else

I am confused about this inconsistency, or am i missing something?

Solution

In general, the actual context object can change dependending on the apollo server configuration (see: https://www.apollographql.com/docs/apollo-server/v2/api/apollo-server#middleware-specific-context-fields)

My guess in the "WhatsApp-clone", the parameter comes from the subscription support of Apollo Server (here as in the github repo from Version 2): https://www.apollographql.com/docs/apollo-server/v2/data/subscriptions/#operation-context

For whatever reason the argument in the example project is called session it is propably that object described in the documentation.

The subscription support is added here to the example server: https://github.com/Urigo/WhatsApp-Clone-Server/blob/master/index.ts#L13

Answered By – Nils Hartmann

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published