AGENT SKILL

Node.js后端服务开发

nodejs

使用 Express、Fastify 或 Hono 构建生产级 Node.js 后端服务。涵盖中间件架构、流处理、工作线程、WebSocket 实现、基于 BullMQ 的队列处理、Redis 缓存、结构化日志、优雅关闭及错误处理模式。适用于构建后端 API 或服务端服务。

使用场景代码实现
License 许可
MIT
最近更新
2026-09-14
Stars
★ 68
Forks
15

01 前言 Front Matter

name
nodejs
description
Build production-grade Node.js backend services with Express, Fastify, or Hono. Covers middleware architecture, stream processing, worker threads, WebSocket implementation, queue processing with BullMQ, Redis caching, structured logging, graceful shutdown, and error handling patterns. Use when building backend APIs or server-side services.

02 资源文件 4

03 SKILL.md 正文

Node.js Backend Mastery

Framework Selection

Framework Best For Perf Ecosystem
Express Mature projects, huge middleware ecosystem Good Massive
Fastify High-performance APIs, schema validation Excellent Growing
Hono Edge/serverless, ultra-lightweight Fastest Moderate
NestJS Enterprise apps, DI-heavy architecture Good Large

Project Architecture

src/
├── routes/           # HTTP route handlers (thin controllers)
├── middleware/        # Auth, validation, error handling, logging
├── services/         # Business logic (NO HTTP concepts)
├── repositories/     # Data access layer (DB queries only)
├── models/           # Type definitions and schemas
├── lib/              # Shared utilities, clients, config
├── jobs/             # Background job processors
├── events/           # Event handlers
└── index.ts          # Server bootstrap

Layered Architecture Rule

Routes → Services → Repositories → Database
  ↓          ↓
Middleware  Events/Jobs
  • Routes: Parse HTTP, validate input, call service, format response
  • Services: Business logic, orchestration, NO database queries
  • Repositories: Data access ONLY, returns typed objects

Express API Pattern

import express, { Request, Response, NextFunction } from "express";

const router = express.Router();

router.post("/users",
  validateBody(CreateUserSchema),
  async (req: Request, res: Response, next: NextFunction) => {
    try {
      const user = await userService.create(req.body);
      res.status(201).json({ data: user });
    } catch (error) {
      next(error);
    }
  }
);

Error Handling Middleware

class AppError extends Error {
  constructor(
    public message: string,
    public statusCode: number = 500,
    public code: string = "INTERNAL_ERROR"
  ) {
    super(message);
    this.name = "AppError";
  }
}

function errorHandler(err: Error, req: Request, res: Response, _next: NextFunction) {
  const statusCode = err instanceof AppError ? err.statusCode : 500;
  const code = err instanceof AppError ? err.code : "INTERNAL_ERROR";

  logger.error({ err, path: req.path, method: req.method });

  res.status(statusCode).json({
    error: { message: err.message, code },
  });
}

Validation Middleware

import { ZodSchema } from "zod";

function validateBody(schema: ZodSchema) {
  return (req: Request, _res: Response, next: NextFunction) => {
    const result = schema.safeParse(req.body);
    if (!result.success) {
      throw new AppError(result.error.issues[0].message, 400, "VALIDATION_ERROR");
    }
    req.body = result.data;
    next();
  };
}

Caching with Redis

import { createClient } from "redis";

const redis = createClient({ url: process.env.REDIS_URL });

async function cacheGet<T>(key: string): Promise<T | null> {
  const data = await redis.get(key);
  return data ? JSON.parse(data) : null;
}

async function cacheSet(key: string, value: unknown, ttlSeconds: number = 300): Promise<void> {
  await redis.setEx(key, ttlSeconds, JSON.stringify(value));
}

async function cacheDel(pattern: string): Promise<void> {
  const keys = await redis.keys(pattern);
  if (keys.length > 0) await redis.del(keys);
}

WebSocket Implementation

import { WebSocketServer, WebSocket } from "ws";

const wss = new WebSocketServer({ server: httpServer, path: "/ws" });
const clients = new Map<string, WebSocket>();

