GraphQL is a modern API query language that is widely used in modern web applications because it provides an efficient, flexible and powerful way to obtain data
First, we need to create a GraphQL server. Install graphql-yoga and create a simple GraphQL schema:
npm init -y npm install graphql yoga graphql-yoga # server.js const { GraphQLServer } = require('graphql-yoga'); const typeDefs = ` type Query { hello: String } type Mutation { addMessage(message: String!): String } `; const resolvers = { Query: { hello: () => 'Hello world!', }, Mutation: { addMessage: (_, { message }) => `You added the message "${message}"`, }, }; const server = new GraphQLServer({ typeDefs, resolvers }); server.start(() => console.log(`Server is running on http://localhost:4000`));
Next, we need to configure Apollo Client in the front-end application to communicate with our GraphQL server:
npm install apollo-boost @apollo/client graphql # client.js import ApolloClient from 'apollo-boost'; import { InMemoryCache } from '@apollo/client'; const client = new ApolloClient({ uri: 'http://localhost:4000/graphql', cache: new InMemoryCache(), }); export default client;
Now, we use Apollo Client in the React component to perform queries and mutations:
// App.js import React from 'react'; import { gql, useQuery, useMutation } from '@apollo/client'; import client from './client'; const GET_HELLO = gql` query GetHello { hello } `; const ADD_MESSAGE_MUTATION = gql` mutation AddMessage($message: String!) { addMessage(message: $message) } `; function App() { const { loading, error, data } = useQuery(GET_HELLO); const [addMessage, { data: mutationData }] = useMutation(ADD_MESSAGE_MUTATION); if (loading) return <p>Loading...</p>; if (error) return <p>Error :(</p>; return ( <div> <h1>{data.hello}</h1> <button onClick={() => addMessage({ variables: { message: 'Hello from frontend!' } })}> Add Message </button> {mutationData && <p>New message: {mutationData.addMessage}</p>} </div> ); } export default App;
We create a GET_HELLO query to get the server's greeting and display it on the page. At the same time, we define an ADD_MESSAGE_MUTATION mutation operation, which will send a new message to the server when the user clicks the button.
Start the backend server:
node server.js
Then start the frontend application, assuming Create React App:
npm start
In GraphQL, queries and mutations are strings represented by JSON-like structures. Here is a simple example:
# Query Example query GetUser { user(id: 1) { name email } } # Mutation Example mutation CreateUser { createUser(name: "Alice", email: "alice@example.com") { id name } } # Subscription Example (Assuming WebSocket) subscription OnNewUser { newUser { id name } }
In the above code, the GetUser query requests the name and email of the user with user ID 1. The CreateUser mutation creates a new user and returns the new user's ID and name. The OnNewUser subscription waits for the new user to be created and returns the new user's information.
On the backend, we define a GraphQL schema to describe these types:
type User { id: ID! name: String! email: String! } type Mutation { createUser(name: String!, email: String!): User } type Subscription { newUser: User }
Here we define a User object type, a Mutation type for mutation operations, and a Subscription type for subscription operations.
The query structure consists of fields and parameters. In the query example above, user is the field, and id and email are subfields of the user field. Parameters such as id: 1 are used to customize the query.
GraphQL queries can be nested. Here is a more complex example:
query GetUsersAndPosts { users { id name posts { id title content author { id name } } } }
This query requests all users and their respective posts, which also include information about the author. Hierarchies allow multiple levels of data to be retrieved in one request.
npm init -y npm install graphql yoga graphql-yoga # server.js const { GraphQLServer } = require('graphql-yoga'); const typeDefs = ` type Query { hello: String } type Mutation { addMessage(message: String!): String } `; const resolvers = { Query: { hello: () => 'Hello world!', }, Mutation: { addMessage: (_, { message }) => `You added the message "${message}"`, }, }; const server = new GraphQLServer({ typeDefs, resolvers }); server.start(() => console.log(`Server is running on http://localhost:4000`));
In this React component, we use useQuery to fetch data from a GraphQL server and render information about users and their posts. This is how GraphQL queries, type systems, and hierarchies come into play.
GraphQL Schema Definition Language (SDL) is a language for describing GraphQL schemas. It defines data types, queries, mutations, and directives in a concise, human-readable format.
Define types
First, let's define some basic data types. For example, define a User type and a Post type.
npm install apollo-boost @apollo/client graphql # client.js import ApolloClient from 'apollo-boost'; import { InMemoryCache } from '@apollo/client'; const client = new ApolloClient({ uri: 'http://localhost:4000/graphql', cache: new InMemoryCache(), }); export default client;
Here, the User type has id, username, email fields, and a posts field that links to multiple Posts. The Post type contains id, title, content fields, and an author field that points to the User.
Query root and mutation root
Next, define the GraphQL query root (Query) and mutation root (Mutation) types, which are the entry points for clients to request data and modify data.
// App.js import React from 'react'; import { gql, useQuery, useMutation } from '@apollo/client'; import client from './client'; const GET_HELLO = gql` query GetHello { hello } `; const ADD_MESSAGE_MUTATION = gql` mutation AddMessage($message: String!) { addMessage(message: $message) } `; function App() { const { loading, error, data } = useQuery(GET_HELLO); const [addMessage, { data: mutationData }] = useMutation(ADD_MESSAGE_MUTATION); if (loading) return <p>Loading...</p>; if (error) return <p>Error :(</p>; return ( <div> <h1>{data.hello}</h1> <button onClick={() => addMessage({ variables: { message: 'Hello from frontend!' } })}> Add Message </button> {mutationData && <p>New message: {mutationData.addMessage}</p>} </div> ); } export default App;
In the Query type, we define queries for getting a single user, all users, a single post, and all posts. In the Mutation type, we define operations for creating new users and new posts.
Understanding and using Directives
Directives are instructions in the GraphQL schema that change execution behavior. They can be applied to any part of the type system definition, such as fields, input types, object types, etc. The following shows how to use a custom @auth directive to control access rights.
First, suppose we define an @auth directive to restrict access to certain fields and require users to log in.
node server.js
Next, apply this directive in the schema:
npm start
In the above example, the me query and username field can be accessed without special permissions, but accessing the user's email field requires administrator permissions (specified by the @auth(requires: ADMIN) directive).
Use GraphQL Cursor-based pagination to improve performance and user experience.
Schema definition:
# Query Example query GetUser { user(id: 1) { name email } } # Mutation Example mutation CreateUser { createUser(name: "Alice", email: "alice@example.com") { id name } } # Subscription Example (Assuming WebSocket) subscription OnNewUser { newUser { id name } }
Resolver example:
type User { id: ID! name: String! email: String! } type Mutation { createUser(name: String!, email: String!): User } type Subscription { newUser: User }
Customize error handling to improve the client's ability to handle errors.
Resolver example:
query GetUsersAndPosts { users { id name posts { id title content author { id name } } } }
Create custom directives to implement specific business logic or security requirements.
Schema definition:
import { gql, useQuery } from '@apollo/client'; const GET_USERS_AND_POSTS = gql` query GetUsersAndPosts { users { id name posts { id title content author { id name } } } } `; function App() { const { loading, error, data } = useQuery(GET_USERS_AND_POSTS); if (loading) return <p>Loading...</p>; if (error) return <p>Error :-(</p>; return ( <div> {data.users.map(user => ( <div key={user.id}> <h2>{user.name}</h2> <ul> {user.posts.map(post => ( <li key={post.id}> <h3>{post.title}</h3> <p>{post.content}</p> <p>Author: {post.author.name}</p> </li> ))} </ul> </div> ))} </div> ); } export default App;
Resolver example:
type User { id: ID! username: String! email: String! posts: [Post!]! } type Post { id: ID! title: String! content: String! author: User! }
Make sure to register this directive handler in your GraphQL server configuration.
Federation allows building a single GraphQL API composed of multiple services.
Service A Schema:
npm init -y npm install graphql yoga graphql-yoga # server.js const { GraphQLServer } = require('graphql-yoga'); const typeDefs = ` type Query { hello: String } type Mutation { addMessage(message: String!): String } `; const resolvers = { Query: { hello: () => 'Hello world!', }, Mutation: { addMessage: (_, { message }) => `You added the message "${message}"`, }, }; const server = new GraphQLServer({ typeDefs, resolvers }); server.start(() => console.log(`Server is running on http://localhost:4000`));
Service B Schema:
npm install apollo-boost @apollo/client graphql # client.js import ApolloClient from 'apollo-boost'; import { InMemoryCache } from '@apollo/client'; const client = new ApolloClient({ uri: 'http://localhost:4000/graphql', cache: new InMemoryCache(), }); export default client;
Use GraphQL's field resolver and data loader to optimize performance.
Data Loader example:
// App.js import React from 'react'; import { gql, useQuery, useMutation } from '@apollo/client'; import client from './client'; const GET_HELLO = gql` query GetHello { hello } `; const ADD_MESSAGE_MUTATION = gql` mutation AddMessage($message: String!) { addMessage(message: $message) } `; function App() { const { loading, error, data } = useQuery(GET_HELLO); const [addMessage, { data: mutationData }] = useMutation(ADD_MESSAGE_MUTATION); if (loading) return <p>Loading...</p>; if (error) return <p>Error :(</p>; return ( <div> <h1>{data.hello}</h1> <button onClick={() => addMessage({ variables: { message: 'Hello from frontend!' } })}> Add Message </button> {mutationData && <p>New message: {mutationData.addMessage}</p>} </div> ); } export default App;
The above is the detailed content of Applications and Advantages of GraphQL in Modern Web Applications. For more information, please follow other related articles on the PHP Chinese website!