Command Palette

Search for a command to run...

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

fastify

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

Fastify is a fast Node.js web framework for building JSON APIs, with JSON Schema validation and serialization, an encapsulated plugin system and lifecycle…

TerminalSkillsот TerminalSkills★ 221 звезда на GitHub

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

Fastify

Overview

Fastify is a low-overhead Node.js web framework. Requests are validated and responses serialized through JSON Schema, and code is organized in encapsulated plugins. This skill targets Fastify 5 (Node.js 20 or newer; the examples use import.meta.dirname, which needs 20.11+). Fastify 5 needs a full JSON Schema object for querystring, params, body and responses (the shorthand without type: 'object' was removed), and listen() takes an options object, not positional arguments.

Instructions

Install

mkdir articles-api && cd articles-api
npm init -y
npm pkg set type=module
npm i fastify @fastify/autoload @fastify/sensible @fastify/cors @fastify/jwt fastify-plugin pg

Layout

src/
├── app.js             # app factory (also used by tests)
├── server.js          # entry point
├── plugins/           # shared plugins, wrapped in fastify-plugin
│   ├── db.js
│   └── auth.js
└── routes/
    └── articles/
        ├── index.js   # route handlers
        └── schema.js  # JSON schemas
test/
└── articles.test.js

App factory and entry point

// src/app.js — autoload plugins, then routes under /api
import Fastify from 'fastify';
import autoload from '@fastify/autoload';
import sensible from '@fastify/sensible';
import cors from '@fastify/cors';
import { join } from 'node:path';

export function buildApp(opts = {}) {
  const app = Fastify({ logger: true, ...opts });

  app.register(sensible);
  app.register(cors, { origin: process.env.CORS_ORIGIN?.split(',') ?? false });
  app.register(autoload, { dir: join(import.meta.dirname, 'plugins') });
  app.register(autoload, {
    dir: join(import.meta.dirname, 'routes'),
    options: { prefix: '/api' },
  });

  return app;
}
// src/server.js
import { buildApp } from './app.js';

const app = buildApp();
try {
  await app.listen({ port: 3000, host: '127.0.0.1' });
} catch (err) {
  app.log.error(err);
  process.exit(1);
}

Bind to 127.0.0.1 for local work. Use 0.0.0.0 only inside a container where a proxy fronts the service.

Schemas and routes

// src/routes/articles/schema.js
export const articleSchema = {
  type: 'object',
  properties: {
    id: { type: 'integer' },
    title: { type: 'string' },
    body: { type: 'string' },
    created_at: { type: 'string', format: 'date-time' },
  },
};

export const listArticlesSchema = {
  querystring: {
    type: 'object',
    properties: {
      page: { type: 'integer', minimum: 1, default: 1 },
      limit: { type: 'integer', minimum: 1, maximum: 100, default: 20 },
    },
  },
  response: { 200: { type: 'array', items: articleSchema } },
};

export const createArticleSchema = {
  body: {
    type: 'object',
    required: ['title', 'body'],
    additionalProperties: false,
    properties: {
      title: { type: 'string', minLength: 1, maxLength: 200 },
      body: { type: 'string' },
    },
  },
  response: { 201: articleSchema },
};
// src/routes/articles/index.js
import { listArticlesSchema, createArticleSchema } from './schema.js';

export default async function articleRoutes(fastify) {
  fastify.get('/', { schema: listArticlesSchema }, async (request) => {
    const { page, limit } = request.query;   // already coerced to numbers, defaults applied
    const { rows } = await fastify.db.query(
      'SELECT * FROM articles ORDER BY created_at DESC LIMIT $1 OFFSET $2',
      [limit, (page - 1) * limit]
    );
    return rows;
  });

  fastify.get('/:id', {
    schema: { params: { type: 'object', properties: { id: { type: 'integer' } } } },
  }, async (request, reply) => {
    const { rows } = await fastify.db.query('SELECT * FROM articles WHERE id = $1', [request.params.id]);
    if (!rows[0]) return reply.notFound();
    return rows[0];
  });

  fastify.post('/', { schema: createArticleSchema, onRequest: [fastify.authenticate] }, async (request, reply) => {
    const { title, body } = request.body;
    const { rows } = await fastify.db.query(
      'INSERT INTO articles (title, body) VALUES ($1, $2) RETURNING *',
      [title, body]
    );
    return reply.code(201).send(rows[0]);
  });
}

Plugins

// src/plugins/db.js — pg pool shared as fastify.db
import fp from 'fastify-plugin';
import pg from 'pg';

export default fp(async function dbPlugin(fastify) {
  const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });
  fastify.decorate('db', pool);
  fastify.addHook('onClose', async () => { await pool.end(); });
});
// src/plugins/auth.js — JWT verification as fastify.authenticate
import fp from 'fastify-plugin';
import jwt from '@fastify/jwt';

export default fp(async function authPlugin(fastify) {
  fastify.register(jwt, { secret: process.env.JWT_SECRET });

  fastify.decorate('authenticate', async function (request, reply) {
    try {
      await request.jwtVerify();
    } catch (err) {
      return reply.unauthorized();
    }
  });
}
Полный SKILL.md на GitHub

Установить fastify в Claude Code и Claude Desktop

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

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

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

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

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

Без ограничений — скилл может использовать любой инструмент.

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

_scores.json

FAQ

Что делает скилл fastify?

Fastify is a fast Node.js web framework for building JSON APIs, with JSON Schema validation and serialization, an encapsulated plugin system and lifecycle hooks. Use when the user wants to build or test a Fastify 5 REST API, add schema validation, JWT auth, a database plugin, CORS, hooks or error handling, or asks about Fastify project structure and plugin encapsulation.

Как установить скилл fastify?

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

Скилл fastify запускает скрипты?

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

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

Сравнить fastify с