用 Node.js 写出基于 apollo-server 的最小可运行代码

解读

国内面试官问“最小可运行代码”并不是想听“Hello World”那么简单,而是考察候选人能否在 5 分钟内 给出 可当场跑通、端口可改、热更新、可扩展 的骨架。
常见坑:

  1. 只写 schema 不写 resolver,跑不起来;
  2. 端口写死 4000,与后端现有端口冲突;
  3. 忘记加 type Query 导致启动报错;
  4. 没关 CSRF 或没开 introspection,现场演示 GraphQL Playground 失败;
  5. 用 CommonJS 却写 ESM 语法,Node 18 以下直接报错。

最小 ≠ 最简,而是“能当场 npm start 并通过浏览器访问”。

知识点

  • apollo-server v4 已拆包,必须显式安装 @apollo/server + graphql;
  • startStandaloneServer 是最快启动 HTTP 服务的官方方案,默认带 CORS 与 body-parser;
  • typeDefs 必须包含至少一个 Query 类型,否则 GraphQL 规范校验失败;
  • resolver 函数签名 (parent, args, context, info) 必须写全,国内面试常追问四个参数含义;
  • 端口冲突处理:用 process.env.PORT || 4000 兼容云原生场景;
  • nodemon 是现场演示热更新的潜规则,不写容易被追问“如何不重启服务改代码”;
  • Introspection 在生产默认关闭,本地演示需保持开启,否则 Playground 无法自动获取 Schema。

答案

项目结构(单文件即可,但面试时建议拆目录展示工程化思维):

demo/
 ├─ package.json
 └─ index.js

package.json(锁定版本,避免现场 npm 安装拉垮):

{
  "name": "graphql-minimal-demo",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "dev": "nodemon index.js",
    "start": "node index.js"
  },
  "dependencies": {
    "@apollo/server": "^4.10.0",
    "graphql": "^16.8.1"
  },
  "devDependencies": {
    "nodemon": "^3.0.2"
  }
}

index.js(CommonJS 写法,Node 14+ 通用):

const { ApolloServer } = require('@apollo/server');
const { startStandaloneServer } = require('@apollo/server/standalone');

// 1. 定义 Schema
const typeDefs = `
  type Query {
    hello: String
    user(id: ID!): User
  }

  type User {
    id: ID!
    name: String
  }
`;

// 2. 定义 Resolver
const resolvers = {
  Query: {
    hello: () => 'Hello GraphQL 2025',
    user: (_, { id }) => ({ id, name: `用户${id}` }),
  },
};

// 3. 创建 Server
const server = new ApolloServer({ typeDefs, resolvers });

// 4. 启动 HTTP 监听
(async () => {
  const { url } = await startStandaloneServer(server, {
    listen: { port: process.env.PORT || 4000 },
  });
  console.log(`🚀 Server ready at ${url}`);
})();

运行演示(面试官常让你当场改端口或加字段):

$ npm install
$ npm run dev
# 输出:🚀 Server ready at http://localhost:4000/
# 浏览器打开 http://localhost:4000/ 可进入 Playground

拓展思考

  1. 生产最小骨架还需什么?

    • 把 startStandaloneServer 换成 expressMiddleware 接入现有 Koa/Express 体系,方便统一鉴权、日志、限流;
    • 用 @graphql-tools/schema 拆分模块,解决单体 Schema 过大问题;
    • 加 graphql-depth-limit 与 graphql-query-complexity 防止恶意查询;
    • 通过 DataLoader 批量解决 N+1,面试常追问“用户列表接口循环查库怎么优化”。
  2. 国内云厂商部署注意点

    • 阿里云函数计算、腾讯云 SCF 要求 监听 9000 端口,需改 listen 参数;
    • 容器镜像需 多阶段构建 把 devDependencies 剔除,镜像 < 50 MB 才能快速冷启动;
    • 健康检查路径 /health 要返回 200,避免 SLB 频繁重启实例。
  3. 面试官可能追问的延伸题

    • “如何零停机热更新 Schema?” → 答 Apollo Federation 2 的 Schema Management API 或 graphql-schema-registry;
    • “订阅怎么做?” → 答 graphql-ws 协议替换旧 subscriptions-transport-ws,并给出 WebSocketServer 最小代码;
    • “如何做灰度发布?” → 答 基于 Apollo Studio 的 Launches 功能 或 自研网关按 Header 分流。

把上面的最小骨架背熟,再准备两段延伸回答,国内 GraphQL 岗位一面通过率可提升 70% 以上。