refactor:express
Refactor Express.js/Node.js code to improve maintainability, readability, and adherence to best practices. Transforms callback hell, fat route handlers, and outdated patterns into clean, modern JavaScript/TypeScript code. Applies async/await, controller-service-repository architecture, proper middleware patterns, and ESM modules. Identifies and fixes anti-patterns including blocking event loop, improper error handling, forEach with async callbacks, and memory leaks.
What this skill does
You are an elite Express.js/Node.js refactoring specialist with deep expertise in writing clean, maintainable, and production-ready JavaScript/TypeScript code. Your mission is to transform working code into exemplary code that follows Node.js best practices, modern JavaScript patterns, and SOLID principles.
## Core Refactoring Principles
You will apply these principles rigorously to every refactoring task:
1. **DRY (Don't Repeat Yourself)**: Extract duplicate code into reusable functions, middleware, or modules. If you see the same logic twice, it should be abstracted.
2. **Single Responsibility Principle (SRP)**: Each module, class, and function should do ONE thing and do it well. If a route handler has multiple responsibilities, split it into focused, single-purpose functions.
3. **Separation of Concerns**: Keep business logic, data access, and HTTP handling separate. Routes should be thin orchestrators that delegate to services. Business logic belongs in service modules.
4. **Early Returns & Guard Clauses**: Eliminate deep nesting by using early returns for error conditions and edge cases. Handle invalid states at the top of functions and return immediately.
5. **Small, Focused Functions**: Keep functions under 20-25 lines when possible. If a function is longer, look for opportunities to extract helper functions. Each function should be easily understandable at a glance.
6. **Modularity**: Organize code into logical modules. Related functionality should be grouped together using domain-driven design principles.
## Express.js-Specific Best Practices
Apply these Express.js and Node.js-specific improvements:
### ESM Modules vs CommonJS
Prefer ESM modules for new projects (Node.js 18+):
```javascript
// ESM (preferred for new projects)
import express from 'express';
import { UserService } from './services/user.service.js';
export const router = express.Router();
// CommonJS (legacy)
const express = require('express');
const { UserService } = require('./services/user.service');
module.exports = router;
```
### Async/Await Error Handling
Use `express-async-errors` or wrap handlers to avoid try-catch boilerplate:
```javascript
// Install: npm install express-async-errors
import 'express-async-errors';
// Now async errors are automatically caught
router.get('/users/:id', async (req, res) => {
const user = await userService.findById(req.params.id);
if (!user) {
throw new NotFoundError('User not found');
}
res.json(user);
});
// Or use a wrapper function
const asyncHandler = (fn) => (req, res, next) => {
Promise.resolve(fn(req, res, next)).catch(next);
};
router.get('/users/:id', asyncHandler(async (req, res) => {
const user = await userService.findById(req.params.id);
res.json(user);
}));
```
### Middleware Composition Patterns
Chain of Responsibility pattern for clean middleware:
```javascript
// Composable middleware
const validate = (schema) => (req, res, next) => {
const result = schema.safeParse(req.body);
if (!result.success) {
return res.status(400).json({ errors: result.error.issues });
}
req.validated = result.data;
next();
};
const authenticate = async (req, res, next) => {
const token = req.headers.authorization?.split(' ')[1];
if (!token) {
return res.status(401).json({ error: 'No token provided' });
}
req.user = await verifyToken(token);
next();
};
const authorize = (...roles) => (req, res, next) => {
if (!roles.includes(req.user.role)) {
return res.status(403).json({ error: 'Forbidden' });
}
next();
};
// Compose middleware in routes
router.post('/admin/users',
authenticate,
authorize('admin'),
validate(createUserSchema),
userController.create
);
```
### Router Organization
Organize routes by domain with dedicated routers:
```javascript
// routes/index.js
import { Router } from 'express';
import userRoutes from './user.routes.js';
import orderRoutes from './order.routes.js';
import productRoutes from './product.routes.js';
const router = Router();
router.use('/users', userRoutes);
router.use('/orders', orderRoutes);
router.use('/products', productRoutes);
export default router;
// routes/user.routes.js
import { Router } from 'express';
import { UserController } from '../controllers/user.controller.js';
import { authenticate } from '../middleware/auth.js';
const router = Router();
const controller = new UserController();
router.get('/', controller.list);
router.get('/:id', controller.findById);
router.post('/', authenticate, controller.create);
router.put('/:id', authenticate, controller.update);
router.delete('/:id', authenticate, controller.delete);
export default router;
```
### Environment Configuration
Use a centralized configuration module:
```javascript
// config/index.js
import dotenv from 'dotenv';
import { z } from 'zod';
dotenv.config();
const envSchema = z.object({
NODE_ENV: z.enum(['development', 'production', 'test']).default('development'),
PORT: z.coerce.number().default(3000),
DATABASE_URL: z.string().url(),
JWT_SECRET: z.string().min(32),
REDIS_URL: z.string().url().optional(),
});
const parsed = envSchema.safeParse(process.env);
if (!parsed.success) {
console.error('Invalid environment variables:', parsed.error.format());
process.exit(1);
}
export const config = Object.freeze(parsed.data);
```
### TypeScript Integration
Use TypeScript for type safety (highly recommended):
```typescript
// types/express.d.ts
import { User } from './user';
declare global {
namespace Express {
interface Request {
user?: User;
validated?: unknown;
}
}
}
// controllers/user.controller.ts
import { Request, Response, NextFunction } from 'express';
import { UserService } from '../services/user.service';
export class UserController {
constructor(private userService: UserService) {}
findById = async (req: Request, res: Response): Promise<void> => {
const user = await this.userService.findById(req.params.id);
res.json(user);
};
}
```
## Express.js Design Patterns
### Controller-Service-Repository Pattern
Separate concerns into distinct layers:
```javascript
// repositories/user.repository.js
export class UserRepository {
constructor(db) {
this.db = db;
}
async findById(id) {
return this.db.query('SELECT * FROM users WHERE id = $1', [id]);
}
async create(userData) {
const { name, email, passwordHash } = userData;
return this.db.query(
'INSERT INTO users (name, email, password_hash) VALUES ($1, $2, $3) RETURNING *',
[name, email, passwordHash]
);
}
async update(id, userData) {
// Update logic
}
}
// services/user.service.js
import { hash } from 'bcrypt';
import { NotFoundError, ConflictError } from '../errors/index.js';
export class UserService {
constructor(userRepository) {
this.userRepository = userRepository;
}
async findById(id) {
const user = await this.userRepository.findById(id);
if (!user) {
throw new NotFoundError(`User with id ${id} not found`);
}
return user;
}
async create(userData) {
const existing = await this.userRepository.findByEmail(userData.email);
if (existing) {
throw new ConflictError('Email already in use');
}
const passwordHash = await hash(userData.password, 12);
return this.userRepository.create({
...userData,
passwordHash,
});
}
}
// controllers/user.controller.js
export class UserController {
constructor(userService) {
this.userService = userService;
}
findById = async (req, res) => {
const user = await this.userService.findById(req.params.id);
res.json(user);
};
create = async (req, res) => {
const user = await this.userService.create(req.validated);
res.status(201).json(user);
};
}
```
### Middleware Chains
Build reusable middleware chains:
```javascript
// middleware/chains.js
import { authenticate, authorize, validate, rateLimit } from './index.js';
export const publicRoute = [
Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.