以 AI 机器人身份加入视频会议,提供语音、虚拟形象与屏幕共享四种模式。
安全
ia-nodejs-backend
试用Node.js 后端工程模式:分层架构、校验、错误处理与可观测性实践。
它能做什么
面向 Express、Fastify、Hono、NestJS、Koa、tRPC 与 Bun 的 Node.js + TypeScript 后端组织指南。覆盖:基于 Zod 或 TypeBox 的契约优先 API 设计、AppError 错误层级与状态码映射、Clean Architecture 依赖方向(routes → services → repositories)、启动期环境变量 fail-fast 校验、/health 与 /ready 双探针、Redis 缓存与 @fastify/under-pressure 限流、opossum 熔断器、pino 结构化日志、prom-client RED 指标、OpenTelemetry 链路追踪。最终以 tsc --noEmit 与 npm test 作为验收,并附 TypeScript 配置、安全、API 设计与数据库/生产四个深入参考。
什么时候用它
- 为新服务挑选 Express、Fastify、Hono 或 NestJS
- 按 Clean Architecture 划清 routes / services / repositories 边界
- 为 TypeScript REST API 接入校验、错误处理与可观测性
- 上线前配置健康探针、RED 指标与链路追踪
技能文档
Node.js Backend
Verify before implementing: For framework-specific APIs (Express 5, Fastify 5, Node.js 22+ built-ins), look up current docs via Context7 (query-docs) before writing code. Training data may lag current releases.
Framework Selection
| Context | Choose | Why |
|---|---|---|
| Edge/Serverless | Hono | Zero-dep, fastest cold starts |
| Performance API | Fastify | Higher throughput than Express, built-in schema validation |
| Enterprise/team | NestJS | DI, decorators, structured conventions |
| Legacy/ecosystem | Express | Most middleware, widest adoption |
Ask user: deployment target, cold start needs, team experience, existing codebase.
Architecture
src/
├── routes/ # HTTP: parse request, call service, format response
├── middleware/ # Auth, validation, rate limiting, logging
├── services/ # Business logic (no HTTP types)
├── repositories/ # Data access only (queries, ORM)
├── config/ # Env, DB pool, constants
└── types/ # Shared TypeScript interfaces
- Routes never contain business logic
- Services never import Request/Response
- Repositories never throw HTTP errors
- Dependencies point inward only (Clean Architecture rule): routes -> services -> repositories. Never the reverse.
- For scripts/prototypes: single file is fine -- ask "will this grow?"
TypeScript Rules
- Use
import type { }for type-only imports -- eliminates runtime overhead - Prefer
interfacefor object shapes (2-5x faster type resolution than intersections) - Prefer
unknownoverany-- forces explicit narrowing - Use
z.inferas single source of truth -- never duplicate types and schemas - Minimize
asassertions -- use type guards instead - Add explicit return types to exported functions (faster declaration emit)
- Untyped package?
declare module 'pkg' { const v: unknown; export default v; }intypes/ambient.d.ts
Validation
Zod (TypeScript inference) or TypeBox (Fastify native). Validate at boundaries only: request entry, before DB ops, env vars at startup. Use .extend(), .pick(), .omit(), .partial(), .merge() for DRY schemas.
Error Handling
Custom error hierarchy: AppError(message, statusCode, isOperational) → ValidationError(400), NotFoundError(404), UnauthorizedError(401), ForbiddenError(403), ConflictError(409)
Centralized handler middleware:
AppError→ return{ error: message }with statusCode- Unknown → log full stack, return 500 + generic message in production
- Async wrapper:
const asyncHandler = (fn) => (req, res, next) => Promise.resolve(fn(req, res, next)).catch(next);
Codes: 400 bad input | 401 no auth | 403 no permission | 404 missing | 409 conflict | 422 business rule | 429 rate limited | 500 server fault
API Design
Contract-first: define route schemas (Zod schemas, Fastify JSON Schema, or OpenAPI spec) before writing handler logic. The schema is the contract -- implementation follows. Generate OpenAPI/Swagger docs from these schemas for interactive API documentation.
- Hyrum's Law awareness: every observable response field, ordering, or timing becomes a dependency for callers. Use Zod schemas or Fastify response schemas to control exactly what's serialized -- never return raw ORM objects or untyped objects from handlers.
- Addition over modification: add new optional fields rather than changing or removing existing ones. Removing a field from a response schema breaks callers silently. Deprecate first (mark in OpenAPI spec), remove in a later version.
- Consistent error envelope: all errors -- validation, auth, not-found, application -- must produce the same
{ error: { code, message, details? } }structure. Centralize in the error handler middleware. Callers build error handling once; inconsistent errors force per-endpoint special cases. - Boundary validation: validate at the middleware/route handler level (Zod
.parse()on request body/params, Fastify schema validation). Services and repositories trust that input was validated at entry -- no redundant checks scattered through business logic. - Third-party responses are untrusted data: validate shape and content of external API responses before using them in logic, rendering, or decision-making. A compromised or misbehaving service can return unexpected types, malicious content, or missing fields. Parse through a Zod schema before use.
- Resources: plural nouns (
/users), max 2 nesting levels (/users/:id/orders) - Methods: GET read | POST create | PUT replace | PATCH partial | DELETE remove
- Versioning: URL path
/api/v1/ - Response:
{ data, pagination?: { page, limit, total, totalPages } } - Queries:
?page=1&limit=20&status=active&sort=createdAt,desc - Return
Locationheader on 201. Use 204 for successful DELETE with no body.
Async Patterns
| Pattern | Use When |
|---|---|
async/await | Sequential operations |
Promise.all | Parallel independent ops |
Promise.allSettled | Parallel, some may fail |
Promise.race | Timeout or first-wins |
Never use readFileSync or other sync methods in production -- use fs.promises or stream equivalents. Offload CPU work to worker threads (Piscina). Stream large payloads.
Production Resilience
- Fail-fast env validation: parse and validate all environment variables at startup with a Zod schema (
const env = envSchema.parse(process.env)). If invalid, crash before serving traffic. Never discover a missing env var on the first request that needs it. - Health endpoints: expose both
/health(shallow, always 200 if process is alive) and/ready(deep, verifies database, cache, and critical dependencies are reachable). Load balancers probe/readyfor traffic routing; monitoring probes/healthfor process liveness. Don't conflate them. - Caching: Redis cache-aside for DB/API responses; in-memory LRU with TTL for hot paths. Always invalidate on writes.
- Load shedding:
@fastify/under-pressure(or equivalent) -- monitor event loop delay, heap, RSS; return 503 when thresholds exceeded. - Response schemas: In Fastify, always define response schemas -- enables
fast-json-stringifyfor 2-3x faster serialization. - Circuit breaker: use
opossumfor outbound service calls. States: CLOSED (normal) -> OPEN (failing, return fallback) -> HALF_OPEN (probe). Prevents cascade failures when downstream services are down. When the outbound call is the security decision (authz check, trust score, license or entitlement gate), the fallback must be deny, and any fail-open allowance scopes to transport failure only -- connection refused, DNS failure, timeout. A response that arrived but cannot be trusted (4xx/5xx, malformed JSON, schema-invalid body, unknown verdict value) stays blocked: the endpoint was reached and did not answer. Absence of evidence is not evidence of trust. Same for "no history yet" states -- reject by default, allow only through an explicit onboarding opt-in.
Observability
- Define "working" before instrumenting: write the questions an on-call engineer will ask when this is broken at 3am ("which dependency is timing out?", "is it all users or one tenant?"), then add only the telemetry that answers them. Instrumentation with no question behind it is cost and noise.
- Pick the signal by the question it answers: logs = "what happened in this one case?" (high-detail, structured, sampled under load); metrics = "how often / how fast / how saturated?" (cheap aggregates — keep label cardinality bounded, never user IDs or request IDs as labels); traces = "where did the time or the error go across services?".
- Structured logging:
pinowith a stable set of event names and a correlation/request ID propagated through async context (AsyncLocalStorage). Neverconsole.login production paths. - Metrics:
prom-clientfor RED per route — Rate (request count), Errors (error count), Duration (latency histogram). OpenTelemetry Node SDK for distributed traces across services. - Initialize tracing before app imports, then verify it fires: the OTel SDK must start before the modules it instruments are required, or auto-instrumentation silently no-ops. Before relying on any signal, force an error and send test traffic in staging and confirm the log/metric/trace actually lands — untested instrumentation fails silent.
- Alert on symptoms, not causes: page on user-visible symptoms (error-rate spike, latency SLO burn,
/readyflapping), not on causes (CPU high, heap growing). A cause with no symptom is a dashboard, not a page.
Discipline
- Simplicity first -- every change as simple as possible, impact minimal code
- Only touch what's necessary -- avoid introducing unrelated changes
- No hacky workarounds -- if a fix feels wrong, step back and implement the clean solution
- Before adding a new abstraction, verify it appears in 3+ places. If not, inline it.
- If a fix requires bypassing TypeScript (
as any, non-null assertions on untrusted data,// @ts-ignore), treat it as a design smell and find the typed solution
Verify
tsc --noEmitpasses with zero errorsnpm testpasses with zero failures- No TypeScript bypasses (
as any,@ts-ignore) in new code
References
- TypeScript config -- tsconfig, ESM, branded types, compiler performance
- Security -- JWT, password hashing, rate limiting, OWASP
- API design patterns -- pagination, filtering, sorting, deprecation
- Database & production -- connection pooling, transactions, Docker, logging
相关技能
把自然语言描述转为结构化 JSON,并由 mcp-diagram-generator MCP 服务生成 Draw.io、Mermaid 或 Excalidraw 图表文件。
诊断生产力系统反复失效的根因,给出最小干预——容量测算、瓶颈定位、可靠的本地记录。
在本地磁盘以分类纯 Markdown 文件保存需要长期留存的事实,与智能体内置记忆并存。
按用户明确指令,在得到大脑(Get笔记)中保存、搜索并管理笔记与知识库。
编写、调试与调优 Playwright 测试,涵盖定位器策略、追踪诊断与 CI 友好的超时配置。
iliaal 的更多技能
浏览全部技能Laravel 与 PHP 8.4 框架级开发指南:架构、Eloquent、迁移、队列、测试,基于真实踩坑编写。
先核对需求规范再评代码质量,输出按严重度排序的发现,并可切换多 agent 深度评审。
围绕可复现失败信号展开的 7 步根因调试流程,先有失败用例再下修复。
在动手写代码之前,先拿到一份通过评审的设计文档。
编写能验证真实行为的测试:每个用例聚焦单一行为,优先使用真实对象,覆盖静默失败路径。
Tailwind CSS v4 模式速查:CSS 优先配置、@theme 设计令牌、组件变体、v3 迁移修复。