Command Palette

Search for a command to run...

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

effect-portable-patterns

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

Portable Effect patterns for robust promise execution. Use when wrapping async operations with timeouts, retries, tagged errors, caching, concurrency, pattern…

millioncoот millionco★ 3 558 звёзд на GitHub

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

Effect as a Portable Promise Utility

Use Effect as a lightweight utility for running promises robustly. Every effect is self-contained (no services, no layers, no dependency injection) and resolves to a plain Promise at the boundary via Effect.runPromise.

The shape is always: Effect.fn or Effect.gen -> pipe operators -> Effect.runPromise.

Quick Reference

Capability API Avoid
Wrap promises Effect.tryPromise Effect.promise (swallows errors)
Define functions Effect.fn("name") Anonymous generators
Errors Data.TaggedError with _tag Plain Error or untagged objects
Catch by tag catchTag / catchTags catchAll (loses type narrowing)
Fallbacks orElse, orElseSucceed Nested try/catch
Timeouts Effect.timeout / Effect.timeoutFail Manual AbortController + setTimeout
Retries Effect.retry with Schedule Manual retry loops
Caching Effect.cachedWithTTL / Effect.cachedFunction Manual Map-based caches
Concurrency Effect.all with { concurrency: N } Manual Promise.all chunking
Pattern matching Match.value / Match.type with Match.tag Switch statements on _tag
Tracing Effect.withSpan / Effect.annotateCurrentSpan Manual console.time
Run at boundary Effect.runPromise Effect.runSync for async work

Core Pattern: Portable Effect Functions

Every effect function follows this structure - build an Effect<Success, Error, never> (no requirements), then run it as a promise at the call site.

import { Effect, Data } from "effect";

class FetchError extends Data.TaggedError("FetchError")<{
  url: string;
  status: number;
  message: string;
}> {}

const fetchUser = Effect.fn("fetchUser")(function* (userId: string) {
  const response = yield* Effect.tryPromise({
    try: () => fetch(`/api/users/${userId}`),
    catch: () =>
      new FetchError({
        url: `/api/users/${userId}`,
        status: 0,
        message: "Network error",
      }),
  });

  if (!response.ok) {
    return yield* Effect.fail(
      new FetchError({
        url: `/api/users/${userId}`,
        status: response.status,
        message: response.statusText,
      }),
    );
  }

  const user = yield* Effect.tryPromise({
    try: () => response.json() as Promise<User>,
    catch: () =>
      new FetchError({
        url: `/api/users/${userId}`,
        status: response.status,
        message: "Invalid JSON",
      }),
  });

  return user;
});

// At the call site - always resolves to a plain Promise
const user: User = await Effect.runPromise(fetchUser("123"));

Tagged Errors

Define errors with Data.TaggedError. The _tag field enables type-safe error matching without services or schemas.

import { Data } from "effect";

class TimeoutError extends Data.TaggedError("TimeoutError")<{
  operation: string;
  durationMs: number;
}> {}

class NotFoundError extends Data.TaggedError("NotFoundError")<{
  resource: string;
  id: string;
}> {}

class ValidationError extends Data.TaggedError("ValidationError")<{
  field: string;
  message: string;
}> {}

Catching Errors by Tag

Use catchTag for single tags, catchTags for multiple. Both preserve type narrowing.

const result =
  yield *
  fetchUser("123").pipe(
    Effect.catchTag("NotFoundError", (error) =>
      Effect.succeed({ id: error.id, name: "Unknown", fallback: true }),
    ),
    Effect.catchTag("TimeoutError", (error) =>
      Effect.fail(
        new ServiceUnavailableError({
          message: `${error.operation} timed out`,
        }),
      ),
    ),
  );

// Or handle multiple tags at once
const result =
  yield *
  fetchUser("123").pipe(
    Effect.catchTags({
      NotFoundError: (error) => Effect.succeed(defaultUser),
      ValidationError: (error) => Effect.fail(new BadRequestError({ message: error.message })),
    }),
  );

Timeouts

Basic Timeout (raises TimeoutException)

const result = yield * fetchUser("123").pipe(Effect.timeout("5 seconds"));

Timeout with Custom Error

const result =
  yield *
  fetchUser("123").pipe(
    Effect.timeoutFail({
      duration: "5 seconds",
      onTimeout: () => new TimeoutError({ operation: "fetchUser", durationMs: 5000 }),
    }),
  );

Timeout with Fallback Value

co
Полный SKILL.md на GitHub

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

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

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

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

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

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

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

FAQ

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

Portable Effect patterns for robust promise execution. Use when wrapping async operations with timeouts, retries, tagged errors, caching, concurrency, pattern matching, or tracing - all designed to resolve to a plain Promise via Effect.runPromise.

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

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

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

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

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

Сравнить effect-portable-patterns с