Token导航 LogoToken导航TokenDH.com
开发需要联网github未标认证来源可访问许可证需确认审计通过

expressexpress 开发

Agent Skill

express 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要围绕仓库状态、代码变更或协作事项进行整理时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

总安装

216

周安装

9

GitHub Stars

8

下载量

72
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:express(express 开发)
来源仓库:https://github.com/ar4mirez/samuel
仓库路径:skills/express
安装命令:
npx skills add https://github.com/ar4mirez/samuel --skill express
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/ar4mirez/samuel --skill express

简介

Express.js 4.x/5.x TypeScript 全栈开发规范。

  • 以中间件为核心构建分层架构体系。express 属于开发类 Skill,可作为该场景下的辅助能力补充。
  • 强制启用 helmet/cors 等安全中间件防护攻击面。
  • 控制器仅作请求分发禁止嵌入业务逻辑。
  • 所有新工程必须配置严格类型检查模式。

SKILL.md

Express.js Guide

Applies to: Express.js 4.x/5.x, TypeScript/JavaScript, REST APIs, Web Servers, Microservices

Core Principles

  1. Middleware-Centric: Everything is middleware -- parsing, auth, logging, errors
  2. Layered Architecture: Controllers -> Services -> Repositories (separation of concerns)
  3. Type Safety: Use TypeScript for all new Express projects
  4. Security First: helmet, cors, rate limiting, input validation on every route
  5. Graceful Lifecycle: Handle startup, shutdown, and uncaught errors properly

Guardrails

Project Setup

  • Use TypeScript with strict mode enabled
  • Install core security packages: helmet, cors, express-rate-limit
  • Use dotenv for environment configuration (never hardcode secrets)
  • Use zod or joi for request validation at every API boundary
  • Use morgan or pino for structured logging
  • Set express.json({limit: '10mb'}) to prevent oversized payloads

Code Style

  • Controllers: thin, delegate to services, catch errors via next(error)
  • Services: business logic only, no req/res references
  • Repositories: data access only, return domain types
  • Middleware: single-responsibility, composable
  • Routes: declarative, grouped by resource
  • No business logic in route files

Error Handling

  • Use a centralized error-handling middleware (4-argument signature)
  • Create a custom AppError class with statusCode and optional errors array
  • Always call next(error) in async handlers -- never swallow errors
  • Return generic messages in production, detailed messages in development
  • Handle 404 with a dedicated not-found middleware after all routes
  • Log all errors with request context (path, method, stack trace)

Security

  • Enable helmet() for security headers
  • Configure CORS with explicit allowed origins (not * in production)
  • Implement rate limiting on all routes, stricter on auth endpoints
  • Validate and sanitize all user inputs before processing
  • Use parameterized queries (Prisma, Knex, or prepared statements)
  • Set secure cookie options: httpOnly, secure, sameSite
  • Never expose stack traces or internal details in production responses

Performance

  • Use compression middleware for response compression
  • Implement pagination for list endpoints (never return unbounded results)
  • Use connection pooling for database connections
  • Set appropriate timeouts on the HTTP server (readTimeout, writeTimeout)
  • Cache expensive computations where appropriate

Project Structure

my-api/
├── src/
│   ├── app.ts                 # Express app setup (middleware, routes, error handling)
│   ├── server.ts              # Entry point (listen, graceful shutdown)
│   ├── config/                # Environment and app configuration
│   │   └── index.ts
│   ├── controllers/           # Route handlers (thin, delegate to services)
│   │   └── user.controller.ts
│   ├── middlewares/           # Custom middleware
│   │   ├── auth.middleware.ts
│   │   ├── error.middleware.ts
│   │   ├── validate.middleware.ts
│   │   └── rateLimit.middleware.ts
│   ├── routes/                # Route definitions (grouped by resource)
│   │   ├── index.ts
│   │   └── user.routes.ts
│   ├── services/              # Business logic (no req/res)
│   │   └── user.service.ts
│   ├── repositories/          # Data access layer
│   │   └── user.repository.ts
│   ├── models/                # Data models / Prisma schema
│   │   └── user.model.ts
│   ├── schemas/               # Zod validation schemas
│   │   └── user.schema.ts
│   ├── types/                 # TypeScript type definitions
│   │   └── index.ts
│   └── utils/                 # Shared utilities
│       ├── errors.ts          # AppError class
│       └── logger.ts          # Logger setup
├── tests/
│   └── user.test.ts
├── .env.example
├── package.json
└── tsconfig.json

