api-handler
БесплатноБез исполняемых скриптовНе проверенStepLeague API route pattern using withApiHandler wrapper. Use when creating or modifying any API route in the /api directory. Keywords: API, route, endpoint…
от diegosouzapw★ 68 звёзд на GitHubОб этом скилле
API Handler Skill
Overview
Use withApiHandler for all API routes. It eliminates boilerplate and ensures consistent auth, validation, and error handling.
Basic Usage
import { withApiHandler } from "@/lib/api/handler";
import { z } from "zod";
const mySchema = z.object({
name: z.string(),
count: z.number().optional(),
});
export const POST = withApiHandler({
auth: 'required',
schema: mySchema,
}, async ({ user, body, adminClient }) => {
const { data } = await adminClient
.from("table")
.insert({ ...body, user_id: user.id })
.select()
.single();
return { success: true, data };
});
Auth Levels
| Level | Description | Context Provided |
|---|---|---|
'none' |
No auth required | user may be null |
'required' |
Must be logged in | user guaranteed |
'superadmin' |
Site-wide superadmin | user guaranteed, verified superadmin |
'league_member' |
Must be league member | user, membership |
'league_admin' |
Must be admin or owner | user, membership (admin/owner role) |
'league_owner' |
Must be owner | user, membership (owner role) |
League Auth Examples
// Any league member can access
export const GET = withApiHandler({
auth: 'league_member',
}, async ({ user, membership }) => {
// membership.role is 'owner', 'admin', or 'member'
return { role: membership?.role };
});
// Only admins and owners
export const PUT = withApiHandler({
auth: 'league_admin',
schema: updateSchema,
}, async ({ user, body, adminClient, membership }) => {
// membership.role is guaranteed 'admin' or 'owner'
return { updated: true };
});
League ID Resolution
For league auth, the handler looks for league_id in this order:
- Request body (
{ league_id: "..." }) - URL params (
/api/leagues/[id]) - Query params (
?league_id=...)
Handler Context
The handler function receives:
interface HandlerContext<T> {
user: User | null; // Authenticated user
body: T; // Parsed & validated request body
adminClient: SupabaseClient; // Admin client (bypasses RLS)
request: Request; // Original request
params: Record<string, string>; // URL params (e.g., { id: 'xxx' })
membership: Membership | null; // For league_* auth levels
}
Schema Validation
Use Zod for request validation:
const createSchema = z.object({
name: z.string().min(1).max(100),
description: z.string().optional(),
is_active: z.boolean().default(true),
league_id: z.string().uuid(),
});
export const POST = withApiHandler({
auth: 'required',
schema: createSchema,
}, async ({ body }) => {
// body is fully typed and validated
console.log(body.name); // string
console.log(body.is_active); // boolean (defaulted to true if not provided)
});
Validation Errors
If validation fails, the handler automatically returns:
{
"error": "Validation failed: name: Required, league_id: Invalid uuid"
}
Returning Responses
Return Object (Auto-wrapped)
return { success: true, data };
// Becomes: Response with JSON { success: true, data }
Return Response Directly
import { json, badRequest, forbidden } from "@/lib/api";
// Custom status or headers
return json({ data }, { status: 201 });
// Error responses
return badRequest("Invalid input");
return forbidden("Not allowed");
Error Handling
Errors thrown in the handler are caught and logged:
export const POST = withApiHandler({
auth: 'required',
}, async ({ adminClient }) => {
const { data, error } = await adminClient.from("table").insert({});
if (error) {
// Use AppError for typed errors
throw new AppError({
code: ErrorCode.DB_INSERT_FAILED,
message: error.message,
context: { table: 'table' },
});
}
return { success: true };
});
Reference the error-handling skill for more on AppError.
Complete Example
// src/app/api/leagues/[id]/members/route.ts
import { withApiHandler } from "@/lib/api/handler";
import { z } from "zod";
import { AppError, ErrorCode } from "@/lib/errors";
const addMemberSchema = z.object({
user_id: z.string().uuid(),
role: z.enum(['member', 'admin']).default('member'),
});
// GET - List members (any league member can view)
export const GET = withApiHandler({
auth: 'league_member',
}, async ({ params, adminClient }) => {
const { data } = await adminClient
.from("memberships")
.select("*, users(*)")
.eq("league_id", params.id);
return { members: data };
});
// POST - Add member (only admins/owners)
export const POST = withApiHandler({
auth: 'league_admin',
schema: addMemberSchema,
}, async ({ params, body, adminClient }) => {
const { data, error } = await adminClient
.from("memberships")
.insert({
league_id: params.id,
Установить api-handler в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл api-handler?
StepLeague API route pattern using withApiHandler wrapper. Use when creating or modifying any API route in the /api directory. Keywords: API, route, endpoint, handler, auth, POST, GET, PUT, DELETE, validation.
Как установить скилл api-handler?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл api-handler запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic