apollo-server by apollographql/skills
npx skills add https://github.com/apollographql/skills --skill apollo-serverApollo Server 是一款开源 GraphQL 服务器,可与任何 GraphQL 模式配合使用。Apollo Server 5 与框架无关,可独立运行或与 Express、Fastify 和无服务器环境集成。
npm install @apollo/server graphql
如需集成 Express:
npm install @apollo/server @as-integrations/express5 express graphql cors
const typeDefs = `#graphql
type Book {
title: String
author: String
}
type Query {
books: [Book]
}
`;
const resolvers = {
Query: {
books: () => [
{ title: "The Great Gatsby", author: "F. Scott Fitzgerald" },
{ title: "1984", author: "George Orwell" },
],
},
};
独立运行(推荐用于原型开发):
独立服务器非常适合原型开发,但对于生产服务,我们建议将 Apollo Server 与功能更全面的 Web 框架(如 Express、Koa 或 Fastify)集成。后期从独立服务器切换到 Web 框架非常简单。
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
import { ApolloServer } from "@apollo/server";
import { startStandaloneServer } from "@apollo/server/standalone";
const server = new ApolloServer({ typeDefs, resolvers });
const { url } = await startStandaloneServer(server, {
listen: { port: 4000 },
});
console.log(`Server ready at ${url}`);
Express:
import { ApolloServer } from "@apollo/server";
import { expressMiddleware } from "@as-integrations/express5";
import { ApolloServerPluginDrainHttpServer } from "@apollo/server/plugin/drainHttpServer";
import express from "express";
import http from "http";
import cors from "cors";
const app = express();
const httpServer = http.createServer(app);
const server = new ApolloServer({
typeDefs,
resolvers,
plugins: [ApolloServerPluginDrainHttpServer({ httpServer })],
});
await server.start();
app.use(
"/graphql",
cors(),
express.json(),
expressMiddleware(server, {
context: async ({ req }) => ({ token: req.headers.authorization }),
}),
);
await new Promise<void>((resolve) => httpServer.listen({ port: 4000 }, resolve));
console.log("Server ready at http://localhost:4000/graphql");
Int - 32 位整数Float - 双精度浮点数String - UTF-8 字符串Boolean - true/falseID - 唯一标识符(序列化为字符串)type User {
id: ID!
name: String!
email: String
posts: [Post!]!
}
type Post {
id: ID!
title: String!
content: String
author: User!
}
input CreatePostInput {
title: String!
content: String
}
type Query {
user(id: ID!): User
users: [User!]!
}
type Mutation {
createPost(input: CreatePostInput!): Post!
}
enum Status {
DRAFT
PUBLISHED
ARCHIVED
}
interface Node {
id: ID!
}
type Article implements Node {
id: ID!
title: String!
}
解析器遵循以下签名:(parent, args, contextValue, info)
parent : 父解析器的结果(根解析器接收 undefined)
args : 传递给字段的参数
contextValue : 共享的上下文对象(身份验证、数据源等)
info : 字段特定信息和模式详情(很少使用)
const resolvers = { Query: { user: async (_, { id }, { dataSources }) => { return dataSources.usersAPI.getUser(id); }, }, User: { posts: async (parent, , { dataSources }) => { return dataSources.postsAPI.getPostsByAuthor(parent.id); }, }, Mutation: { createPost: async (, { input }, { dataSources, user }) => { if (!user) throw new GraphQLError("Not authenticated"); return dataSources.postsAPI.create({ ...input, authorId: user.id }); }, }, };
上下文是为每个请求创建的,并传递给所有解析器。
interface MyContext {
token?: string;
user?: User;
dataSources: {
usersAPI: UsersDataSource;
postsAPI: PostsDataSource;
};
}
const server = new ApolloServer<MyContext>({
typeDefs,
resolvers,
});
// 独立运行
const { url } = await startStandaloneServer(server, {
context: async ({ req }) => ({
token: req.headers.authorization || "",
user: await getUser(req.headers.authorization || ""),
dataSources: {
usersAPI: new UsersDataSource(),
postsAPI: new PostsDataSource(),
},
}),
});
// Express 中间件
expressMiddleware(server, {
context: async ({ req, res }) => ({
token: req.headers.authorization,
user: await getUser(req.headers.authorization),
dataSources: {
usersAPI: new UsersDataSource(),
postsAPI: new PostsDataSource(),
},
}),
});
特定主题的详细文档:
@defer 和 @streamgraphql 包中的 GraphQLError 处理错误startStandaloneServer 用于原型开发每周安装量
527
代码仓库
GitHub 星标
31
首次出现
2026 年 1 月 23 日
安全审计
安装于
claude-code442
opencode422
codex419
github-copilot410
gemini-cli406
cursor375
Apollo Server is an open-source GraphQL server that works with any GraphQL schema. Apollo Server 5 is framework-agnostic and runs standalone or integrates with Express, Fastify, and serverless environments.
npm install @apollo/server graphql
For Express integration:
npm install @apollo/server @as-integrations/express5 express graphql cors
const typeDefs = `#graphql
type Book {
title: String
author: String
}
type Query {
books: [Book]
}
`;
const resolvers = {
Query: {
books: () => [
{ title: "The Great Gatsby", author: "F. Scott Fitzgerald" },
{ title: "1984", author: "George Orwell" },
],
},
};
Standalone (Recommended for prototyping):
The standalone server is great for prototyping, but for production services, we recommend integrating Apollo Server with a more fully-featured web framework such as Express, Koa, or Fastify. Swapping from the standalone server to a web framework later is straightforward.
import { ApolloServer } from "@apollo/server";
import { startStandaloneServer } from "@apollo/server/standalone";
const server = new ApolloServer({ typeDefs, resolvers });
const { url } = await startStandaloneServer(server, {
listen: { port: 4000 },
});
console.log(`Server ready at ${url}`);
Express:
import { ApolloServer } from "@apollo/server";
import { expressMiddleware } from "@as-integrations/express5";
import { ApolloServerPluginDrainHttpServer } from "@apollo/server/plugin/drainHttpServer";
import express from "express";
import http from "http";
import cors from "cors";
const app = express();
const httpServer = http.createServer(app);
const server = new ApolloServer({
typeDefs,
resolvers,
plugins: [ApolloServerPluginDrainHttpServer({ httpServer })],
});
await server.start();
app.use(
"/graphql",
cors(),
express.json(),
expressMiddleware(server, {
context: async ({ req }) => ({ token: req.headers.authorization }),
}),
);
await new Promise<void>((resolve) => httpServer.listen({ port: 4000 }, resolve));
console.log("Server ready at http://localhost:4000/graphql");
Int - 32-bit integerFloat - Double-precision floating-pointString - UTF-8 stringBoolean - true/falseID - Unique identifier (serialized as String)type User {
id: ID!
name: String!
email: String
posts: [Post!]!
}
type Post {
id: ID!
title: String!
content: String
author: User!
}
input CreatePostInput {
title: String!
content: String
}
type Query {
user(id: ID!): User
users: [User!]!
}
type Mutation {
createPost(input: CreatePostInput!): Post!
}
enum Status {
DRAFT
PUBLISHED
ARCHIVED
}
interface Node {
id: ID!
}
type Article implements Node {
id: ID!
title: String!
}
Resolvers follow the signature: (parent, args, contextValue, info)
parent : Result from parent resolver (root resolvers receive undefined)
args : Arguments passed to the field
contextValue : Shared context object (auth, dataSources, etc.)
info : Field-specific info and schema details (rarely used)
const resolvers = { Query: { user: async (_, { id }, { dataSources }) => { return dataSources.usersAPI.getUser(id); }, }, User: { posts: async (parent, , { dataSources }) => { return dataSources.postsAPI.getPostsByAuthor(parent.id); }, }, Mutation: { createPost: async (, { input }, { dataSources, user }) => { if (!user) throw new GraphQLError("Not authenticated"); return dataSources.postsAPI.create({ ...input, authorId: user.id }); }, }, };
Context is created per-request and passed to all resolvers.
interface MyContext {
token?: string;
user?: User;
dataSources: {
usersAPI: UsersDataSource;
postsAPI: PostsDataSource;
};
}
const server = new ApolloServer<MyContext>({
typeDefs,
resolvers,
});
// Standalone
const { url } = await startStandaloneServer(server, {
context: async ({ req }) => ({
token: req.headers.authorization || "",
user: await getUser(req.headers.authorization || ""),
dataSources: {
usersAPI: new UsersDataSource(),
postsAPI: new PostsDataSource(),
},
}),
});
// Express middleware
expressMiddleware(server, {
context: async ({ req, res }) => ({
token: req.headers.authorization,
user: await getUser(req.headers.authorization),
dataSources: {
usersAPI: new UsersDataSource(),
postsAPI: new PostsDataSource(),
},
}),
});
Detailed documentation for specific topics:
@defer and @stream for large responsesGraphQLError from graphql package for errorsstartStandaloneServer for prototyping onlyWeekly Installs
527
Repository
GitHub Stars
31
First Seen
Jan 23, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
claude-code442
opencode422
codex419
github-copilot410
gemini-cli406
cursor375
agent-browser 浏览器自动化工具 - Vercel Labs 命令行网页操作与测试
136,300 周安装
Gemini图像分割技能 - 基于AI的物体识别与遮罩生成工具
spec-workflow:腾讯云开发技能,结构化开发工作流与EARS需求语法指南
656 周安装
Amazon Aurora DSQL 分布式 SQL 数据库技能 - 无服务器 PostgreSQL 兼容,支持模式管理与迁移
从 NativeWind 迁移到 Uniwind 完整指南:提升 React Native 样式性能与稳定性
656 周安装
Amazon Aurora DSQL 技能:无服务器分布式SQL数据库,支持MCP工具查询与模式管理
合作与业务拓展指南:9位产品负责人教你建立战略伙伴关系,达成业务交易
656 周安装