GraphQL JavaScript Library (Node.js): Complete Guide
GraphQL is a query language and runtime for APIs, developed by Facebook. In the Node.js ecosystem, the main library for working with GraphQL is the graphql package. It provides all the necessary tools for creating, validating, and executing GraphQL queries. This library is the foundation for popular frameworks such as Apollo Server, Express-GraphQL, and others.
What is GraphQL and why is it needed?
Unlike REST APIs, where each endpoint returns a fixed data structure, GraphQL allows the client to request only the fields it needs. This solves the problems of over-fetching (retrieving unnecessary data) and under-fetching (insufficient data). Key advantages:
- Query flexibility: the client determines which data to retrieve.
- Single entry point: all requests go to one endpoint (e.g.,
/graphql). - Strong typing: the GraphQL schema defines data types and their relationships.
- Introspection: you can automatically generate documentation and testing tools (GraphiQL).
Installing the GraphQL library for Node.js
To get started, install the package via npm or yarn:
npm install graphqlYou will also need an HTTP server, such as express, and middleware like express-graphql (or Apollo Server). However, the graphql library itself is the core.
Creating your first schema and resolver
A schema is a description of data types and available operations (queries, mutations). Resolvers are functions that execute the actual data retrieval logic.
Example of a simple schema with one User type and a user query:
const { graphql, buildSchema } = require('graphql');
// Define the schemaconst schema = buildSchema(` type User { id: ID! name: String email: String }
type Query { user(id: ID!): User }`);
// Data (in a real project — a database)const users = [ { id: '1', name: 'Ivan', email: 'ivan@example.com' }, { id: '2', name: 'Maria', email: 'maria@example.com' }];
// Resolversconst root = { user: ({ id }) => users.find(user => user.id === id)};
// Execute the querygraphql({ schema, source: '{ user(id: "1") { name email } }', rootValue: root}).then(response => { console.log(JSON.stringify(response)); // {"data":{"user":{"name":"Ivan","email":"ivan@example.com"}}}});Data types in GraphQL
The graphql library supports all standard scalar types:
String— a string;Int— an integer;Float— a floating-point number;Boolean— a boolean value;ID— a unique identifier (serialized as a string).
You can also create custom object types, enumerations (enum), lists ([Type]), and non-null fields (Type!).
Mutations and subscriptions
Mutations are used to modify data (analogous to POST/PUT/DELETE in REST). Subscriptions allow you to receive real-time updates via WebSocket.
Example of a mutation for adding a user:
const schema = buildSchema(` type Mutation { addUser(name: String!, email: String!): User }`);
const root = { addUser: ({ name, email }) => { const newUser = { id: String(users.length + 1), name, email }; users.push(newUser); return newUser; }};
// Execute the mutationgraphql({ schema, source: 'mutation { addUser(name: "Petr", email: "petr@example.com") { id name } }', rootValue: root}).then(console.