Command Palette

Search for a command to run...

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

api-tier-architecture

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

3-tier API architecture (Convex WebSocket, SSE, REST) for cross-platform data fetching. Platform detection, hybrid hooks, DAL layer patterns. Triggers on…

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

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

API Tier Architecture

Three-tier API architecture for web (real-time) and mobile (battery-optimized) platforms.

Architecture Overview

Tier 1 (Web Desktop): Convex WebSocket - Real-time bidirectional subscription Tier 2 (Mobile): SSE - Server-Sent Events with polling (battery-optimized) Tier 3 (Mobile Fallback): REST - Standard HTTP polling

All tiers authenticated via withAuth middleware, data accessed via DAL layer.

Platform Detection

// From apps/web/src/lib/utils/platform.ts
export function shouldUseConvex(): boolean {
  return getDataFetchingStrategy() === "convex";
}

export function shouldUseSSE(): boolean {
  return getDataFetchingStrategy() === "sse";
}

// Detection hierarchy:
// 1. User-agent (iPhone, Android, mobile browsers)
// 2. Viewport width (< 768px)
// 3. Touch capability

Manual override for testing:

localStorage.setItem("blah_data_strategy", "convex"); // or "sse" or "polling"

Hybrid Hook Pattern

All data hooks use hybrid pattern: Convex for web, React Query for mobile.

// From apps/web/src/lib/hooks/queries/useConversations.ts
export function useConversations(options: UseConversationsOptions = {}) {
  const { page = 1, pageSize = 20, archived = false } = options;
  const useConvexMode = shouldUseConvex();
  const apiClient = useApiClient();

  // Tier 1: Convex WebSocket subscription (web desktop)
  const convexData = useConvexQuery(
    api.conversations.list,
    useConvexMode && !archived ? {} : "skip",
  );

  // Tier 2/3: REST API query (mobile)
  const restQuery = useQuery({
    queryKey: ["conversations", { page, pageSize, archived }],
    queryFn: async () => {
      const params = new URLSearchParams({
        page: String(page),
        pageSize: String(pageSize),
        archived: String(archived),
      });
      return apiClient.get(`/conversations?${params}`);
    },
    enabled: !useConvexMode,
    staleTime: 30_000, // 30s cache
  });

  // Return unified interface
  if (useConvexMode) {
    return {
      data: convexData ? { items: convexData, ... } : undefined,
      isLoading: convexData === undefined,
      error: null,
      refetch: () => Promise.resolve(),
    };
  }

  return {
    data: restQuery.data,
    isLoading: restQuery.isLoading,
    error: restQuery.error,
    refetch: restQuery.refetch,
  };
}

Key conventions:

  • Import both useQuery from @tanstack/react-query and useQuery as useConvexQuery from convex/react
  • Check shouldUseConvex() before rendering
  • Pass "skip" to Convex query when disabled
  • Return unified interface: { data, isLoading, error, refetch }

DAL Layer (Data Access Layer)

Server-only Convex client wrappers. Never import in client components.

// From apps/web/src/lib/api/dal/conversations.ts
import "server-only";

export const conversationsDAL = {
  create: async (_userId: string, data: CreateInput) => {
    const validated = createConversationSchema.parse(data);
    const convex = getConvexClient();

    const conversationId = (await (convex.mutation as any)(
      // @ts-ignore - TypeScript recursion limit with 94+ Convex modules
      api.conversations.create,
      { ...validated },
    )) as any;

    const conversation = (await (convex.query as any)(
      // @ts-ignore - TypeScript recursion limit with 94+ Convex modules
      api.conversations.get,
      { conversationId },
    )) as any;

    return formatEntity(conversation, "conversation", conversation._id);
  },

  getById: async (userId: string, conversationId: string) => {
    const convex = getConvexClient();

    // Uses clerkId for server-side ownership verification
    const conversation = (await (convex.query as any)(
      // @ts-ignore - TypeScript recursion limit with 94+ Convex modules
      api.conversations.getWithClerkVerification,
      { conversationId: conversationId as Id<"conversations">, clerkId: userId },
    )) as any;

    if (!conversation) {
      throw new Error("Conversation not found or access denied");
    }

    return formatEntity(conversation, "conversation", conversation._id);
  },

  // Always verify ownership before mutations
  update: async (userId: string, conversationId: string, data: UpdateInput) => {
    await conversationsDAL.getById(userId, conversationId); // Ownership check
    // ... perform mutation
  },
};

DAL conventions:

  • Always validate input with Zod schemas
  • Use (convex.mutation as any) + @ts-ignore for type recursion workaround
  • Always wrap responses with formatEntity(data, "entityName", id)
  • Verify ownership before mutations (call getById first)
  • For mutations requiring ctx.auth, use getAuthenticatedConvexClient(sessionToken)

REST API Routes (Tier 3)

// From apps/web/src/app/api/v1/conversations/route.ts
async function postHandler(req: NextRequest, { userId }: { userId: string }) {
  const startTime = performance.now();
  logger.info({ userId }, "POST /
Полный SKILL.md на GitHub

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

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

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

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

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

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

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

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

metadata.json

FAQ

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

3-tier API architecture (Convex WebSocket, SSE, REST) for cross-platform data fetching. Platform detection, hybrid hooks, DAL layer patterns. Triggers on "API", "tier", "Convex", "REST", "SSE", "useConvexQuery", "useQuery", "withAuth", "DAL".

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

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

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

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

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

Сравнить api-tier-architecture с