Layer Responsibilities

LayerKnows AboutNever References
RoutesControllers, middlewareServices, repositories
ControllersServices, typesRepositories, database
ServicesRepositories, typesreq/res, Express
RepositoriesDatabase client, typesServices, controllers

Application Setup

App Configuration (src/app.ts)

import express, { Application } from 'express';
import cors from 'cors';
import helmet from 'helmet';
import morgan from 'morgan';
import { errorHandler } from './middlewares/error.middleware';
import { notFoundHandler } from './middlewares/notFound.middleware';
import routes from './routes';

const app: Application = express();

// Security
app.use(helmet());
app.use(cors({ origin: process.env.CORS_ORIGIN || '*', credentials: true }));

// Parsing
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true }));

// Logging (skip in test)
if (process.env.NODE_ENV !== 'test') {
  app.use(morgan('combined'));
}

// Health check
app.get('/health', (_req, res) => {
  res.json({ status: 'ok', timestamp: new Date().toISOString() });
});

// API routes
app.use('/api/v1', routes);

// Error handling (order matters: 404 first, then error handler)
app.use(notFoundHandler);
app.use(errorHandler);

export default app;

Server Entry Point (src/server.ts)

import 'dotenv/config';
import app from './app';
import { logger } from './utils/logger';

const PORT = process.env.PORT || 3000;

const server = app.listen(PORT, () => {
  logger.info(`Server running on port ${PORT}`);
});

// Graceful shutdown
const shutdown = () => {
  logger.info('Shutting down gracefully...');
  server.close(() => process.exit(0));
  setTimeout(() => process.exit(1), 10000); // Force after 10s
};

process.on('SIGTERM', shutdown);
process.on('SIGINT', shutdown);
process.on('unhandledRejection', (reason: Error) => {
  logger.error('Unhandled Rejection:', reason);
  throw reason;
});
process.on('uncaughtException', (error: Error) => {
  logger.error('Uncaught Exception:', error);
  process.exit(1);
});

Routing

Route Organization

// src/routes/index.ts
import { Router } from 'express';
import userRoutes from './user.routes';
import authRoutes from './auth.routes';

const router = Router();

router.use('/auth', authRoutes);
router.use('/users', userRoutes);

export default router;

Resource Routes

// src/routes/user.routes.ts
import { Router } from 'express';
import { UserController } from '../controllers/user.controller';
import { authMiddleware } from '../middlewares/auth.middleware';
import { validate } from '../middlewares/validate.middleware';
import { createUserSchema, updateUserSchema } from '../schemas/user.schema';

const router = Router();
const controller = new UserController();

router.get('/', controller.getAll);
router.get('/:id', controller.getById);
router.post('/', validate(createUserSchema), controller.create);
router.put('/:id', authMiddleware, validate(updateUserSchema), controller.update);
router.delete('/:id', authMiddleware, controller.delete);

export default router;

Route Conventions

  • Group routes by resource under /api/v1/
  • Use plural nouns for resource names (/users, /products)
  • HTTP verbs map to CRUD: GET (read), POST (create), PUT/PATCH (update), DELETE (remove)
  • Apply auth middleware selectively (not on public routes)
  • Apply validation middleware before the controller handler

Middleware

Middleware Order (in app.ts)

  1. helmet() -- security headers
  2. cors() -- cross-origin requests
  3. express.json() -- body parsing
  4. morgan() -- request logging
  5. Route-level middleware (auth, validation, rate limiting)
  6. Routes
  7. notFoundHandler -- catch unmatched routes
  8. errorHandler -- centralized error handling

Custom AppError

// src/utils/errors.ts
export class AppError extends Error {
  constructor(
    message: string,
    public statusCode: number = 500,
    public errors?: any[]
  ) {
    super(message);
    this.name = 'AppError';
    Error.captureStackTrace(this, this.constructor);
  }
}

