Complete the code to add middleware that logs each GraphQL request.
const server = new ApolloServer({ typeDefs, resolvers, [1] });The plugins option is used to add middleware like logging in Apollo Server.
Complete the code to add authentication middleware in the context function.
const server = new ApolloServer({ typeDefs, resolvers, context: ({ req }) => [1] });The context function should return an object with the authenticated user, usually by calling an authenticate function with the request.
Fix the error in the middleware setup to correctly handle errors.
const errorMiddleware = { requestDidStart() { return { [1](err) { console.error(err); } }; } };The correct lifecycle event for error handling in Apollo Server plugins is didEncounterErrors.
Fill both blanks to create middleware that measures request duration.
const timingPlugin = { requestDidStart() { const start = Date.now(); return { [1]() { const duration = Date.now() [2] start; console.log(`Request took ${duration}ms`); } }; } };The willSendResponse event runs before sending the response. Subtracting start from current time gives the duration.
Fill all three blanks to add middleware that modifies the response headers.
const headerPlugin = { requestDidStart() { return { [1](requestContext) { requestContext.response.http.headers.set([2], [3]); } }; } };The willSendResponse event is used to modify headers before sending. The header name and value are set as strings.