GraphQL 在现代 Web 应用程序中的应用和优势

来源:undefined 2025-01-20 01:15:31 1032

GraphQL 作为一种现代 API 查询语言,凭借其高效、灵活和强大的数据获取能力,广泛应用于现代 Web 应用程序。

GraphQL 快速入门示例:

1. 后端配置 (使用 GraphQL Yoga)

首先,搭建 GraphQL 服务器。安装 GraphQL Yoga 并创建一个简单的 GraphQL schema:

1

2

npm init -y

npm install graphql yoga graphql-yoga

登录后复制

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

// 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(`服务器运行在 http://localhost:4000`));

登录后复制
2. 前端配置 (使用 Apollo Client)

接下来,在前端应用中配置 Apollo Client 与 GraphQL 服务器通信:

1

npm install apollo-boost @apollo/client graphql

登录后复制

1

2

3

4

5

6

7

8

9

10

// 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. 编写前端组件

在 React 组件中使用 Apollo Client 执行查询和变更:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

// 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>加载中...</p>;

if (error) return <p>错误 :(</p>;

return (

<div>

<h1>{data.hello}</h1>

<button onClick={() => addMessage({ variables: { message: Hello from frontend! } })}>

添加消息

</button>

{mutationData && <p>新消息: {mutationData.addMessage}</p>}

</div>

);

}

export default App;

登录后复制

我们使用 GET_HELLO 查询获取服务器的问候语,并使用 ADD_MESSAGE_MUTATION 变更在用户点击按钮时向服务器发送新消息。

4. 运行应用

启动后端服务器:

1

node server.js

登录后复制

然后启动前端应用 (假设使用 Create React App):

1

npm start

登录后复制

GraphQL 基本查询

1. 查询语言:查询、变更、订阅

GraphQL 查询和变更使用类似 JSON 的结构表示:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

# 查询示例

query GetUser {

user(id: 1) {

name

email

}

}

# 变更示例

mutation CreateUser {

createUser(name: "Alice", email: "alice@example.com") {

id

name

}

}

# 订阅示例 (假设使用 WebSocket)

subscription OnNewUser {

newUser {

id

name

}

}

登录后复制
2. 类型系统

后端定义 GraphQL schema 描述这些类型:

1

2

3

4

5

6

7

8

9

10

11

12

13

type User {

id: ID!

name: String!

email: String!

}

type Mutation {

createUser(name: String!, email: String!): User

}

type Subscription {

newUser: User

}

登录后复制
3. 查询结构:字段和参数

查询结构由字段和参数组成。

4. 层次结构和嵌套

GraphQL 查询可以嵌套。

客户端代码示例 (使用 Apollo Client) (与快速入门示例类似,此处省略)

GraphQL 架构 (Schema) (内容与输入文本类似,此处省略)

GraphQL 高级应用 (内容与输入文本类似,此处省略)

GraphQL 的特点和优势 (内容与输入文本类似,此处省略)

最新文章