Command Palette

Search for a command to run...

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

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от 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:

  • null and undefined values
  • 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
Полный SKILL.md на GitHub

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

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

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

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

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

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

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

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

metadata.json

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), без исполняемых скриптов.

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

Сравнить api-envelope-pattern с