Command Palette

Search for a command to run...

Назад к скиллам
скилл № 51918

elysia-patterns

Use when the user asks about Elysia Eden Treaty clients, Elysia WebSocket pub/sub, Elysia macros, custom plugins, hook scopes (local, scoped, global) or file…

БесплатноБез исполняемых скриптов
j4flmaoот j4flmao★ 47 звёзд на GitHub

Установить elysia-patterns в Claude Code и Claude Desktop

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

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

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

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

Elysia Patterns

Purpose

Implement Elysia.js-specific patterns — Eden Treaty type-safe client, WebSocket with Bun, macro-based guards, custom plugins, and validation patterns.

Agent Protocol

Trigger

User request includes: elysia pattern, elysia eden treaty, elysia websocket, elysia plugin, elysia macro, elysia validation, elysia type safe.

Input Context

  • Elysia version and plugin set
  • Server-side patterns needed (auth, middleware, validation)
  • Client-side (React, Svelte, Vue) for Eden Treaty

Output Artifact

Code examples for the requested patterns — plugin, macro, WebSocket handler, Eden client.

Response Format

Code-first: pattern name, problem, implementation. Compress output.

Completion Criteria

  • Pattern implemented with type safety
  • Schema validation applied
  • Error handling included
  • Test example provided

Max Response Length

4096 tokens

Architecture Decision Trees

Eden Treaty vs tRPC vs REST+OpenAPI

Criterion Eden Treaty tRPC REST+OpenAPI
Backend Elysia only TypeScript servers (Node, Bun, Deno, edge adapters) Any
Type safety Full-stack inference Full-stack inference Generated client
Setup Single typeof app Manual procedure defs External tooling
File upload Declarative Manual Multipart
Websocket Via plugin Via subscription Separate
Flexibility Elysia-native tRPC server Any HTTP

Decision: Elysia backend + any frontend → Eden Treaty. tRPC backend → tRPC fits better. Multi-language clients → REST+OpenAPI.

Macro vs Middleware vs Plugin

Pattern Scope Use Case
Macro (.macro(), enabled per route or guard) Route-level Auth check, permission guard
Middleware (onRequest, beforeHandle) Global or group Logging, CORS, rate limit
Plugin (new Elysia({name})) Modular feature User module, auth module

Decision: Reusable route modifier → Macro. Cross-cutting concern → Middleware. Standalone feature → Plugin.

Workflow

Step 1: Eden Treaty Full-Stack Setup

// server/src/app.ts — EXPORT TYPE
import { Elysia } from 'elysia'
import { userModule } from './modules/users'

export const app = new Elysia()
  .use(userModule)
  .get('/health', () => ({ status: 'ok' }))

export type App = typeof app

// client/src/api.ts
import { treaty } from '@elysiajs/eden' // Eden Treaty 2
import type { App } from '../../server/src/app'

export const client = treaty<App>('localhost:3000', {
  headers: () => ({
    authorization: `Bearer ${localStorage.getItem('token')}`,
  }),
})

// Usage (e.g. inside a data-fetching hook)
export async function loadUser(id: string) {
  const { data, error } = await client.users({ id }).get()
  if (error) throw new Error(`Failed to load user ${id}: HTTP ${error.status}`)
  return data
}

Step 2: WebSocket Pattern

// src/plugins/realtime.ts — WebSocket support is built into Elysia (Bun's uWebSockets), no plugin needed
import { Elysia, t } from 'elysia'

export const realtimePlugin = new Elysia({ name: 'realtime' })
  .ws('/ws/orders/:orderId', {
    body: t.Object({
      type: t.String(),
      payload: t.Any(),
    }),
    async open(ws) {
      ws.subscribe(`order:${ws.data.params.orderId}`)
      ws.send({ type: 'connected', payload: { orderId: ws.data.params.orderId } })
    },
    async message(ws, message) {
      // Broadcast to all subscribers of this order
      ws.publish(`order:${ws.data.params.orderId}`, message)
    },
    async close(ws) {
      ws.unsubscribe(`order:${ws.data.params.orderId}`)
    },
  })

// Emit from service code (app = the listening Elysia instance)
function notifyOrderStatus(orderId: string, status: string) {
  app.server?.publish(`order:${orderId}`, JSON.stringify({
    type: 'status_update',
    payload: { orderId, status },
  }))
}
// Pub/sub is per process; fan out through Redis/NATS when running several instances.

Step 3: Custom Plugin with Lifecycle

// src/plugins/audit-log.ts
import { Elysia } from 'elysia'

interface AuditLogConfig {
  excludePaths?: string[]
  db: { save: (entry: AuditEntry) => Promise<void> }
}

interface AuditEntry {
  method: string
  path: string
  userId: string | null
  statusCode: number
  duration: number
  timestamp: Date
}

export const auditLogPlugin = (config: AuditLogConfig) =>
  new Elysia({ name: 'audit-log' })
    .derive({ as: 'global' }, () => ({ startTime: performance.now() }))
    .onAfterResponse({ as: 'global' }, (ctx) => {
      const { request, set, startTime } = ctx
      const url = new URL(request.url)
      if (config.excludePaths?.includes(url.pathname)) return

      const entry: AuditEntry = {
        method: request.method,
        path: url.pathname,
        userId: (ctx as { user?: { id: string } }).user?.id ?? null, // set by auth plugin if present
        statusCode: typeof set.stat
Полный SKILL.md на GitHub

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

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

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

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

  • references/eden-treaty.md
  • references/elysia-auth.md
  • references/elysia-performance.md
  • references/elysia-plugins.md
  • references/elysia-validation.md
  • references/elysia-websocket.md

FAQ

Что делает скилл elysia-patterns?

Use when the user asks about Elysia Eden Treaty clients, Elysia WebSocket pub/sub, Elysia macros, custom plugins, hook scopes (local, scoped, global) or file upload validation. Produces Elysia recipe code. Not for app folder structure (use elysia-architecture).

Как установить скилл elysia-patterns?

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

Скилл elysia-patterns запускает скрипты?

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

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

Сравнить elysia-patterns с