Complete the code to create a simple REST GET endpoint in Express.
app.[1]('/users', (req, res) => { res.send('User list'); });
The get method defines a REST GET endpoint to fetch data.
Complete the code to define a GraphQL query type in Express using 'graphql' package.
const queryType = new GraphQLObjectType({ name: 'Query', fields: { users: { type: new GraphQLList(GraphQLString), resolve: () => ['Alice', 'Bob'] } } });
const schema = new GraphQLSchema({ [1]: queryType });The query field defines the root query type in a GraphQL schema.
Fix the error in this Express REST route that should respond with JSON data.
app.get('/data', (req, res) => { res.[1]({ message: 'Hello' }); });
The json method sends a JSON response, which is standard for REST APIs.
Fill both blanks to create a GraphQL mutation type and add it to the schema.
const mutationType = new GraphQLObjectType({ name: 'Mutation', fields: { addUser: { type: GraphQLString, args: { name: { type: GraphQLString } }, resolve: (parent, args) => args.[1] } } });
const schema = new GraphQLSchema({ query: queryType, [2]: mutationType });The resolver accesses the argument 'name' to add a user. The schema includes the 'mutation' field for mutations.
Fill all three blanks to create an Express route that handles a GraphQL query using 'express-graphql'.
import express from 'express'; import { graphqlHTTP } from 'express-graphql'; import { GraphQLSchema, GraphQLObjectType, GraphQLString } from 'graphql'; const app = express(); const queryType = new GraphQLObjectType({ name: 'Query', fields: { hello: { type: GraphQLString, resolve: () => 'Hello World' } } }); const schema = new GraphQLSchema({ [1]: queryType }); app.use('/graphql', graphqlHTTP({ schema: schema, [2]: true, [3]: true })); app.listen(4000, () => console.log('Server running'));
The schema needs the 'query' field. The 'graphiql' option enables the GraphiQL UI. The 'pretty' option formats JSON responses nicely.