Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

express-api-patterns

БесплатноБез исполняемых скриптовНе проверен

Express.js API development, route handling, middleware, error handling, request validation, CORS. Use when building Express routes, implementing middleware…

diegosouzapwот diegosouzapw★ 68 звёзд на GitHub

Об этом скилле

Express API Patterns

Core Principles

  1. RESTful Design - Use HTTP methods appropriately (GET, POST, PUT, DELETE)
  2. Middleware First - Use middleware for cross-cutting concerns
  3. Error Handling - Centralized error handling middleware
  4. Validation - Validate all inputs before processing
  5. Security - CORS, rate limiting, input sanitization

Server Setup Pattern

CORRECT: Well-Structured Express Server

// server/index.js
import express from 'express';
import cors from 'cors';
import dotenv from 'dotenv';

// Load environment variables
dotenv.config();

// Import routes
import authRoutes from './routes/auth.js';
import generateRoutes from './routes/generate.js';
import imageRoutes from './routes/images.js';

const app = express();
const PORT = process.env.PORT || 3001;

// ===== Middleware =====

// CORS configuration
app.use(cors({
  origin: process.env.CLIENT_URL || 'http://localhost:5173',
  credentials: true
}));

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

// Request logging (development only)
if (process.env.NODE_ENV === 'development') {
  app.use((req, res, next) => {
    console.log(`${req.method} ${req.path}`);
    next();
  });
}

// ===== Routes =====

app.use('/api/auth', authRoutes);
app.use('/api/generate', generateRoutes);
app.use('/api/images', imageRoutes);

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

// ===== Error Handling =====

// 404 handler
app.use((req, res) => {
  res.status(404).json({ error: 'Endpoint not found' });
});

// Global error handler
app.use((err, req, res, next) => {
  console.error('Error:', err);

  const status = err.status || 500;
  const message = err.message || 'Internal server error';

  res.status(status).json({ error: message });
});

// ===== Start Server =====

app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
  console.log(`Environment: ${process.env.NODE_ENV || 'development'}`);
});

export default app;

Route Pattern

CORRECT: Well-Structured Route

// server/routes/generate.js
import express from 'express';
import { generatePage, generatePageStream } from '../services/claude.js';
import fs from 'fs/promises';
import path from 'path';

const router = express.Router();

// Load system prompt
let systemPrompt = '';
try {
  systemPrompt = await fs.readFile(
    path.join(process.cwd(), 'prompts', 'system.txt'),
    'utf-8'
  );
} catch (error) {
  console.error('Failed to load system prompt:', error);
}

/**
 * POST /api/generate
 * Generate or update instructional page
 */
router.post('/', async (req, res, next) => {
  try {
    // 1. Extract and validate input
    const { config, message, history = [] } = req.body;

    if (!config || !config.topic) {
      return res.status(400).json({ error: 'Topic is required' });
    }

    if (!message) {
      return res.status(400).json({ error: 'Message is required' });
    }

    if (config.depthLevel < 0 || config.depthLevel > 4) {
      return res.status(400).json({ error: 'Depth level must be 0-4' });
    }

    // 2. Call service
    const result = await generatePage(systemPrompt, config, message, history);

    // 3. Return response
    res.json({
      message: result.message,
      html: result.html,
      timestamp: new Date().toISOString()
    });

  } catch (error) {
    // Pass to error handler
    next(error);
  }
});

/**
 * POST /api/generate/stream
 * Generate page with streaming response
 */
router.post('/stream', async (req, res, next) => {
  try {
    const { config, message, history = [] } = req.body;

    // Validation (same as above)
    if (!config?.topic || !message) {
      return res.status(400).json({ error: 'Invalid request' });
    }

    // Set headers for Server-Sent Events
    res.setHeader('Content-Type', 'text/event-stream');
    res.setHeader('Cache-Control', 'no-cache');
    res.setHeader('Connection', 'keep-alive');

    // Stream generation
    await generatePageStream(systemPrompt, config, message, history, (chunk) => {
      res.write(`data: ${JSON.stringify(chunk)}\n\n`);
    });

    res.end();

  } catch (error) {
    next(error);
  }
});

export default router;

WRONG: Poor Route Structure

// ❌ DON'T DO THIS
router.post('/generate', (req, res) => {
  // ❌ No input validation
  // ❌ No error handling
  // ❌ Directly accessing nested properties without checks
  generatePage(req.body.config.topic, req.body.message).then(result => {
    res.send(result); // ❌ Not using res.json()
  });
});

Middleware Patterns

Authentication Middleware

// server/middleware/auth.js
export const verifyPassword = (req, res, next) => {
  const { password } = req.body;
  const correctPassword = process.env.FACULTY_PASSWORD;

  if (!correctPassword) {
    return res.status
Полный SKILL.md на GitHub

Установить express-api-patterns в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Read
Grep
Glob

Вложенные файлы

metadata.json

FAQ

Что делает скилл express-api-patterns?

Express.js API development, route handling, middleware, error handling, request validation, CORS. Use when building Express routes, implementing middleware, handling API requests, or setting up the backend server.

Как установить скилл express-api-patterns?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл express-api-patterns запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить express-api-patterns с