phase 5 part 3: mongodb, elasticsearch hybrid search, data-pipeline, nodejs BFF topics with verified examples

This commit is contained in:
Shikui Wang committed 2026-10-23 16:38:52 +08:00
1 parent 9eeb10aede
commit 075872e31e
27 files changed
+2405 -52

No files matched your search

@@ -0,0 +1,92 @@
---
id: backend.nodejs.express-nest
title: Node.js 后端(了解级):事件循环、Express 5 中间件与错误处理、NestJS 的模块化思路、做 BFF
type: lesson
domain: backend
stack: [nodejs]
tags: [Node.js, 事件循环, Express 5, 中间件, 错误处理, NestJS, 依赖注入, BFF, SSE]
level: basic
prerequisites: [frontend.typescript.type-system]
est_hours: 2.5
related: [frontend.ssr.nextjs-app-router, backend.nodejs.scenario.ai-bff, backend.nodejs.interview]
week: [7, 14]
order: 1
---
# Node.js 后端(了解级):事件循环、Express 5 中间件与错误处理、NestJS 的模块化思路、做 BFF
> 定位:**了解并能写**。你的主线后端是 Go(基础)+ Python(AI / Agent)。BOSS直聘 2026-10-23 的调研中有岗位提到 Node.js / Next.js,前端出身的候选人被问到 Node 的概率很高。示例基于 Node 24 + Express 5 实际运行通过;NestJS 部分是示意代码,未编译。以官方文档为准:https://nodejs.org/docs 、https://expressjs.com/ 、https://docs.nestjs.com/ 。
## 解释说明
### 事件循环(面试必问)
Node 单线程执行 JS,I/O 交给系统异步完成,回调放进队列。事件循环的主要阶段:timers(`setTimeout`)→ pending callbacks → poll(I/O)→ check(`setImmediate`)→ close callbacks;每个阶段之间先清空 `process.nextTick` 队列和 Promise 微任务队列。
**结论**:适合 I/O 密集(BFF、网关、实时推送);CPU 密集的计算会阻塞所有请求,要放到 `worker_threads` 或其他服务。
### Express 5
- **中间件**:`(req, res, next)` 按注册顺序执行,类似 Gin 的中间件链。
- **错误处理中间件**:4 个参数 `(err, req, res, next)`,放在最后。
- **Express 5 的变化**:async 处理函数抛出的错误 / 被拒绝的 Promise 会自动传给错误处理中间件(Express 4 需要手动 `next(err)`);路由路径语法也有调整(以迁移指南为准)。
### NestJS
在 Express(或 Fastify)之上提供 Angular 风格的结构:模块(Module)、控制器(Controller)、服务(Provider)、**依赖注入**、管道(Pipe,做校验)、守卫(Guard,做鉴权)、拦截器(Interceptor)。适合中大型团队统一规范。对照:Go 中你手写依赖注入,FastAPI 用 `Depends`。
### 为什么前端团队常用 Node 做 BFF
同一语言、类型可以共享;聚合多个后端接口、裁剪字段;统一鉴权、限流;流式转发 AI 回答。
## 案例
AI 客服的 BFF:校验登录、限流、为每个请求生成 request id,调用 Python AI 服务并把流式回答以 SSE 转发给浏览器;客户端断开时中止上游。
## 代码示例
[examples/express-bff](examples/express-bff/):`node --test app.test.ts` 4 个测试通过、`tsc` 通过,`node server.ts` 启动后 `curl -N` 观察到每 200ms 到达一条 SSE 事件。
```ts
// Express 5:async 路由中直接 throw,由统一错误处理中间件返回
app.get("/orders/:id", async (req, res) => {
if (!/^[A-Z]\d{3,}$/.test(req.params.id)) throw new HttpError(400, "BAD_ORDER_ID", "订单号格式不正确");
const order = await deps.findOrder(req.params.id);
if (!order) throw new HttpError(404, "ORDER_NOT_FOUND", "订单不存在");
res.json(order);
});
app.use((err: unknown, _req: Request, res: Response, _next: NextFunction) => {
if (err instanceof HttpError) { res.status(err.status).json({ code: err.code, message: err.message }); return; }
res.status(500).json({ code: "INTERNAL", message: "服务器内部错误" }); // 不暴露内部细节
});
```
NestJS 的写法(示意,未编译;需要装饰器相关的编译配置):
```ts
@Controller("orders")
export class OrdersController {
constructor(private readonly orders: OrdersService) {} // 依赖注入
@Get(":id")
@UseGuards(AuthGuard) // 鉴权
find(@Param("id") id: string) {
return this.orders.findOne(id); // 抛出 NotFoundException 自动转成 404
}
}
```
## 易错点
- 在请求处理中做大量同步计算(大 JSON 序列化、加密、图片处理),阻塞所有请求。
- Express 4 的项目里 async 错误没有 `next(err)`,请求挂起直到超时。
- SSE 响应头发出后出错,还试图设置状态码。
- 没有监听客户端断开,上游 AI 继续生成、浪费 token。
- 未处理的 Promise 拒绝导致进程退出:要有全局监控和进程守护。
## 面试常问
- 讲讲 Node 的事件循环,`process.nextTick`、Promise、`setTimeout`、`setImmediate` 的顺序?
- Express 中间件原理?错误处理怎么做?
- Node 适合什么场景,不适合什么场景?
@@ -0,0 +1,53 @@
// 不自动运行(需要 npm install 后执行 node --test app.test.ts)
import assert from "node:assert/strict";
import type { AddressInfo } from "node:net";
import { after, before, test } from "node:test";
import { createApp } from "./app.ts";
let base = "";
let close: () => void = () => {};
before(async () => {
const app = createApp({
async *askLLM(q) {
if (q === "boom") throw new Error("upstream down");
yield "你好";
yield q;
},
findOrder: async (id) => (id === "A001" ? { id, status: "paid" } : null),
});
const server = app.listen(0);
await new Promise((r) => server.once("listening", r));
base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
close = () => server.close();
});
after(() => close());
test("查询订单:正常 / 格式错误 / 不存在", async () => {
assert.deepEqual(await (await fetch(`${base}/orders/A001`)).json(), { id: "A001", status: "paid" });
const bad = await fetch(`${base}/orders/xx`);
assert.equal(bad.status, 400);
assert.equal((await bad.json()).code, "BAD_ORDER_ID");
const missing = await fetch(`${base}/orders/A999`);
assert.equal(missing.status, 404);
assert.ok(missing.headers.get("x-request-id"));
});
test("请求体不是合法 JSON 时返回 400 而不是 500", async () => {
const r = await fetch(`${base}/chat`, { method: "POST", headers: { "content-type": "application/json" }, body: "{bad" });
assert.equal(r.status, 400);
});
test("流式对话:逐条 SSE 事件,最后是 done", async () => {
const r = await fetch(`${base}/chat`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ question: "退货" }) });
assert.match(r.headers.get("content-type") ?? "", /^text\/event-stream/); // express 会追加 charset
const text = await r.text();
assert.match(text, /data: \{"token":"你好"\}/);
assert.match(text, /data: \{"token":"退货"\}/);
assert.match(text, /event: done/);
});
test("上游失败:用 error 事件通知,而不是挂起连接", async () => {
const r = await fetch(`${base}/chat`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ question: "boom" }) });
assert.match(await r.text(), /event: error/);
});
@@ -0,0 +1,88 @@
// 不自动运行:需要先 npm install(express 5)。Node 23.6+ 可以直接运行 .ts(类型擦除)
// Express 5 BFF 示例:请求 id、输入校验、统一错误处理、async 路由(Express 5 会自动捕获 Promise 拒绝)、SSE 流式转发
import express, { type NextFunction, type Request, type Response } from "express";
import { randomUUID } from "node:crypto";
export class HttpError extends Error {
status: number;
code: string;
constructor(status: number, code: string, message: string) {
super(message);
this.status = status;
this.code = code;
}
}
export type Deps = {
// 上游 AI 服务:返回逐段文本的异步迭代器;真实项目里是对 Python 服务的 fetch 流式调用
askLLM: (question: string, signal: AbortSignal) => AsyncIterable<string>;
findOrder: (id: string) => Promise<{ id: string; status: string } | null>;
};
export function createApp(deps: Deps) {
const app = express();
app.use(express.json({ limit: "100kb" })); // 限制请求体大小
app.use((req, res, next) => { // 请求 id:贯穿日志和上游调用,便于排查
const id = req.get("x-request-id") ?? randomUUID();
res.locals.requestId = id;
res.set("x-request-id", id);
next();
});
app.get("/healthz", (_req, res) => {
res.json({ ok: true });
});
// Express 5:async 处理函数抛出的错误会自动交给错误处理中间件(Express 4 需要手动 next(err))
app.get("/orders/:id", async (req, res) => {
const id = req.params.id;
if (!/^[A-Z]\d{3,}$/.test(id)) throw new HttpError(400, "BAD_ORDER_ID", "订单号格式不正确");
const order = await deps.findOrder(id);
if (!order) throw new HttpError(404, "ORDER_NOT_FOUND", "订单不存在");
res.json(order);
});
app.post("/chat", async (req, res) => {
const question: unknown = req.body?.question;
if (typeof question !== "string" || question.length === 0 || question.length > 500) {
throw new HttpError(400, "BAD_QUESTION", "question 必须是 1~500 字的字符串");
}
const controller = new AbortController();
res.on("close", () => controller.abort()); // 客户端断开:通知上游停止生成
res.set({ "Content-Type": "text/event-stream", "Cache-Control": "no-cache", "X-Accel-Buffering": "no" });
res.flushHeaders();
try {
for await (const token of deps.askLLM(question, controller.signal)) {
if (controller.signal.aborted) break;
res.write(`data: ${JSON.stringify({ token })}\n\n`);
}
res.write("event: done\ndata: {}\n\n");
} catch (e) {
// 响应头已经发出,不能再改状态码:用一个 error 事件告诉前端
res.write(`event: error\ndata: ${JSON.stringify({ message: "生成失败,请重试" })}\n\n`);
console.error(res.locals.requestId, e);
} finally {
res.end();
}
});
app.use((_req, _res, next) => next(new HttpError(404, "NOT_FOUND", "接口不存在")));
// 统一错误处理:4 个参数。不把内部错误细节返回给客户端
app.use((err: unknown, _req: Request, res: Response, _next: NextFunction) => {
if (err instanceof HttpError) {
res.status(err.status).json({ code: err.code, message: err.message, requestId: res.locals.requestId });
return;
}
const status = (err as { status?: number }).status;
if (status === 400 || status === 413) { // express.json 的解析错误 / 请求体过大
res.status(status).json({ code: "BAD_REQUEST", message: "请求体无效", requestId: res.locals.requestId });
return;
}
console.error(res.locals.requestId, err);
res.status(500).json({ code: "INTERNAL", message: "服务器内部错误", requestId: res.locals.requestId });
});
return app;
}
@@ -0,0 +1,17 @@
{
"name": "express-bff-demo",
"private": true,
"type": "module",
"scripts": {
"start": "node server.ts",
"test": "node --test app.test.ts"
},
"dependencies": {
"express": "^5.1.0"
},
"devDependencies": {
"@types/express": "^5.0.0",
"@types/node": "^24.0.0",
"typescript": "^5.9.0"
}
}
@@ -0,0 +1,17 @@
// 不自动运行:启动服务 node server.ts,然后 curl -N -X POST localhost:3000/chat -H 'content-type: application/json' -d '{"question":"退货"}'
import { createApp } from "./app.ts";
async function* fakeLLM(q: string, signal: AbortSignal) {
for (const t of ["关于", `“${q}”`, ":", "签收 7 天内", "可以申请退货。"]) {
if (signal.aborted) return;
await new Promise((r) => setTimeout(r, 200));
yield t;
}
}
const app = createApp({
askLLM: fakeLLM,
findOrder: async (id) => (id === "A001" ? { id, status: "paid" } : null),
});
const port = Number(process.env.PORT ?? 3000);
app.listen(port, () => console.log(`listening on http://127.0.0.1:${port}`));
@@ -0,0 +1,14 @@
{
"compilerOptions": {
"target": "ES2023",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"strict": true,
"noEmit": true,
"skipLibCheck": true,
"allowImportingTsExtensions": true,
"erasableSyntaxOnly": true,
"verbatimModuleSyntax": true
},
"include": ["*.ts"]
}
+26 -5
View File
@@ -1,15 +1,36 @@
---
id: backend.nodejs.index
title: Node.js 后端(Express / NestJS)
title: Node.js(了解级)
type: index
domain: backend
stack: [nodejs]
tags: []
tags: [Node.js, Express, NestJS, BFF]
week: [7, 14]
---
# Node.js 后端(Express / NestJS)
# Node.js(了解级)
了解级:前端出身的后端选项,Express 中间件、NestJS 模块与依赖注入。
事件循环、Express 5、NestJS 思路,以及为 AI 应用做 BFF。定位“了解并能写”:主线后端是 Go 基础 + Python AI。BOSS直聘 2026-10-23 的调研中有岗位提到 Node.js / Next.js。
> 本专题建设中:课程、企业场景、面试题和示例代码会陆续补充。
## 学习路线
| 顺序 | 课程 | 级别 | 预计 |
| --- | --- | --- | --- |
| 1 | [Node.js 后端(了解级):事件循环、Express 5 中间件与错误处理、NestJS 的模块化思路、做 BFF](01-express-nest-basics.md) | 基础 | 2.5 小时 |
## 企业场景
- [用 Node.js 给 AI 应用做 BFF:鉴权、限流、流式转发、超时和断开处理](scenarios/ai-bff.md)
## 面试题
- [Node.js 面试题](interview.md)
## 示例代码
- [examples/express-bff](examples/express-bff/):Express 5 统一错误处理、request id、SSE 流式输出与断开处理(4 个测试通过,tsc 通过)
## 在 16 周计划中
- [第 7 周:前端工程化查漏](../../../plan/week07-frontend.md)
- [第 14 周:后端扩展与部署](../../../plan/week14-backend-extend-deploy.md)
+67
View File
@@ -0,0 +1,67 @@
---
id: backend.nodejs.interview
title: Node.js 面试题
type: interview
domain: backend
stack: [nodejs]
tags: [Node.js, 事件循环, Express, NestJS, 面试]
level: basic
related: [backend.nodejs.express-nest]
week: [14, 16]
---
# Node.js 面试题
## 基础
### 【基础】Node 的事件循环是怎样的?
**参考答案**:单线程执行 JS,I/O 由 libuv 异步完成。主要阶段:timers → pending callbacks → poll → check → close callbacks;每个回调执行完后先清空 `process.nextTick` 队列,再清空 Promise 微任务队列。
**追问**:`setTimeout(fn, 0)` 和 `setImmediate` 谁先执行?→ 在主模块中顺序不确定(取决于进入事件循环时计时器是否到期);在 I/O 回调中 `setImmediate` 一定先执行。
### 【基础】Node 适合什么场景?
**参考答案**:I/O 密集、高并发连接:BFF、API 网关、实时推送(WebSocket / SSE)、工具链。不适合长时间的 CPU 计算,否则阻塞事件循环;需要时用 `worker_threads` 或拆到其他服务。
**追问**:怎么发现事件循环被阻塞?→ 监控事件循环延迟(`perf_hooks.monitorEventLoopDelay`),用 CPU profile 找热点。
### 【基础】Express 中间件的执行原理?
**参考答案**:按注册顺序组成链,每个中间件处理后调用 `next()` 进入下一个,不调用则请求在此结束;错误处理中间件有 4 个参数,`next(err)` 或 Express 5 中 async 函数抛错时跳转过去。
**追问**:和 Koa 的洋葱模型有什么区别?→ Koa 的 `await next()` 可以在后续中间件执行完后继续执行后半段逻辑,天然适合计时和统一响应处理;Express 需要监听 `res` 的 `finish` 事件实现类似效果。
## 进阶
### 【进阶】NestJS 的依赖注入有什么好处?
**参考答案**:类声明依赖,由容器创建和注入;便于替换实现(测试中注入假的服务)、统一生命周期管理、模块边界清晰;配合管道、守卫、拦截器形成统一规范。
**追问**:和 FastAPI 的 `Depends` 比较?→ 思想相同,FastAPI 基于函数参数声明,Nest 基于类构造函数和装饰器元数据。
### 【进阶】Node 服务如何处理未捕获的异常?
**参考答案**:请求级错误用统一错误处理中间件;进程级监听 `uncaughtException` / `unhandledRejection` 记录日志后退出,由进程管理器(容器编排 / systemd / PM2)重启;不要在未知状态下继续运行。
**追问**:为什么不能捕获后继续运行?→ 程序可能处于不一致的状态(连接、内存中的数据),继续运行可能产生更隐蔽的错误。
### 【进阶】Node 如何利用多核?
**参考答案**:多进程(`cluster` 或容器多副本 + 负载均衡)处理更多请求;`worker_threads` 处理 CPU 计算。服务要无状态,会话等放在 Redis。
**追问**:WebSocket 多实例怎么广播?→ 通过 Redis Pub/Sub 或消息队列在实例之间转发,负载均衡开启会话保持或使用支持多实例的方案。
## 场景题
### 【场景题】给 AI 应用做 BFF,你会做哪些事?
**参考答案**:统一鉴权、限流、request id;首屏并行聚合与降级;SSE 流式透传、断开时中止上游、超时控制、上游错误以事件形式通知;保持薄层。详见[AI BFF 场景](scenarios/ai-bff.md)。
**追问**:怎么测试流式接口?→ 启动应用监听随机端口,用 `fetch` 读取响应,断言事件内容和顺序、错误事件和响应头,见[示例测试](examples/express-bff/app.test.ts)。
### 【场景题】Node 服务内存持续上涨,怎么排查?
**参考答案**:观察堆内存趋势;在不同时间点生成堆快照对比,找增长的对象和引用链;常见原因:全局缓存无上限、事件监听未移除、闭包持有大对象、定时器未清理。修复后压测验证。
**追问**:线上怎么安全地拿堆快照?→ 在摘除流量的单个实例上进行,快照期间进程会暂停,注意快照可能包含敏感数据。
+84
View File
@@ -0,0 +1,84 @@
---
id: backend.nodejs.scenario.ai-bff
title: 用 Node.js 给 AI 应用做 BFF:鉴权、限流、流式转发、超时和断开处理
type: scenario
domain: backend
stack: [nodejs, redis, nginx, fastapi]
tags: [BFF, SSE, 流式转发, 限流, 超时, request id]
level: intermediate
prerequisites: [backend.nodejs.express-nest]
est_hours: 2
related: [backend.nodejs.interview, frontend.ssr.scenario.help-center]
week: [14]
---
# 用 Node.js 给 AI 应用做 BFF:鉴权、限流、流式转发、超时和断开处理
## 业务背景与问题
前端团队维护的 AI 助手页面直接调用 Python 的 Agent 服务,问题:
1. Agent 服务要校验各业务线不同的登录态,越来越臃肿;
2. 页面需要的数据来自 3 个服务,前端串行请求,首屏慢;
3. 用户关掉页面后,Agent 仍在生成,浪费模型费用;
4. 出问题时无法串起前端、BFF、Agent 三方日志。
## 约束
- 前端团队熟悉 TypeScript,希望自己维护这一层。
- Agent 服务由 AI 团队维护,接口为 SSE。
## 方案设计
1. **BFF(Express 5 或 NestJS)**:统一鉴权(会话 / JWT)、按用户限流(Redis)、生成并透传 `x-request-id`。
2. **聚合接口**:首屏所需的用户信息、会话列表、配额用 `Promise.allSettled` 并行请求,各自设超时,部分失败时降级返回。
3. **流式转发**:`fetch` 上游时传入 `AbortSignal`,`res.on("close")` 时中止;首字节超时和总超时分别控制;上游出错时发送 SSE `error` 事件而不是挂起。
4. **部署**:多实例无状态,Nginx 关闭对 SSE 路由的缓冲,设置较长的读超时。
## 关键代码
```ts
app.post("/chat", async (req, res) => {
const user = await auth(req); // 失败时 throw HttpError(401)
await rateLimit(`chat:${user.id}`); // 超限 throw HttpError(429)
const controller = new AbortController();
res.on("close", () => controller.abort());
const timeout = setTimeout(() => controller.abort(), 120_000); // 总超时
const upstream = await fetch(`${AGENT_URL}/chat`, {
method: "POST",
headers: { "content-type": "application/json", "x-request-id": res.locals.requestId, "x-user-id": user.id },
body: JSON.stringify({ question: req.body.question }),
signal: controller.signal,
});
res.set({ "Content-Type": "text/event-stream", "Cache-Control": "no-cache", "X-Accel-Buffering": "no" });
try {
for await (const chunk of upstream.body!) res.write(chunk); // 原样透传上游的 SSE 字节
} catch {
if (!controller.signal.aborted) res.write('event: error\ndata: {"message":"生成中断"}\n\n');
} finally {
clearTimeout(timeout);
res.end();
}
});
```
可运行的基础版本(含测试):[examples/express-bff](../examples/express-bff/)。
## 取舍
| 选择 | 优点 | 缺点 |
| --- | --- | --- |
| **Node BFF(本方案)** | 前端团队自治、类型共享、擅长 I/O | 多一层服务和一跳网络 |
| Next.js 路由处理器做 BFF | 和页面同一个项目 | 受部署形态限制(Serverless 超时) |
| 由 Agent 服务直接对外 | 链路短 | 鉴权、聚合逻辑侵入 AI 服务 |
## 易错点
- 把上游的流读完再返回(`await upstream.text()`),失去流式效果。
- 没有向上游传播取消。
- `Promise.all` 中一个接口失败导致整页失败:首屏聚合用 `allSettled` + 降级。
- 在 BFF 里堆业务逻辑,最后变成“第二个后端”。
## 面试怎么讲
> “AI 助手页面我们加了一层 Node BFF:统一鉴权和按用户限流,生成 request id 透传到 Agent 服务;首屏数据并行聚合、部分失败降级;对话接口把 Agent 的 SSE 原样透传,用户断开时通过 AbortController 中止上游,节省模型费用;上游失败时发 error 事件。BFF 保持薄,只做协议适配和横切逻辑。”