Command Palette

Search for a command to run...

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

API Contracts Generator

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

Génère des contrats API cohérents entre Frontend (Next.js) et Backend (NestJS) avec types synchronisés, validation standardisée et error handling uniforme. À…

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

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

API Contracts Generator

🎯 Mission

Garantir une communication parfaite entre Frontend (Next.js) et Backend (NestJS) via des contrats API cohérents, types synchronisés et validation standardisée.

🏗️ Philosophie des API Contracts

Le Problème

Dans un projet full-stack, les erreurs de communication Frontend ↔ Backend sont fréquentes :

  • ❌ Types incohérents (backend attend clubId, frontend envoie id)
  • ❌ Validations divergentes (backend accepte 100 chars, frontend 50)
  • ❌ Erreurs non standardisées (format différent selon l'endpoint)
  • ❌ Documentation obsolète (Swagger non à jour)

La Solution : API Contracts

Un API Contract définit le contrat entre frontend et backend :

  • ✅ DTOs Backend : Structure des requêtes/réponses avec validation
  • ✅ Types Frontend : TypeScript synchronisés avec le backend
  • ✅ Validation cohérente : Mêmes règles backend et frontend
  • ✅ Error format standard : Format uniforme pour toutes les erreurs
  • ✅ Documentation auto : Swagger généré depuis le code

Architecture de Communication

Frontend (Next.js)
  ↓ Server Action (avec types)
  ↓ Validation Zod
  ↓ fetch/axios
Backend (NestJS)
  ↓ Controller (avec DTOs)
  ↓ Validation class-validator
  ↓ Handler (CQRS)
  ↓ Response DTO
  ↑ JSON Response
Frontend (Next.js)
  ↑ Typed Response
  ↑ UI Update

📦 1. Backend DTOs (NestJS)

Request DTOs (Input)

Les Request DTOs définissent la structure des données envoyées par le frontend.

Template Request DTO

// volley-app-backend/src/club-management/presentation/dtos/create-club.dto.ts

import { IsString, IsNotEmpty, IsOptional, MaxLength, MinLength } from 'class-validator';
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';

export class CreateClubDto {
  @ApiProperty({
    description: 'Club name',
    example: 'Volley Club Paris',
    minLength: 3,
    maxLength: 100,
  })
  @IsString()
  @IsNotEmpty()
  @MinLength(3)
  @MaxLength(100)
  readonly name: string;

  @ApiPropertyOptional({
    description: 'Club description',
    example: 'Best volleyball club in Paris',
    maxLength: 500,
  })
  @IsString()
  @IsOptional()
  @MaxLength(500)
  readonly description?: string;
}

Règles pour Request DTOs :

  • ✅ Validation avec class-validator (IsString, IsNotEmpty, etc.)
  • ✅ Swagger decorators @ApiProperty pour documentation
  • ✅ readonly pour immutabilité
  • ✅ Types primitifs (string, number, boolean, Date)
  • ✅ Exemples dans Swagger (example)
  • ❌ JAMAIS de logique métier (seulement validation)

Response DTOs (Output)

Les Response DTOs définissent la structure des données retournées par le backend.

Template Response DTO

// volley-app-backend/src/club-management/presentation/dtos/club-detail.dto.ts

import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';

export class OwnerDto {
  @ApiProperty({ example: 'user-123' })
  id: string;

  @ApiProperty({ example: 'John Doe' })
  name: string;

  @ApiProperty({ example: '[email protected]' })
  email: string;
}

export class SubscriptionDto {
  @ApiProperty({ example: 'FREE', enum: ['FREE', 'PRO', 'UNLIMITED'] })
  plan: string;

  @ApiProperty({ example: 'ACTIVE', enum: ['ACTIVE', 'INACTIVE', 'EXPIRED'] })
  status: string;

  @ApiProperty({ example: 1 })
  maxTeams: number;

  @ApiProperty({ example: 0 })
  currentTeamsCount: number;
}

export class ClubDetailDto {
  @ApiProperty({ example: 'club-123' })
  id: string;

  @ApiProperty({ example: 'Volley Club Paris' })
  name: string;

  @ApiPropertyOptional({ example: 'Best club in Paris' })
  description?: string;

  @ApiProperty({ type: OwnerDto })
  owner: OwnerDto;

  @ApiProperty({ type: SubscriptionDto })
  subscription: SubscriptionDto;

  @ApiProperty({ example: 15 })
  membersCount: number;

  @ApiProperty({ example: '2024-01-01T00:00:00.000Z' })
  createdAt: Date;
}

Règles pour Response DTOs :

  • ✅ Swagger decorators pour documentation complète
  • ✅ Nested DTOs pour relations (OwnerDto, SubscriptionDto)
  • ✅ Exemples réalistes
  • ✅ Enum values documentés
  • ✅ Types primitifs + nested objects
  • ❌ JAMAIS d'entités domain brutes (utiliser des mappers)

Pagination DTO (Standard)

// volley-app-backend/src/shared/dtos/pagination.dto.ts

import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { Type } from 'class-transformer';
import { IsInt, IsOptional, Max, Min } from 'class-validator';

export class PaginationQueryDto {
  @ApiPropertyOptional({ default: 1, minimum: 1 })
  @IsOptional()
  @Type(() => Number)
  @IsInt()
  @Min(1)
  page?: number = 1;

  @ApiPropertyOptional({ default: 10, minimum: 1, maximum: 100 })
  @IsOptional()
  @Type(() => Number)
  @IsInt()
  @Min(1)
  @Max(100)
  limit?: number = 10;
}

export class PaginationMetaDto {
  @ApiProperty({ example: 1 })
  page: number;

  @ApiProperty({ example: 10 })
  limit: number;

  @ApiProperty({ example: 50 })
  total: numb
Полный SKILL.md на GitHub

Установить API Contracts Generator в Claude Code и Claude Desktop

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

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

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

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

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

Read
Write
Edit
Glob
Grep
Bash

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

metadata.json

FAQ

Что делает скилл API Contracts Generator?

Génère des contrats API cohérents entre Frontend (Next.js) et Backend (NestJS) avec types synchronisés, validation standardisée et error handling uniforme. À utiliser lors de la création d'APIs, DTOs, types frontend/backend, ou quand l'utilisateur mentionne "API", "DTO", "types", "contract", "validation", "frontend-backend", "synchronisation".

Как установить скилл API Contracts Generator?

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

Скилл API Contracts Generator запускает скрипты?

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

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

Сравнить API Contracts Generator с