Node.js › GraphQL with Node.js
How would you set up a basic GraphQL server in Node.js using Apollo Server, and what are schema and resolvers?
BeginnerAnswer
A GraphQL server needs a schema (written in GraphQL's Schema Definition Language, describing the available types and operations) and resolvers (functions that actually fetch or compute the data for each field defined in the schema) -- Apollo Server ties these together and handles the HTTP layer, parsing incoming GraphQL queries and invoking the appropriate resolver functions to build the response.
const { ApolloServer, gql } = require('apollo-server');
const typeDefs = gql`
type User { id: ID!, name: String!, email: String! }
type Query { user(id: ID!): User }
`;
const resolvers = {
Query: {
user: async (_, { id }) => db.users.findById(id),
},
};
const server = new ApolloServer({ typeDefs, resolvers });
server.listen().then(({ url }) => console.log(`Server ready at ${url}`));Real-world example A team building a new API for a mobile app chooses GraphQL specifically so the mobile client can request exactly the fields it needs for each screen (like only 'name' and 'avatarUrl' for a list view) in a single request, rather than either over-fetching a full REST resource or needing several separate REST endpoint calls.