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★ 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
useQueryfrom@tanstack/react-queryanduseQuery as useConvexQueryfromconvex/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-ignorefor type recursion workaround - Always wrap responses with
formatEntity(data, "entityName", id) - Verify ownership before mutations (call
getByIdfirst) - For mutations requiring
ctx.auth, usegetAuthenticatedConvexClient(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 /
Установить api-tier-architecture в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
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), без исполняемых скриптов.
Похожие скиллы
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