← 返回 Skills 市场
iliaal

ia-nodejs-backend

作者 Ilia Alshanetsky · GitHub ↗ · v3.0.4 · MIT-0
cross-platform ✓ 安全检测通过
319
总下载
0
收藏
0
当前安装
11
版本数
在 OpenClaw 中安装
/install compound-eng-nodejs-backend
功能描述
Node.js backend patterns: layered architecture, TypeScript, validation, error handling, security, deployment. Use when building REST APIs, REST endpoints, mi...
使用说明 (SKILL.md)

Node.js Backend

Verify before implementing: For framework-specific APIs (Express 5, Fastify 5, Node.js 22+ built-ins), search current docs via search_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 interface for object shapes (2-5x faster type resolution than intersections)
  • Prefer unknown over any -- forces explicit narrowing
  • Use z.infer\x3Ctypeof Schema> as single source of truth -- never duplicate types and schemas
  • Minimize as assertions -- 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; } in types/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 Location header 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 /ready for traffic routing; monitoring probes /health for 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-stringify for 2-3x faster serialization.
  • Circuit breaker: use opossum for outbound service calls. States: CLOSED (normal) -> OPEN (failing, return fallback) -> HALF_OPEN (probe). Prevents cascade failures when downstream services are down.

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 --noEmit && npm test pass with zero warnings before declaring done

Verify

  • tsc --noEmit passes with zero errors
  • npm test passes with zero failures
  • No TypeScript bypasses (as any, @ts-ignore) in new code

References

安全使用建议
This skill is an offline style-guide/reference for building Node.js backends and appears coherent with that purpose. It does not request credentials or install anything. Before using: (1) review any generated code and chosen dependencies for security and licensing, (2) run dependency audits and SAST/secret-scan on your repo, and (3) avoid exposing sensitive data in code files the agent may read when it applies these patterns. If you want the agent to run or deploy code, confirm which CI/hosting credentials it will use and limit those to least privilege.
功能分析
Type: OpenClaw Skill Name: compound-eng-nodejs-backend Version: 3.0.4 The skill bundle provides standard architectural and security guidance for Node.js backend development, focusing on frameworks like Express, Fastify, and NestJS. It promotes security best practices such as Zod validation, JWT authentication, and environment variable sanitization across SKILL.md and the reference files. No indicators of malicious intent, data exfiltration, or harmful prompt injection were found.
能力标签
requires-oauth-tokenrequires-sensitive-credentials
能力评估
Purpose & Capability
Name/description (Node.js backend patterns) match the provided artifacts: SKILL.md and reference docs that cover architecture, TypeScript, validation, error handling, security, and deployment. No unrelated credentials, binaries, or config paths are requested.
Instruction Scope
Runtime instructions are focused on backend design and coding practices. They do not direct the agent to read or transmit secrets, access system-wide config, or call external endpoints outside normal documentation lookups (e.g., `search_docs`). The guidance is prescriptive but narrowly scoped to building APIs.
Install Mechanism
No install spec and no code files to execute — instruction-only skill. Nothing is downloaded or written to disk by the skill itself.
Credentials
The skill declares no required environment variables, credentials, or config paths. The SKILL.md recommends validating env vars in user code but does not request any secrets or tokens for the skill to function.
Persistence & Privilege
always is false and model invocation is allowed by default. The skill does not request permanent inclusion or modification of other skills or system settings.
如何使用
  1. 确保已安装 OpenClaw(本地或 Docker 部署)
  2. 在对话框中输入安装命令:/install compound-eng-nodejs-backend
  3. 安装完成后,直接呼叫该 Skill 的名称或使用 /compound-eng-nodejs-backend 触发
  4. 根据 Skill 的参数说明提供必要输入,即可获得结构化输出
版本历史
v3.0.4
v3.0.4
v3.0.3
v3.0.3
v3.0.2
v3.0.2
v3.0.1
v3.0.1
v3.0.0
v3.0.0
v2.56.1
v2.56.1
v2.56.0
v2.56.0
v2.55.1
v2.55.1
v2.55.0
v2.55.0
v2.53.2
v2.53.2
v2.53.0
v2.53.0
元数据
Slug compound-eng-nodejs-backend
版本 3.0.4
许可证 MIT-0
累计安装 0
当前安装数 0
历史版本数 11
常见问题

ia-nodejs-backend 是什么?

Node.js backend patterns: layered architecture, TypeScript, validation, error handling, security, deployment. Use when building REST APIs, REST endpoints, mi... 它是一个面向 Claude Code / OpenClaw 的 AI Agent Skill 插件,目前累计下载 319 次。

如何安装 ia-nodejs-backend?

在 OpenClaw 或 Claude Code 对话框中运行命令「/install compound-eng-nodejs-backend」即可一键安装,无需额外配置。

ia-nodejs-backend 是免费的吗?

是的,ia-nodejs-backend 完全免费,采用 MIT-0 许可证,可自由下载、安装和使用。

ia-nodejs-backend 支持哪些平台?

ia-nodejs-backend 跨平台运行,可在任意部署了 OpenClaw / Claude Code 的环境中使用(cross-platform)。

谁开发了 ia-nodejs-backend?

由 Ilia Alshanetsky(@iliaal)开发并维护,当前版本 v3.0.4。

💬 留言讨论