0
0
GraphQLquery~10 mins

Server middleware in GraphQL - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to add middleware that logs each GraphQL request.

GraphQL
const server = new ApolloServer({ typeDefs, resolvers, [1] });
Drag options to blanks, or click blank then click option'
Aplugins: [loggingPlugin()]
Bmiddlewares: [authMiddleware()]
Ccontext: ({ req }) => ({ user: req.user })
Dintrospection: true
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'middlewares' instead of 'plugins' option.
Adding logging inside 'context' instead of plugins.
2fill in blank
medium

Complete the code to add authentication middleware in the context function.

GraphQL
const server = new ApolloServer({ typeDefs, resolvers, context: ({ req }) => [1] });
Drag options to blanks, or click blank then click option'
A{ user: req.user }
B{ headers: req.headers }
C{ token: req.token }
D{ user: authenticate(req) }
Attempts:
3 left
💡 Hint
Common Mistakes
Returning headers instead of user info.
Accessing a non-existent 'token' property.
3fill in blank
hard

Fix the error in the middleware setup to correctly handle errors.

GraphQL
const errorMiddleware = { requestDidStart() { return { [1](err) { console.error(err); } }; } };
Drag options to blanks, or click blank then click option'
AonError
BdidEncounterError
CdidEncounterErrors
DhandleError
Attempts:
3 left
💡 Hint
Common Mistakes
Using singular 'didEncounterError' instead of plural.
Using non-existent event names like 'onError' or 'handleError'.
4fill in blank
hard

Fill both blanks to create middleware that measures request duration.

GraphQL
const timingPlugin = { requestDidStart() { const start = Date.now(); return { [1]() { const duration = Date.now() [2] start; console.log(`Request took ${duration}ms`); } }; } };
Drag options to blanks, or click blank then click option'
AwillSendResponse
B-
C+
DdidFinish
Attempts:
3 left
💡 Hint
Common Mistakes
Using addition instead of subtraction for duration.
Using wrong lifecycle event names.
5fill in blank
hard

Fill all three blanks to add middleware that modifies the response headers.

GraphQL
const headerPlugin = { requestDidStart() { return { [1](requestContext) { requestContext.response.http.headers.set([2], [3]); } }; } };
Drag options to blanks, or click blank then click option'
AwillSendResponse
B'X-Custom-Header'
C'Processed'
DdidResolveOperation
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong event names like 'didResolveOperation'.
Not using string quotes for header name and value.