Consider this Express server setup using GraphQL:
const express = require('express');
const { graphqlHTTP } = require('express-graphql');
const { buildSchema } = require('graphql');
const schema = buildSchema(`
type Query {
hello: String
}
`);
const root = {
hello: () => 'Hello world!'
};
const app = express();
app.use('/graphql', graphqlHTTP({
schema: schema,
rootValue: root,
graphiql: false
}));
app.listen(4000);
If a client sends the query { hello } to /graphql, what is the JSON response?
Remember that GraphQL responses wrap data inside a data field.
The GraphQL server returns the data requested inside a data object. Since the resolver for hello returns 'Hello world!', the response is {"data":{"hello":"Hello world!"}}.
Which of the following code snippets correctly integrates GraphQL middleware into an Express app?
GraphQL middleware is usually added with app.use and takes an options object.
Option C correctly uses app.use with an options object containing schema, rootValue, and graphiql. Option C uses app.get which is not standard for GraphQL middleware. Option C passes arguments incorrectly. Option C uses root instead of rootValue and only listens to POST requests.
You notice your Express server rebuilds the GraphQL schema on every request, causing slow responses. Which approach optimizes this?
Think about expensive operations and how often they should run.
Building the schema is expensive. Doing it once and reusing it improves performance. Building it on every request (option A) slows down the server. Options C and D cause unnecessary overhead.
Given this Express setup:
const express = require('express');
const { graphqlHTTP } = require('express-graphql');
const { buildSchema } = require('graphql');
const schema = buildSchema(`
type Query {
greet: String
}
`);
const root = {
greet: () => 'Hi!'
};
const app = express();
app.get('/graphql', graphqlHTTP({ schema, rootValue: root, graphiql: true }));
app.listen(3000);
When a client sends a POST request to /graphql, the server responds with 404 Not Found. Why?
Check which HTTP methods the middleware is attached to.
The middleware is attached only to GET requests via app.get. POST requests to /graphql are not handled, resulting in 404 errors. Using app.use would handle all HTTP methods.
In Express GraphQL middleware, what does the rootValue option represent?
Think about what resolves the data for queries.
The rootValue is an object that contains resolver functions. These functions provide the data for the fields defined in the GraphQL schema when queries are executed.