GraphQL is a query language and runtime for APIs developed by Facebook in 2012 and released publicly in 2015. It provides a more efficient, powerful, and flexible alternative to REST by allowing clients to request exactly the data they need and nothing more.
GraphQL allows clients to define the structure of the response. It solves many of the shortcomings of REST, such as over-fetching or under-fetching of data, and provides a strongly typed schema that serves as a contract between client and server.
mkdir graphql-api
cd graphql-api
npm init -y
npm install express express-graphql 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, GraphQL!'
};
const app = express();
app.use('/graphql', graphqlHTTP({
schema,
rootValue: root,
graphiql: true,
}));
app.listen(4000, () => console.log('Server running on http://localhost:4000/graphql'));
A GraphQL schema defines types, queries, mutations, and subscriptions. It's the backbone of any GraphQL server.
const schema = buildSchema(`
type User {
id: ID
name: String
email: String
}
type Query {
getUser(id: ID!): User
getUsers: [User]
}
type Mutation {
addUser(name: String!, email: String!): User
}
`);
Resolvers are functions that handle the logic for returning data for each field in the schema.
let users = [
{ id: '1', name: 'John Doe', email: 'john@example.com' }
];
const root = {
getUser: ({ id }) => users.find(user => user.id === id),
getUsers: () => users,
addUser: ({ name, email }) => {
const newUser = { id: String(users.length + 1), name, email };
users.push(newUser);
return newUser;
}
};
With GraphiQL enabled, navigate to http://localhost:4000/graphql and try the following:
{
getUser(id: "1") {
name
email
}
}
mutation {
addUser(name: "Jane Doe", email: "jane@example.com") {
id
name
email
}
}
| Feature | GraphQL | REST |
|---|---|---|
| Data Fetching | Client-specified structure | Server-specified structure |
| Endpoints | Single endpoint | Multiple endpoints |
| Versioning | No need for versioning | Often uses URL versioning |
| Over-fetching | None | Common issue |
| Tools | GraphiQL, Apollo | Postman, Swagger |
Allows real-time communication using WebSockets.
input UserInput {
name: String!
email: String!
}
type Mutation {
addUser(input: UserInput): User
}
interface Animal {
name: String!
}
type Dog implements Animal {
name: String!
breed: String!
}
union SearchResult = User | DogGraphQL represents a modern approach to API design that gives clients more power, improves performance, and simplifies server logic. With Node.js, tools like express-graphql and Apollo Server make it easy to get started and scale your GraphQL APIs effectively.
A function passed as an argument and executed later.
Runs multiple instances to utilize multi-core systems.
Reusable blocks of code, exported and imported using require() or import.
nextTick() executes before setImmediate() in the event loop.
Starts a server and listens on specified port.
Node Package Manager β installs, manages, and shares JavaScript packages.
A minimal and flexible web application framework for Node.js.
A stream handles reading or writing data continuously.
It processes asynchronous callbacks and non-blocking I/O operations efficiently.
Node.js is a JavaScript runtime built on Chrome's V8 engine for server-side scripting.
An object representing the eventual completion or failure of an asynchronous operation.
require is CommonJS; import is ES6 syntax (requires transpilation or newer versions).
Use module.exports or exports.functionName.
Variables stored outside the code for configuration, accessed using process.env.
MongoDB, often used with Mongoose for schema management.
Describes project details and manages dependencies and scripts.
Synchronous blocks execution; asynchronous runs in background without blocking.
Allows or restricts resources shared between different origins.
Use try-catch, error events, or middleware for error handling.
Provides file system-related operations like read, write, delete.
Using event-driven architecture and non-blocking I/O.
Functions in Express that execute during request-response cycle.
A set of routes or endpoints to interact with server logic or databases.
Yes, it's single-threaded but handles concurrency using the event loop and asynchronous callbacks.
Middleware to parse incoming request bodies, like JSON or form data.
Copyrights © 2024 letsupdateskills All rights reserved