国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home Web Front-end JS Tutorial Applications and Advantages of GraphQL in Modern Web Applications

Applications and Advantages of GraphQL in Modern Web Applications

Dec 23, 2024 pm 06:58 PM

Applications and Advantages of GraphQL in Modern Web Applications

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

GraphQL basic quick application example:

1. Backend settings (using graphql-yoga)

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`));

2. Front-end setup (using Apollo Client)

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;

3. Write front-end components

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.

4. Run the application

Start the backend server:

node server.js

Then start the frontend application, assuming Create React App:

npm start

GraphQL Basic Queries

1. Query Language: Queries, Mutations, Subscriptions

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.

2. Type System

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.

3. Query structure: fields and parameters

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.

4. Hierarchy and nesting

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.

Client Code Example (Using Apollo Client)

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

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).

GraphQL Advanced Applications

1. Pagination

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
}

2. Error handling

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
      }
    }
  }
}

3. Custom directives

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.

4. GraphQL Federation

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;

5. Complex query optimization

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;

GraphQL Features and Advantages

  • Performance optimization: By obtaining data on demand, network transmission overhead is reduced and page loading speed is improved.
  • Reduce errors: The client defines the query structure, and the server returns the expected shape, reducing errors caused by interface mismatch.
  • Better API design: The strong type system ensures the consistency and correctness of the data, making the API easier to understand and maintain.
  • Client control: The client can decide how much data to obtain and when to obtain it, which improves the user experience.
  • Cache optimization: The client can more easily implement caching strategies based on the returned data structure.
  • Reduce backend complexity: The backend no longer needs to create multiple API endpoints to meet the needs of different clients.

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Why should you place  tags at the bottom of the ? Why should you place tags at the bottom of the ? Jul 02, 2025 am 01:22 AM

PlacingtagsatthebottomofablogpostorwebpageservespracticalpurposesforSEO,userexperience,anddesign.1.IthelpswithSEObyallowingsearchenginestoaccesskeyword-relevanttagswithoutclutteringthemaincontent.2.Itimprovesuserexperiencebykeepingthefocusonthearticl

How to work with dates and times in js? How to work with dates and times in js? Jul 01, 2025 am 01:27 AM

The following points should be noted when processing dates and time in JavaScript: 1. There are many ways to create Date objects. It is recommended to use ISO format strings to ensure compatibility; 2. Get and set time information can be obtained and set methods, and note that the month starts from 0; 3. Manually formatting dates requires strings, and third-party libraries can also be used; 4. It is recommended to use libraries that support time zones, such as Luxon. Mastering these key points can effectively avoid common mistakes.

What is event bubbling and capturing in the DOM? What is event bubbling and capturing in the DOM? Jul 02, 2025 am 01:19 AM

Event capture and bubble are two stages of event propagation in DOM. Capture is from the top layer to the target element, and bubble is from the target element to the top layer. 1. Event capture is implemented by setting the useCapture parameter of addEventListener to true; 2. Event bubble is the default behavior, useCapture is set to false or omitted; 3. Event propagation can be used to prevent event propagation; 4. Event bubbling supports event delegation to improve dynamic content processing efficiency; 5. Capture can be used to intercept events in advance, such as logging or error processing. Understanding these two phases helps to accurately control the timing and how JavaScript responds to user operations.

How can you reduce the payload size of a JavaScript application? How can you reduce the payload size of a JavaScript application? Jun 26, 2025 am 12:54 AM

If JavaScript applications load slowly and have poor performance, the problem is that the payload is too large. Solutions include: 1. Use code splitting (CodeSplitting), split the large bundle into multiple small files through React.lazy() or build tools, and load it as needed to reduce the first download; 2. Remove unused code (TreeShaking), use the ES6 module mechanism to clear "dead code" to ensure that the introduced libraries support this feature; 3. Compress and merge resource files, enable Gzip/Brotli and Terser to compress JS, reasonably merge files and optimize static resources; 4. Replace heavy-duty dependencies and choose lightweight libraries such as day.js and fetch

A definitive JS roundup on JavaScript modules: ES Modules vs CommonJS A definitive JS roundup on JavaScript modules: ES Modules vs CommonJS Jul 02, 2025 am 01:28 AM

The main difference between ES module and CommonJS is the loading method and usage scenario. 1.CommonJS is synchronously loaded, suitable for Node.js server-side environment; 2.ES module is asynchronously loaded, suitable for network environments such as browsers; 3. Syntax, ES module uses import/export and must be located in the top-level scope, while CommonJS uses require/module.exports, which can be called dynamically at runtime; 4.CommonJS is widely used in old versions of Node.js and libraries that rely on it such as Express, while ES modules are suitable for modern front-end frameworks and Node.jsv14; 5. Although it can be mixed, it can easily cause problems.

How to make an HTTP request in Node.js? How to make an HTTP request in Node.js? Jul 13, 2025 am 02:18 AM

There are three common ways to initiate HTTP requests in Node.js: use built-in modules, axios, and node-fetch. 1. Use the built-in http/https module without dependencies, which is suitable for basic scenarios, but requires manual processing of data stitching and error monitoring, such as using https.get() to obtain data or send POST requests through .write(); 2.axios is a third-party library based on Promise. It has concise syntax and powerful functions, supports async/await, automatic JSON conversion, interceptor, etc. It is recommended to simplify asynchronous request operations; 3.node-fetch provides a style similar to browser fetch, based on Promise and simple syntax

How does garbage collection work in JavaScript? How does garbage collection work in JavaScript? Jul 04, 2025 am 12:42 AM

JavaScript's garbage collection mechanism automatically manages memory through a tag-clearing algorithm to reduce the risk of memory leakage. The engine traverses and marks the active object from the root object, and unmarked is treated as garbage and cleared. For example, when the object is no longer referenced (such as setting the variable to null), it will be released in the next round of recycling. Common causes of memory leaks include: ① Uncleared timers or event listeners; ② References to external variables in closures; ③ Global variables continue to hold a large amount of data. The V8 engine optimizes recycling efficiency through strategies such as generational recycling, incremental marking, parallel/concurrent recycling, and reduces the main thread blocking time. During development, unnecessary global references should be avoided and object associations should be promptly decorated to improve performance and stability.

var vs let vs const: a quick JS roundup explainer var vs let vs const: a quick JS roundup explainer Jul 02, 2025 am 01:18 AM

The difference between var, let and const is scope, promotion and repeated declarations. 1.var is the function scope, with variable promotion, allowing repeated declarations; 2.let is the block-level scope, with temporary dead zones, and repeated declarations are not allowed; 3.const is also the block-level scope, and must be assigned immediately, and cannot be reassigned, but the internal value of the reference type can be modified. Use const first, use let when changing variables, and avoid using var.

See all articles