본문으로 건너뛰기
Skillpedia
API 및 서버 (백엔드)48k · #4638

fp-async

하는 일

이 도구는 시간이 걸리는 비동기 작업(완료에 시간이 필요한 작업)을 코드에서 체계적으로 관리하도록 돕습니다. 특히 실패할 수 있는 작업에 유용합니다. 「TaskEither」라는 방법을 사용해 오류가 명확하고 체계적으로 처리되도록 하여 혼란을 피합니다.

사용하는 경우

  • ✓API에서 데이터를 가져오거나 데이터베이스에 정보를 저장하는 등 시간이 걸리는 작업을 처리해야 할 때.
  • ✓여러 겹의 중첩된 `try/catch` 블록으로 비동기 코드의 오류 처리를 정리하기 어려울 때.
  • ✓순서대로 실행되어야 하고 오류를 일관되게 관리해야 하는 비동기 작업의 연속을 만들 때.

스킬 링크

https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/fp-async/SKILL.md

복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.

사용 방법

가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

Use this skill to help me: https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/fp-async/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 15,000+개 중에서 검색합니다.1분 만에 설치 →

AI에게 요청하는 예시

“`TaskEither`를 사용해 API에서 데이터를 가져오고 네트워크 오류를 처리하려면 어떻게 하나요?”

매주 새 스킬 5개. 읽는 데 1분.

작동 방식

도구는 `TaskEither`를 사용합니다. 이것은 성공한 결과나 오류 중 하나를 담을 수 있는 상자와 같습니다. 비동기 작업을 연결할 수 있으며, 한 작업이 실패하면 오류를 잡아내 프로그램의 흐름을 방해하지 않고 깔끔하게 처리합니다.

기술 내용 (원본 SKILL.md)

작성자의 영어 원문을 GitHub에서 그대로 가져왔습니다.

Practical Async Patterns with fp-ts

Stop writing nested try/catch blocks. Stop losing error context. Start building clean async pipelines that handle errors properly.

TaskEither is simply an async operation that tracks success or failure. That's it. No fancy terminology needed.

Detailed Guide

Read the detailed guide before executing this skill. It retains the complete procedure and reference material. Treat its safety, prerequisites, and validation requirements as mandatory. For focused work, load the relevant sections; for end-to-end work, read the guide completely.

When to Use

  • You need async error handling in TypeScript with TaskEither.
  • The task involves wrapping Promises, composing API calls, or replacing nested try/catch flows.
  • You want practical fp-ts async patterns instead of academic explanations.
// TaskEither<Error, User> means:
// "An async operation that either fails with Error or succeeds with User"

5. Real API Examples

Complete Fetch Wrapper

// types.ts
interface ApiError {
  code: string
  message: string
  status: number
  details?: unknown
}

// api.ts
const createApiError = (
  code: string,
  message: string,
  status: number,
  details?: unknown
): ApiError => ({ code, message, status, details })

const request = <T>(
  url: string,
  options: RequestInit = {}
): TE.TaskEither<ApiError, T> =>
  TE.tryCatch(
    async () => {
      const response = await fetch(url, {
        headers: {
          'Content-Type': 'application/json',
          ...options.headers,
        },
        ...options,
      })

      if (!response.ok) {
        const body = await response.json().catch(() => ({}))
        throw createApiError(
          body.code || 'HTTP_ERROR',
          body.message || response.statusText,
          response.status,
          body
        )
      }

      // Handle 204 No Content
      if (response.status === 204) {
        return undefined as T
      }

      return response.json()
    },
    (error): ApiError => {
      if (typeof error === 'object' && error !== null && 'code' in error) {
        return error as ApiError
      }
      return createApiError(
        'NETWORK_ERROR',
        error instanceof Error ? error.message : 'Request failed',
        0
      )
    }
  )

// API client
const api = {
  get: <T>(url: string) => request<T>(url),

  post: <T>(url: string, body: unknown) =>
    request<T>(url, {
      method: 'POST',
      body: JSON.stringify(body)
    }),

  put: <T>(url: string, body: unknown) =>
    request<T>(url, {
      method: 'PUT',
      body: JSON.stringify(body)
    }),

  delete: (url: string) =>
    request<void>(url, { method: 'DELETE' }),
}

// Usage
const getUser = (id: string) => api.get<User>(`/api/users/${id}`)
const createUser = (data: CreateUserDto) => api.post<User>('/api/users', data)
const updateUser = (id: string, data: UpdateUserDto) => api.put<User>(`/api/users/${id}`, data)
const deleteUser = (id: string) => api.delete(`/api/users/${id}`)

Database Operations (Prisma Example)

import { PrismaClient, Prisma } from '@prisma/client'

type DbError =
  | { _tag: 'NotFound'; entity: string; id: string }
  | { _tag: 'UniqueViolation'; field: string }
  | { _tag: 'ConnectionError'; cause: unknown }

const prisma = new PrismaClient()

const wrapPrisma = <T>(
  operation: () => Promise<T>
): TE.TaskEither<DbError, T> =>
  TE.tryCatch(
    operation,
    (error): DbError => {
      if (error instanceof Prisma.PrismaClientKnownRequestError) {
        if (error.code === 'P2002') {
          const field = (error.meta?.target as string[])?.join(', ') || 'unknown'
          return { _tag: 'UniqueViolation', field }
        }
        if (error.code === 'P2025') {
          return { _tag: 'NotFound', entity: 'Record', id: 'unknown' }
        }
      }
      return { _tag: 'ConnectionError', cause: error }
    }
  )

// Repository pattern
const userRepository = {
  findById: (id: string): TE.TaskEither<DbError, User> =>
    pipe(
      wrapPrisma(() => prisma.user.findUnique({ where: { id } })),
      TE.chain(user =>
        user
          ? TE.right(user)
          : TE.left({ _tag: 'NotFound', entity: 'User', id })
      )
    ),

  findByEmail: (email: string): TE.TaskEither<DbError, User | null> =>
    wrapPrisma(() => prisma.user.findUnique({ where: { email } })),

  create: (data: CreateUserInput): TE.TaskEither<DbError, User> =>

…
자주 묻는 질문

`TaskEither`란 무엇인가요?

성공하거나 실패할 수 있는 비동기 작업을 나타내는 방법입니다. 예상된 결과 또는 발생한 오류 설명을 담은 꾸러미라고 생각하면 됩니다.

왜 `try/catch` 대신 이것을 사용하나요?

`TaskEither`를 쓰면 중첩된 `try/catch` 블록을 많이 피할 수 있어 코드가 혼란스러워지지 않습니다. 비동기 작업의 오류를 더 구조적이고 명확하게 처리할 수 있습니다.

고급 프로그래밍을 알아야 하나요?

꼭 그렇지는 않습니다. 함수형 프로그래밍 개념을 일부 사용하지만, 핵심 아이디어는 시간이 걸리는 작업의 오류 처리를 단순하게 하여 코드를 더 읽기 쉽게 만드는 것입니다.

상세 정보

작성자의 원본 설명

Practical async patterns using TaskEither - clean pipelines instead of try/catch hell, with real API examples

repo: sickn33/agentic-awesome-skills

인기도

GitHub 스타
48k
순위
#4638
라이선스
MIT
업데이트
2026. 10. 15.

이 스킬이 유용한가요?

0

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