wss.on("connection", (ws, req) => {
  const userId = authenticateWs(req);
  clients.set(userId, ws);

  ws.on("message", (data) => {
    const message = JSON.parse(data.toString());
    handleMessage(userId, message);
  });

  ws.on("close", () => clients.delete(userId));

  ws.on("error", (err) => logger.error("WebSocket error", { userId, err }));
});

function broadcast(event: string, data: unknown, exclude?: string) {
  const payload = JSON.stringify({ event, data });
  clients.forEach((ws, id) => {
    if (id !== exclude && ws.readyState === WebSocket.OPEN) ws.send(payload);
  });
}

Background Jobs (BullMQ)

import { Queue, Worker } from "bullmq";

const emailQueue = new Queue("email", { connection: { url: process.env.REDIS_URL } });

await emailQueue.add("welcome", { userId, email }, {
  attempts: 3,
  backoff: { type: "exponential", delay: 2000 },
});

const worker = new Worker("email", async (job) => {
  if (job.name === "welcome") {
    await sendWelcomeEmail(job.data.email);
  }
}, { connection: { url: process.env.REDIS_URL }, concurrency: 5 });

Graceful Shutdown

async function gracefulShutdown(signal: string) {
  logger.info(`${signal} received, starting graceful shutdown`);
  server.close();
  await redis.quit();
  await prisma.$disconnect();
  process.exit(0);
}

process.on("SIGTERM", () => gracefulShutdown("SIGTERM"));
process.on("SIGINT", () => gracefulShutdown("SIGINT"));

Best Practices

  • Use async/await everywhere — never unhandled promise rejections
  • Validate ALL inputs with Zod before processing
  • Return consistent JSON: { data } for success, { error: { message, code } } for failure
  • Use environment variables for config — never hardcode
  • Use helmet, cors, rate limiting middleware on every API
  • Set NODE_ENV=production in production
  • Use worker threads for CPU-intensive tasks
  • Implement request ID tracing across all logs

04 同仓库更多 Skills

RaheesAhmed
RaheesAhmed/SajiCode

演示测试技能

demo-skill

用于测试的演示插件技能。

普通用户示例与演示技能
★ 68
RaheesAhmed
RaheesAhmed/SajiCode

智能体技能开发

write-a-skill

创建新的智能体技能,具备合理的结构、渐进式披露(progressive disclosure)机制和配套捆绑资源。当用户想要创建、编写或构建新技能时使用。

AI 工程师插件与技能管理
★ 68
RaheesAhmed
RaheesAhmed/SajiCode

网络调研与数据提取

web-research

深度网络研究与数据提取技能。通过获取 URL、阅读文档、爬取 API 文档、评估 npm/pypi 包、比较技术,并将研究发现综合为可操作的建议,系统地研究任意主题。适用于研究库、框架、API、解决方案,或任何需要网络调查的主题。

知识工作者网页搜索与信息研究
★ 68
RaheesAhmed
RaheesAhmed/SajiCode

自动化测试套件设计与实现

testing

设计并实现全面的测试套件。涵盖单元测试、集成测试、使用 Playwright 的 E2E 测试、API 测试、mock 策略、测试数据工厂、TDD 工作流、快照测试、覆盖率目标以及 CI 集成。适用于编写测试、设计测试架构或排查测试失败。

测试工程师测试与质量保障
★ 68
RaheesAhmed
RaheesAhmed/SajiCode

工程开发工作流与质量规范

superpowers

核心工程工作流,在每一项任务中都会激活。强制执行系统化的“先计划后编码”方法论、多文件重构安全、依赖感知的变更、预检验证以及零占位符质量标准。在所有编码任务中主动(PROACTIVELY)使用。

软件开发工程师工程实践准则
★ 68
RaheesAhmed
RaheesAhmed/SajiCode

CSS样式系统设计与实现

styling

使用 Tailwind CSS、原生 CSS 或 CSS-in-JS 实现生产级样式系统。涵盖 CSS 架构(BEM、utility-first、模块化)、设计令牌、响应式模式、动画系统、暗黑模式、容器查询、打印样式以及性能优化。适用于实现设计或构建 CSS 架构。

软件开发工程师前端开发与界面实现
★ 68