Error Handler

// src/middlewares/error.middleware.ts
import { Request, Response, NextFunction } from 'express';
import { AppError } from '../utils/errors';
import { logger } from '../utils/logger';

export const errorHandler = (
  error: Error, req: Request, res: Response, _next: NextFunction
) => {
  logger.error('Error:', { message: error.message, path: req.path, method: req.method });

  if (error instanceof AppError) {
    return res.status(error.statusCode).json({
      status: 'error',
      message: error.message,
      ...(error.errors && { errors: error.errors }),
    });
  }

  res.status(500).json({
    status: 'error',
    message: process.env.NODE_ENV === 'production'
      ? 'Internal server error'
      : error.message,
  });
};

Validation Middleware (Zod)

// src/middlewares/validate.middleware.ts
import { Request, Response, NextFunction } from 'express';
import { ZodSchema, ZodError } from 'zod';
import { AppError } from '../utils/errors';

export const validate = (schema: ZodSchema) => {
  return (req: Request, _res: Response, next: NextFunction) => {
    try {
      schema.parse({ body: req.body, query: req.query, params: req.params });
      next();
    } catch (error) {
      if (error instanceof ZodError) {
        const errors = error.errors.map((e) => ({
          field: e.path.join('.'),
          message: e.message,
        }));
        next(new AppError('Validation failed', 400, errors));
      } else {
        next(error);
      }
    }
  };
};

Testing

Testing Stack

  • Jest for test runner and assertions
  • Supertest for HTTP integration tests
  • Use app (not server) for supertest -- avoids port conflicts

Integration Test Pattern

import request from 'supertest';
import app from '../src/app';

describe('GET /api/v1/users', () => {
  it('should return 200 with user list', async () => {
    const response = await request(app)
      .get('/api/v1/users')
      .expect('Content-Type', /json/)
      .expect(200);

    expect(response.body.data).toBeDefined();
    expect(response.body.meta).toBeDefined();
  });

  it('should return 400 for invalid query params', async () => {
    await request(app)
      .get('/api/v1/users?page=-1')
      .expect(400);
  });
});

Test Organization

  • One test file per resource/feature
  • Group by HTTP method and route using describe blocks
  • Test both success and error paths
  • Test validation, auth, and edge cases
  • Use beforeEach/afterEach for database cleanup

Tooling

Essential Commands

# Development
npm run dev              # Start with hot-reload (ts-node-dev)

# Build
npm run build            # Compile TypeScript
npm start                # Run compiled JS

# Testing
npm test                 # Run all tests
npm run test:watch       # Watch mode
npm run test:cov         # With coverage

# Quality
npm run lint             # ESLint
npm run lint:fix         # Auto-fix lint issues

Configuration (tsconfig.json)

{
  "compilerOptions": {
    "target": "ES2020",
    "module": "commonjs",
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true,
    "resolveJsonModule": true,
    "declaration": true,
    "sourceMap": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "dist"]
}

Package Scripts

{
  "scripts": {
    "dev": "ts-node-dev --respawn --transpile-only src/server.ts",
    "build": "tsc",
    "start": "node dist/server.js",
    "test": "jest",
    "lint": "eslint src/**/*.ts"
  }
}

Dependencies

Core

PackagePurpose
expressWeb framework
corsCross-origin resource sharing
helmetSecurity headers
morganHTTP request logging
dotenvEnvironment variables
zodInput validation

Auth & Security

PackagePurpose
jsonwebtokenJWT authentication
bcryptjsPassword hashing
express-rate-limitRate limiting

Database

PackagePurpose
@prisma/clientORM / database client

Dev

PackagePurpose
typescriptType system
ts-node-devDev server with hot reload
jestTest runner
supertestHTTP testing
@types/expressExpress type definitions

Advanced Topics

For detailed code examples and advanced patterns, see:

  • references/patterns.md -- Controller patterns, service layer, authentication, database integration, rate limiting, testing examples

External References

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

35.94%
按下载量换算26

Claude

32.59%
按下载量换算23

Cursor

19.45%
按下载量换算14

Gemini CLI

10.01%
按下载量换算7

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills