{"id":280,"date":"2026-10-10T11:19:32","date_gmt":"2026-10-10T03:19:32","guid":{"rendered":"https:\/\/yykcj.com\/?p=280"},"modified":"2026-10-10T11:19:32","modified_gmt":"2026-10-10T03:19:32","slug":"graphql-api-%e8%ae%be%e8%ae%a1%e4%b8%8e%e5%ae%9e%e7%8e%b0%ef%bc%9a%e4%bb%8e-schema-%e5%88%b0%e7%94%9f%e4%ba%a7%e7%8e%af%e5%a2%83%e7%9a%84%e6%9c%80%e4%bd%b3%e5%ae%9e%e8%b7%b5","status":"publish","type":"post","link":"https:\/\/yykcj.com\/?p=280","title":{"rendered":"GraphQL API \u8bbe\u8ba1\u4e0e\u5b9e\u73b0\uff1a\u4ece Schema \u5230\u751f\u4ea7\u73af\u5883\u7684\u6700\u4f73\u5b9e\u8df5"},"content":{"rendered":"<h2>\u4e3a\u4ec0\u4e48\u9009\u62e9 GraphQL\uff1f<\/h2>\n<p>\u5728 RESTful API \u7edf\u6cbb\u591a\u5e74\u540e\uff0cGraphQL \u4ee5\u5176<strong>\u6309\u9700\u83b7\u53d6\u6570\u636e<\/strong>\u3001<strong>\u5f3a\u7c7b\u578b Schema<\/strong> \u548c<strong>\u5355\u7aef\u70b9<\/strong>\u7684\u7279\u6027\uff0c\u6210\u4e3a\u73b0\u4ee3 API \u8bbe\u8ba1\u7684\u70ed\u95e8\u9009\u62e9\u3002\u4f46\u5f88\u591a\u56e2\u961f\u5728\u843d\u5730\u65f6\uff0c\u5e38\u9677\u5165 N+1 \u67e5\u8be2\u3001\u6743\u9650\u5931\u63a7\u3001\u6027\u80fd\u74f6\u9888\u7b49\u9677\u9631\u3002<\/p>\n<p>\u672c\u6587\u5c06\u4ee5\u4e00\u4e2a\u535a\u5ba2\u7cfb\u7edf\u4e3a\u4f8b\uff0c\u4ece\u96f6\u5f00\u59cb\u8bbe\u8ba1\u5e76\u5b9e\u73b0\u4e00\u4e2a\u751f\u4ea7\u53ef\u7528\u7684 GraphQL API\u3002\u4f60\u5c06\u5b66\u5230\uff1a<\/p>\n<ul>\n<li>\u5982\u4f55\u8bbe\u8ba1\u6e05\u6670\u53ef\u6269\u5c55\u7684 Schema<\/li>\n<li>\u4f7f\u7528 Apollo Server \u5b9e\u73b0 Resolver<\/li>\n<li>\u5229\u7528 DataLoader \u89e3\u51b3 N+1 \u95ee\u9898<\/li>\n<li>\u5206\u9875\u3001\u9519\u8bef\u5904\u7406\u3001\u9274\u6743\u7b49\u5b9e\u6218\u6280\u5de7<\/li>\n<\/ul>\n<p>> \u793a\u4f8b\u4ee3\u7801\u57fa\u4e8e Node.js + Apollo Server 4 + TypeScript\uff0c\u6570\u636e\u5e93\u4f7f\u7528 Prisma + SQLite\uff08\u4fbf\u4e8e\u672c\u5730\u8fd0\u884c\uff09\u3002<\/p>\n<h2>1. \u73af\u5883\u51c6\u5907\u4e0e\u9879\u76ee\u521d\u59cb\u5316<\/h2>\n<p>\u9996\u5148\u521b\u5efa\u9879\u76ee\u5e76\u5b89\u88c5\u4f9d\u8d56\uff1a<\/p>\n<pre><code class=\"language-bash\">\nmkdir graphql-blog &amp;&amp; cd graphql-blog\nnpm init -y\nnpm install @apollo\/server graphql @prisma\/client prisma dataloader\nnpm install -D typescript ts-node @types\/node\nnpx tsc --init\n<\/code><\/pre>\n<p>\u521d\u59cb\u5316 Prisma \u5e76\u5b9a\u4e49\u6570\u636e\u6a21\u578b\uff1a<\/p>\n<pre><code class=\"language-prisma\">\n\/\/ prisma\/schema.prisma\ngenerator client {\n  provider = &quot;prisma-client-js&quot;\n}\n\ndatasource db {\n  provider = &quot;sqlite&quot;\n  url      = &quot;file:.\/dev.db&quot;\n}\n\nmodel User {\n  id    Int    @id @default(autoincrement())\n  name  String\n  email String @unique\n  posts Post[]\n}\n\nmodel Post {\n  id        Int     @id @default(autoincrement())\n  title     String\n  content   String\n  published Boolean @default(false)\n  authorId  Int\n  author    User    @relation(fields: [authorId], references: [id])\n}\n<\/code><\/pre>\n<p>\u8fd0\u884c\u8fc1\u79fb\u5e76\u751f\u6210\u5ba2\u6237\u7aef\uff1a<\/p>\n<pre><code class=\"language-bash\">\nnpx prisma migrate dev --name init\n<\/code><\/pre>\n<h2>2. \u8bbe\u8ba1 GraphQL Schema<\/h2>\n<p>Schema \u662f GraphQL \u7684\u6838\u5fc3\u5951\u7ea6\u3002\u597d\u7684 Schema \u5e94<strong>\u9762\u5411\u4e1a\u52a1\u9886\u57df<\/strong>\uff0c\u800c\u975e\u6570\u636e\u5e93\u8868\u7ed3\u6784\u3002<\/p>\n<pre><code class=\"language-graphql\">\n# src\/schema.graphql\ntype User {\n  id: ID!\n  name: String!\n  email: String!\n  posts: [Post!]!\n}\n\ntype Post {\n  id: ID!\n  title: String!\n  content: String!\n  published: Boolean!\n  author: User!\n}\n\ntype Query {\n  user(id: ID!): User\n  users: [User!]!\n  post(id: ID!): Post\n  posts(published: Boolean, first: Int, after: String): PostConnection!\n}\n\ntype PostConnection {\n  edges: [PostEdge!]!\n  pageInfo: PageInfo!\n}\n\ntype PostEdge {\n  cursor: String!\n  node: Post!\n}\n\ntype PageInfo {\n  hasNextPage: Boolean!\n  endCursor: String\n}\n\ntype Mutation {\n  createPost(input: CreatePostInput!): Post!\n  publishPost(id: ID!): Post!\n}\n\ninput CreatePostInput {\n  title: String!\n  content: String!\n  authorId: ID!\n}\n<\/code><\/pre>\n<p><strong>\u8bbe\u8ba1\u8981\u70b9<\/strong>\uff1a<\/p>\n<ul>\n<li>\u4f7f\u7528 <code>ID<\/code> \u7c7b\u578b\u800c\u975e <code>Int<\/code>\uff0c\u589e\u5f3a\u524d\u7aef\u7075\u6d3b\u6027\u3002<\/li>\n<li>\u5217\u8868\u5b57\u6bb5\u8fd4\u56de <code>[Post!]!<\/code>\uff0c\u660e\u786e\u975e\u7a7a\uff0c\u51cf\u5c11\u5ba2\u6237\u7aef\u5224\u7a7a\u3002<\/li>\n<li>\u5206\u9875\u91c7\u7528 <strong>Relay \u98ce\u683c<\/strong>\u7684 Connection \u6a21\u5f0f\uff0c\u4e3a\u672a\u6765\u6e38\u6807\u5206\u9875\u7559\u51fa\u7a7a\u95f4\u3002<\/li>\n<\/ul>\n<p>\ud83d\udca1 <strong>\u6ce8\u610f<\/strong>\uff1a\u907f\u514d\u5728 Schema \u4e2d\u76f4\u63a5\u66b4\u9732\u6570\u636e\u5e93\u81ea\u589e ID\uff0c\u53ef\u4f7f\u7528\u5168\u5c40\u552f\u4e00 ID\uff08\u5982 <code>Buffer.from('Post:1').toString('base64')<\/code>\uff09\u9632\u6b62\u904d\u5386\u653b\u51fb\u3002<\/p>\n<h2>3. \u5b9e\u73b0 Resolver \u4e0e\u4e0a\u4e0b\u6587<\/h2>\n<p>\u521b\u5efa Apollo Server \u5b9e\u4f8b\uff0c\u5e76\u6ce8\u5165 Prisma \u548c DataLoader \u5230 context\uff1a<\/p>\n<pre><code class=\"language-typescript\">\n\/\/ src\/server.ts\nimport { ApolloServer } from &#x27;@apollo\/server&#x27;;\nimport { startStandaloneServer } from &#x27;@apollo\/server\/standalone&#x27;;\nimport { PrismaClient } from &#x27;@prisma\/client&#x27;;\nimport { readFileSync } from &#x27;fs&#x27;;\nimport { resolvers } from &#x27;.\/resolvers&#x27;;\nimport { createLoaders } from &#x27;.\/loaders&#x27;;\n\nconst prisma = new PrismaClient();\nconst typeDefs = readFileSync(&#x27;.\/src\/schema.graphql&#x27;, &#x27;utf-8&#x27;);\n\nconst server = new ApolloServer({\n  typeDefs,\n  resolvers,\n});\n\nstartStandaloneServer(server, {\n  context: async ({ req }) =&gt; ({\n    prisma,\n    loaders: createLoaders(prisma),\n    user: await getUserFromToken(req.headers.authorization),\n  }),\n}).then(({ url }) =&gt; {\n  console.log(`\ud83d\ude80 Server ready at ${url}`);\n});\n\nasync function getUserFromToken(token?: string) {\n  \/\/ \u7b80\u5316\u793a\u4f8b\uff1a\u5b9e\u9645\u5e94\u9a8c\u8bc1 JWT\n  return token ? { id: 1, name: &#x27;Alice&#x27; } : null;\n}\n<\/code><\/pre>\n<p>\u5b9e\u73b0 Resolver\uff1a<\/p>\n<pre><code class=\"language-typescript\">\n\/\/ src\/resolvers.ts\nimport { PrismaClient } from &#x27;@prisma\/client&#x27;;\nimport { GraphQLError } from &#x27;graphql&#x27;;\n\nexport const resolvers = {\n  Query: {\n    user: (_: any, { id }: { id: string }, { prisma }: { prisma: PrismaClient }) =&gt;\n      prisma.user.findUnique({ where: { id: Number(id) } }),\n    users: (_: any, __: any, { prisma }: { prisma: PrismaClient }) =&gt;\n      prisma.user.findMany(),\n    post: (_: any, { id }: { id: string }, { prisma }: { prisma: PrismaClient }) =&gt;\n      prisma.post.findUnique({ where: { id: Number(id) } }),\n    posts: async (\n      _: any,\n      { published, first = 10, after }: { published?: boolean; first?: number; after?: string },\n      { prisma }: { prisma: PrismaClient }\n    ) =&gt; {\n      const where = published !== undefined ? { published } : {};\n      const cursor = after ? { id: Number(after) } : undefined;\n      const posts = await prisma.post.findMany({\n        where,\n        take: first + 1,\n        cursor,\n        orderBy: { id: &#x27;asc&#x27; },\n      });\n      const hasNextPage = posts.length &gt; first;\n      const edges = posts.slice(0, first).map((post) =&gt; ({\n        cursor: String(post.id),\n        node: post,\n      }));\n      return {\n        edges,\n        pageInfo: {\n          hasNextPage,\n          endCursor: edges.length ? edges[edges.length - 1].cursor : null,\n        },\n      };\n    },\n  },\n  Post: {\n    author: (parent: { authorId: number }, _: any, { loaders }: any) =&gt;\n      loaders.userLoader.load(parent.authorId),\n  },\n  User: {\n    posts: (parent: { id: number }, _: any, { prisma }: { prisma: PrismaClient }) =&gt;\n      prisma.post.findMany({ where: { authorId: parent.id } }),\n  },\n  Mutation: {\n    createPost: async (\n      _: any,\n      { input }: { input: { title: string; content: string; authorId: string } },\n      { prisma, user }: any\n    ) =&gt; {\n      if (!user) {\n        throw new GraphQLError(&#x27;\u672a\u6388\u6743&#x27;, { extensions: { code: &#x27;UNAUTHENTICATED&#x27; } });\n      }\n      return prisma.post.create({\n        data: {\n          title: input.title,\n          content: input.content,\n          authorId: Number(input.authorId),\n        },\n      });\n    },\n    publishPost: async (_: any, { id }: { id: string }, { prisma, user }: any) =&gt; {\n      if (!user) throw new GraphQLError(&#x27;\u672a\u6388\u6743&#x27;, { extensions: { code: &#x27;UNAUTHENTICATED&#x27; } });\n      return prisma.post.update({\n        where: { id: Number(id) },\n        data: { published: true },\n      });\n    },\n  },\n};\n<\/code><\/pre>\n<h2>4. \u4f7f\u7528 DataLoader \u89e3\u51b3 N+1 \u67e5\u8be2<\/h2>\n<p>\u5f53\u67e5\u8be2 <code>posts { author { name } }<\/code> \u65f6\uff0c\u6bcf\u4e2a Post \u90fd\u4f1a\u89e6\u53d1\u4e00\u6b21 <code>user<\/code> \u67e5\u8be2\uff0c\u9020\u6210 N+1\u3002DataLoader \u53ef\u4ee5\u6279\u5904\u7406\u5e76\u7f13\u5b58\u8fd9\u4e9b\u8bf7\u6c42\u3002<\/p>\n<pre><code class=\"language-typescript\">\n\/\/ src\/loaders.ts\nimport DataLoader from &#x27;dataloader&#x27;;\nimport { PrismaClient } from &#x27;@prisma\/client&#x27;;\n\nexport function createLoaders(prisma: PrismaClient) {\n  return {\n    userLoader: new DataLoader&lt;number, any&gt;(async (ids) =&gt; {\n      const users = await prisma.user.findMany({\n        where: { id: { in: ids as number[] } },\n      });\n      const map = new Map(users.map((u) =&gt; [u.id, u]));\n      return ids.map((id) =&gt; map.get(id) || null);\n    }),\n  };\n}\n<\/code><\/pre>\n<p>\ud83d\udca1 <strong>\u6ce8\u610f<\/strong>\uff1aDataLoader \u5b9e\u4f8b\u5fc5\u987b<strong>\u6bcf\u4e2a\u8bf7\u6c42\u521b\u5efa\u4e00\u6b21<\/strong>\uff0c\u5426\u5219\u4f1a\u8de8\u8bf7\u6c42\u7f13\u5b58\u5bfc\u81f4\u6570\u636e\u6cc4\u9732\u3002\u6211\u4eec\u5728 context \u4e2d\u8c03\u7528 <code>createLoaders<\/code> \u6b63\u662f\u4e3a\u6b64\u3002<\/p>\n<h2>5. \u9519\u8bef\u5904\u7406\u4e0e\u9274\u6743<\/h2>\n<p>GraphQL \u7684\u9519\u8bef\u5e94\u901a\u8fc7 <code>extensions.code<\/code> \u63d0\u4f9b\u673a\u5668\u53ef\u8bfb\u7684\u9519\u8bef\u7801\u3002<\/p>\n<pre><code class=\"language-typescript\">\nthrow new GraphQLError(&#x27;\u6587\u7ae0\u4e0d\u5b58\u5728&#x27;, {\n  extensions: { code: &#x27;NOT_FOUND&#x27;, http: { status: 404 } },\n});\n<\/code><\/pre>\n<p>\u5bf9\u4e8e\u5b57\u6bb5\u7ea7\u9274\u6743\uff0c\u53ef\u4ee5\u4f7f\u7528 <strong>schema directive<\/strong> \u6216 <strong>resolver \u4e2d\u95f4\u4ef6<\/strong>\u3002\u7b80\u5355\u573a\u666f\u4e0b\uff0c\u5728 resolver \u4e2d\u5224\u65ad <code>context.user<\/code> \u5373\u53ef\u3002<\/p>\n<pre><code class=\"language-typescript\">\n\/\/ \u793a\u4f8b\uff1a\u4ec5\u4f5c\u8005\u53ef\u5220\u9664\nif (post.authorId !== user.id) {\n  throw new GraphQLError(&#x27;\u65e0\u6743\u64cd\u4f5c&#x27;, { extensions: { code: &#x27;FORBIDDEN&#x27; } });\n}\n<\/code><\/pre>\n<h2>6. \u751f\u4ea7\u73af\u5883\u4f18\u5316\u5efa\u8bae<\/h2>\n<ul>\n<li><strong>\u67e5\u8be2\u6df1\u5ea6\u9650\u5236<\/strong>\uff1a\u4f7f\u7528 <code>graphql-depth-limit<\/code> \u9632\u6b62\u6076\u610f\u5d4c\u5957\u67e5\u8be2\u3002<\/li>\n<li><strong>\u67e5\u8be2\u6210\u672c\u5206\u6790<\/strong>\uff1a\u4f7f\u7528 <code>graphql-cost-analysis<\/code> \u9650\u5236\u590d\u6742\u67e5\u8be2\u3002<\/li>\n<li><strong>\u6301\u4e45\u5316\u67e5\u8be2<\/strong>\uff1a\u5c06\u5e38\u7528\u67e5\u8be2\u54c8\u5e0c\u540e\u5b58\u50a8\uff0c\u51cf\u5c11\u4f20\u8f93\u4e0e\u89e3\u6790\u5f00\u9500\u3002<\/li>\n<li><strong>\u76d1\u63a7<\/strong>\uff1a\u96c6\u6210 Apollo Studio \u6216 OpenTelemetry \u8ffd\u8e2a resolver \u6027\u80fd\u3002<\/li>\n<li><strong>\u7f13\u5b58<\/strong>\uff1a\u5bf9\u516c\u5f00\u6570\u636e\u4f7f\u7528 <code>@cacheControl<\/code> \u6307\u4ee4\u914d\u5408 CDN\u3002<\/li>\n<\/ul>\n<p>\u793a\u4f8b\uff1a\u6dfb\u52a0\u6df1\u5ea6\u9650\u5236<\/p>\n<pre><code class=\"language-typescript\">\nimport depthLimit from &#x27;graphql-depth-limit&#x27;;\n\nconst server = new ApolloServer({\n  typeDefs,\n  resolvers,\n  validationRules: [depthLimit(5)],\n});\n<\/code><\/pre>\n<h2>\u603b\u7ed3<\/h2>\n<p>\u672c\u6587\u4ece Schema \u8bbe\u8ba1\u5230 Resolver \u5b9e\u73b0\uff0c\u518d\u5230 DataLoader \u4f18\u5316\u548c\u9519\u8bef\u5904\u7406\uff0c\u5b8c\u6574\u6f14\u793a\u4e86\u6784\u5efa\u751f\u4ea7\u7ea7 GraphQL API \u7684\u5173\u952e\u6b65\u9aa4\u3002\u8bb0\u4f4f\u51e0\u4e2a\u6838\u5fc3\u539f\u5219\uff1a<\/p>\n<ol>\n<li><strong>Schema \u5373\u5951\u7ea6<\/strong>\uff1a\u9762\u5411\u4e1a\u52a1\u8bbe\u8ba1\uff0c\u800c\u975e\u6570\u636e\u5e93\u6620\u5c04\u3002<\/li>\n<li><strong>\u6279\u5904\u7406\u4e0e\u7f13\u5b58<\/strong>\uff1a\u7528 DataLoader \u6839\u6cbb N+1\u3002<\/li>\n<li><strong>\u5b89\u5168\u4e0e\u6027\u80fd<\/strong>\uff1a\u6df1\u5ea6\u9650\u5236\u3001\u6210\u672c\u5206\u6790\u3001\u9274\u6743\u7f3a\u4e00\u4e0d\u53ef\u3002<\/li>\n<\/ol>\n<p>\u4e0b\u4e00\u6b65\uff0c\u4f60\u53ef\u4ee5\u63a2\u7d22\uff1a<\/p>\n<ul>\n<li>GraphQL Federation \u5b9e\u73b0\u5fae\u670d\u52a1\u805a\u5408<\/li>\n<li>\u4f7f\u7528 GraphQL Code Generator \u751f\u6210\u524d\u7aef\u7c7b\u578b<\/li>\n<li>\u8ba2\u9605\uff08Subscription\uff09\u5b9e\u73b0\u5b9e\u65f6\u66f4\u65b0<\/li>\n<\/ul>\n<p>\u5e0c\u671b\u8fd9\u7bc7\u6559\u7a0b\u80fd\u5e2e\u52a9\u4f60\u5c11\u8e29\u5751\uff0c\u5feb\u901f\u843d\u5730 GraphQL\uff01<\/p>\n","protected":false},"excerpt":{"rendered":"<p>\u672c\u6587\u901a\u8fc7\u4e00\u4e2a\u535a\u5ba2\u7cfb\u7edf\u6848\u4f8b\uff0c\u624b\u628a\u624b\u6559\u4f60\u8bbe\u8ba1 GraphQL Schema\u3001\u5b9e\u73b0 Resolver\u3001\u4f18\u5316 N+1 \u67e5\u8be2\uff0c\u5e76\u5206\u4eab\u751f\u4ea7\u73af\u5883\u4e2d\u7684\u5b9e\u7528\u6280\u5de7\u3002\u8bfb\u5b8c\u4f60\u5c06\u80fd\u72ec\u7acb\u6784\u5efa\u9ad8\u6027\u80fd\u7684 GraphQL API\u3002<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3,4],"tags":[266,265,261,5,123,6],"class_list":["post-280","post","type-post","status-publish","format-standard","hentry","category-3","category-4","tag-api-","tag-apollo-server","tag-graphql","tag-node-js","tag-prisma","tag-6"],"_links":{"self":[{"href":"https:\/\/yykcj.com\/index.php?rest_route=\/wp\/v2\/posts\/280","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/yykcj.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/yykcj.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/yykcj.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/yykcj.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=280"}],"version-history":[{"count":0,"href":"https:\/\/yykcj.com\/index.php?rest_route=\/wp\/v2\/posts\/280\/revisions"}],"wp:attachment":[{"href":"https:\/\/yykcj.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=280"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/yykcj.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=280"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/yykcj.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=280"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}