api-envelope-pattern
БесплатноБез исполняемых скриптовНе проверенStandard API envelope pattern for all responses (success/list/error). Wraps data in consistent structure with sys metadata, automatic payload compaction…
от diegosouzapw★ 68 звёзд на GitHubОб этом скилле
API Envelope Pattern
ALL API responses MUST use standard envelope pattern. NEVER return raw Convex docs or plain data. Consistent structure enables mobile clients, monitoring, caching.
Standard Envelope Structure
Every response wrapped in ApiResponse<T>:
// Success (single entity)
{
status: "success",
sys: {
entity: "conversation",
id: "j97...",
timestamps?: {
created: "2024-01-15T10:30:00.000Z",
updated: "2024-01-15T12:45:00.000Z",
retrieved: "2024-01-15T13:00:00.000Z"
}
},
data: { ... } // Compacted data (nulls/empty removed)
}
// List response
{
status: "success",
sys: { entity: "list" },
data: [
{
sys: { entity: "conversation", id: "j97..." },
data: { ... }
}
]
}
// Error response
{
status: "error",
sys: { entity: "error" },
error: "Resource not found" // or { message, code, details }
}
Entity Formatters
Use these helpers from @/lib/utils/formatEntity:
formatEntity (Single Item)
// From convex/api/dal/conversations.ts
return formatEntity(conversation, "conversation", conversation._id);
// Auto-injects timestamps from Convex _creationTime + updatedAt
// Compacts data (removes null/undefined/empty)
formatEntityList (Arrays)
// From convex/api/dal/conversations.ts
return conversations.map((conversation) =>
formatEntity(conversation, "conversation", conversation._id)
);
// Each item wrapped with sys metadata
// Lists use sys.entity = "list" at top level
formatErrorEntity (Errors)
// String error
return NextResponse.json(formatErrorEntity("Verse not found"), {
status: 404
});
// Structured error (from error middleware)
return NextResponse.json(
formatErrorEntity({
message: error.message,
code: error.code,
}),
{ status: error.statusCode }
);
// With details (e.g., Zod validation)
formatErrorEntity({
message: "Validation failed",
code: "VALIDATION_ERROR",
details: zodError.issues,
})
Compact Utility (30-40% Payload Reduction)
Automatically strips null/undefined/empty values:
// From lib/utils/payload.ts
compact({
a: 1,
b: null,
c: undefined,
d: "",
e: [],
f: { nested: null }
})
// Returns: { a: 1 }
// Applied automatically in formatEntity/formatEntityList
// Recursive for nested objects and arrays
What gets removed:
nullandundefinedvalues- Empty strings (
"") - Empty arrays (
[]) - Empty objects after compaction (
{})
Timestamp Injection
Automatic timestamp extraction from Convex:
// formatEntity reads:
// - data._creationTime → sys.timestamps.created
// - data.updatedAt → sys.timestamps.updated
// - new Date() → sys.timestamps.retrieved
// Example output
{
sys: {
entity: "conversation",
id: "j97...",
timestamps: {
created: "2024-01-15T10:30:00.000Z",
updated: "2024-01-15T12:45:00.000Z",
retrieved: "2024-01-15T13:00:00.000Z"
}
}
}
DAL Layer Pattern
Data Access Layer (DAL) functions MUST return formatted entities:
// From lib/api/dal/conversations.ts
export const conversationsDAL = {
create: async (_userId: string, data: CreateData) => {
const conversationId = await convex.mutation(api.conversations.create, data);
const conversation = await convex.query(api.conversations.get, { conversationId });
// ALWAYS format before returning
return formatEntity(conversation, "conversation", conversation._id);
},
list: async (_userId: string, limit = 50, archived = false) => {
const conversations = await convex.query(api.conversations.list, { limit, archived });
// Map each item through formatEntity
return conversations.map((c) =>
formatEntity(c, "conversation", c._id)
);
},
delete: async (userId: string, conversationId: string, sessionToken: string) => {
await authConvex.mutation(api.conversations.deleteConversation, { conversationId });
// Even for operations without response data
return formatEntity(
{ deleted: true, conversationId },
"conversation",
conversationId
);
},
};
Route Handler Pattern
API routes wrap DAL responses:
// From app/api/v1/conversations/route.ts
async function postHandler(req: NextRequest, { userId }: { userId: string }) {
const body = await parseBody(req, createSchema);
const result = await conversationsDAL.create(userId, body);
// DAL already formatted - return directly
return NextResponse.json(result, { status: 201 });
}
async function getHandler(req: NextRequest, { userId }: { userId: string }) {
const conversations = await conversationsDAL.list(userId, limit, archived);
// Wrap list in top-level envelope
return NextResponse.json(
formatEntity(
{ items: conversations, total: conversations.length },
"list",
),
{ headers: { "Cache-Control": cacheControl } }
);
}
export const POST = withErrorHandl
Установить api-envelope-pattern в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл api-envelope-pattern?
Standard API envelope pattern for all responses (success/list/error). Wraps data in consistent structure with sys metadata, automatic payload compaction (30-40% reduction), timestamp injection. Triggers on "formatEntity", "formatEntityList", "formatErrorEntity", "API", "route handler", "dal".
Как установить скилл api-envelope-pattern?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл api-envelope-pattern запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
skill-creator
Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an…
от Anthropicdiscernment-nudge
After you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals…
от Anthropicdata-consolidate
Joins the plant's scheduled exports and connector data into one working dataset — ERP items (NetSuite or Infor M3), sales orders, production work orders…
от Anthropicinspection-to-capa
Runs the quality chain end to end: writes the nonconformance against the requirement it violates, searches history at the moment of writing to say whether…
от Anthropic