Command Palette

Search for a command to run...

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

api

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

DraftForge frontend↔backend API binding: axios client, Zod response schemas, TanStack Query hooks, DRF errors, generated Zod from pydantic models, and…

kettleofketchupот kettleofketchup★ 16 звёзд на GitHub

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

API binding

Every HTTP call from the frontend goes through one client, returns data that a Zod schema has parsed, and reaches components through a query hook. The Zod schema either comes from a backend pydantic model (generated) or mirrors a DRF serializer (hand-written).

WebSocket messages (app/lib/websocket/) are out of scope.

Layout

New code lives in a feature folder (app/features/promotion/ is the reference):

File Holds
schemas.ts Zod schemas + z.infer types, or re-exports from a *.generated.ts
api.ts one async function per endpoint: call, parse, return
queryKeys.ts / queries.ts key factories; useQuery / useMutation hooks
__tests__/ Vitest for api.ts parsing and queries.ts invalidation

Legacy app/components/api/*API.tsx use axios.get<T>() with no validation. Don't copy that. When you touch one of those functions, move it to the parse pattern below.

Client

import api from '~/components/api/axios';

That instance sets the SSR/browser base URL, sends cookies, adds X-CSRFToken on writes and handles Discord Activity auth. Never import axios directly for requests, never use the bare instance in components/api/utils.tsx, and never call fetch. Paths are relative to /api and keep DRF's trailing slash: api.get(/events/${id}/). Pass query strings via { params }.

Endpoint functions

export async function getPromoTemplates(orgId: number): Promise<PromoTemplate[]> {
  const response = await api.get(`${base(orgId)}/templates/`);
  return z.array(PromoTemplateSchema).parse(response.data);
}
  • Parse every response body with Schema.parse. Don't use api.get<T>(): the type argument is an unchecked cast.
  • Keep the wire field names. DRF and pydantic API models send snake_case, so schemas use snake_case too. Rename only in a mapping function, never in the schema.
  • Type request bodies: generated request type, form schema output, or a local type.
  • Map "expected" statuses at the edge: isAxiosError(err) && err.response?.status === 404 → return null (see getPasswordInfo in app/components/lobby/api.ts). Let the rest throw.

Where the schema comes from

  1. The backend has (or should have) a pydantic model for the payload. Use a generated binding; don't hand-write it. Follow references/pydantic-bindings.md. Good fits: views that Model.model_validate(request.data) and return model.model_dump(mode="json"), new non-model endpoints, and static catalogues.
  2. The endpoint returns a DRF serializer. Hand-write the Zod schema in schemas.ts, field for field from the serializer (fields, read_only, SerializerMethodField return types, allow_null → .nullable(), required=False → .optional()). Note the serializer path in a one-line comment above the schema. For a payload where drift would hurt, pin it with a fixture both test suites read (backend/org/tests/render_fixture.json ↔ frontend/app/features/promotion/__tests__/, compared with cmp in the unit CI job).

Don't add drf-spectacular/OpenAPI codegen for one endpoint. Raise it with the user first.

Backend validation: pydantic first

Validate request bodies and stored JSON config with pydantic models, not hand-written isinstance/regex checks in the view or a helper module.

  • Put rules in the model: Annotated types with StringConstraints or AfterValidator for field shapes, field_validator for one field, model_validator(mode="after") for cross-field rules.
  • Keep API error codes stable with pydantic_core.PydanticCustomError("<code>", ...), then map the ValidationError to the code the endpoint returns.
  • Keep outside the model only what must run before it: size and depth guards on raw input, and normalisation that copies the validated model.
  • Example: backend/org/api_connections/types.py (rules) and backend/org/api_connections/schemas.py (validate_connection_config).
  • DRF serializers stay for model-backed CRUD that already uses them; new non-model payloads get a pydantic model.

Queries and mutations

  • Key factories in queryKeys.ts, with scope first and the viewer in the key when the response depends on permissions: promotionKeys.templates(orgId, viewerPk) (app/features/org-features/queryKeys.ts).
  • useQuery({ queryKey, queryFn: () => getX(...), enabled }). Gate on permission flags rather than letting the request 403.
  • Mutations invalidate or setQueryData the affected keys in onSuccess; prefix keys let you invalidate a whole feature.

Errors

  • User-facing message: extractApiError(err) from ~/lib/apiError (handles DRF error / detail / field-list shapes), then toast.error(msg ?? fallback).
  • A ZodError from parse is a contract bug, not a user error. Don't swallow it. Log it via getLogger and fix the schema or the backend.
  • Field errors on forms: map DRF {field: [msg]} onto React Hook Form `form.s
Полный SKILL.md на GitHub

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

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

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

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

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

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

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

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

references/pydantic-bindings.md

FAQ

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

DraftForge frontend↔backend API binding: axios client, Zod response schemas, TanStack Query hooks, DRF errors, generated Zod from pydantic models, and pydantic-first backend validation. Use when adding or changing an endpoint call or validating a request body or stored config.

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

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

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

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

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

Сравнить api с