用Node.js和Apollo Server搭建GraphQL API

用Node.js和Apollo Server搭建GraphQL API

引言

GraphQL以其灵活的查询能力和类型系统成为现代API开发的热门选择。本文将指导你用Node.js和Apollo Server搭建一个简单的GraphQL API,涵盖schema设计、resolver实现和查询优化。

环境搭建

安装依赖:npm install apollo-server graphql

定义Schema

schema.graphql中定义类型:

1
2
3
4
5
6
7
8
9
10
type User {
id: ID!
name: String!
email: String!
}

type Query {
user(id: ID!): User
users: [User!]!
}

实现Resolvers

index.js中实现查询逻辑:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
const { ApolloServer, gql } = require('apollo-server');
const fs = require('fs');

const typeDefs = gql(fs.readFileSync('./schema.graphql', { encoding: 'utf8' }));

const users = [
{ id: '1', name: 'Alice', email: 'alice@example.com' },
{ id: '2', name: 'Bob', email: 'bob@example.com' },
];

const resolvers = {
Query: {
user: (parent, { id }) => users.find(user => user.id === id),
users: () => users,
},
};

const server = new ApolloServer({ typeDefs, resolvers });
server.listen().then(({ url }) => {
console.log(`GraphQL服务运行在 ${url}`);
});

运行:node index.js,访问http://localhost:4000查看GraphQL Playground。

查询优化

1. 避免N+1查询

使用DataLoader批量加载数据:

1
2
3
4
5
6
const DataLoader = require('dataloader');

const userLoader = new DataLoader(async ids => {
const users = await db.queryUsersByIds(ids); // 假设的数据库查询
return ids.map(id => users.find(user => user.id === id));
});

2. 分页查询

实现分页以减少响应数据量:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
type Query {
users(first: Int, after: String): UserConnection!
}

type UserConnection {
edges: [UserEdge!]!
pageInfo: PageInfo!
}

type UserEdge {
node: User!
cursor: String!
}

type PageInfo {
hasNextPage: Boolean!
endCursor: String!
}

注意事项

  • 强类型检查:确保schema定义与resolver一致。
  • 错误处理:使用ApolloError抛出标准错误。
  • 性能监控:集成apollo-tracing分析查询性能。

总结

Apollo Server简化了Node.js中的GraphQL开发,通过清晰的schema和高效的resolver,可以快速构建灵活的API。结合DataLoader和分页优化,能进一步提升性能。希望本文的示例能为你的GraphQL项目提供帮助!