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

webiny-use-case-pattern

하는 일

이 스킬은 Webiny 백엔드에서 하나의 비즈니스 작업을 작성할 때 AI를 안내합니다. 유스케이스나 그 뒤의 리포지토리를 만들거나 덮어쓰는 개발자를 위한 스킬입니다.

사용하는 경우

  • ✓항목 생성이나 발행처럼 새로운 비즈니스 작업이 필요할 때.
  • ✓기존 유스케이스를 교체하거나 감싸서 확장(decorate)하고 싶을 때.
  • ✓유스케이스가 CMS 리포지토리를 통해 데이터를 저장해야 하는 경우.

스킬 링크

https://github.com/webiny/webiny-js/blob/next/skills/user-skills/api/use-case-pattern/SKILL.md

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

사용 방법

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

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

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

AI에게 요청하는 예시

“CMS 항목을 발행하는 유스케이스를 작성해 주세요. 이미 발행되어 있으면 명확한 오류를 반환해야 합니다.”

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

작동 방식

이 스킬은 execute 메서드 하나, 타입이 지정된 입력, 성공 또는 실패를 보고하는 결과, 코드를 포함하는 오류 유형을 설명합니다. 또한 유스케이스가 다른 코드에 주입되는 방법도 보여 줍니다.

기술 내용 (원본 SKILL.md)

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

UseCase Pattern

What It Is

A UseCase is a single-method orchestrator that encapsulates one business operation (e.g., CreateTenantUseCase, PublishEntryUseCase). Each UseCase is a DI abstraction with an execute method that returns Result<T, E>.

Interface Shape

interface SomeUseCase.Interface {
    execute(input: Input): Promise<Result<ReturnType, ErrorType>>;
}
  • Input — a typed object specific to the use case
  • Result — always returns Result<T, E> from webiny/api
  • Error — extends BaseError with a unique code

How to Use a UseCase

UseCases are injected as dependencies into EventHandlers, other UseCases, or GraphQL resolvers via DI.

import { SomeUseCase } from "webiny/api/<category>";
import { SomeEventHandler } from "webiny/api/<category>";

class MyHandler implements SomeEventHandler.Interface {
  constructor(private someUseCase: SomeUseCase.Interface) {}

  async handle(event: SomeEventHandler.Event) {
    const result = await this.someUseCase.execute({/* input */});

    if (result.isFail()) {
      console.error(result.error.message);
      return;
    }

    const value = result.value;
    // ... use value
  }
}

export default SomeEventHandler.createImplementation({
  implementation: MyHandler,
  dependencies: [SomeUseCase]
});

How to Override a UseCase

To replace the default implementation, register your own:

import { SomeUseCase } from "webiny/api/<category>";

class CustomImplementation implements SomeUseCase.Interface {
  async execute(input) {
    // Custom logic
    return Result.ok(/* ... */);
  }
}

export default SomeUseCase.createImplementation({
  implementation: CustomImplementation,
  dependencies: []
});

Registration

YOU MUST include the full file path with the .ts extension in the src prop. For example, use src={"@/extensions/my-extension.ts"}, NOT src={"@/extensions/my-extension"}. Omitting the file extension will cause a build failure.

YOU MUST use export default for the createImplementation() call when the file is targeted directly by an Extension src prop. Using a named export (export const Foo = SomeFactory.createImplementation(...)) will cause a build failure. Named exports are only valid inside files registered via createFeature.

// In your app's configuration
<Api.Extension src={"@/extensions/my-extension.ts"} />

Deploy with: yarn webiny deploy api --env=dev


Error Handling Pattern

Domain-Specific Errors

Every feature defines errors extending BaseError. Never use generic Error for validation or business rule failures.

// domain/errors.ts
import { BaseError } from "webiny/api";

export class EntityNotFoundError extends BaseError {
  override readonly code = "Entity/NotFound" as const;
  constructor(id: string) {
    super({ message: `Entity with id "${id}" was not found!` });
  }
}

export class EntityPersistenceError extends BaseError<{ error: Error }> {
  override readonly code = "Entity/Persist" as const;
  constructor(error: Error) {
    super({ message: error.message, data: { error } });
  }
}

export class EntityValidationError extends BaseError<{ message: string }> {
  override readonly code = "Entity/Validation" as const;
  constructor(message: string) {
    super({ message, data: { message } });
  }
}

Typed Error Unions in Abstractions

Define an IErrors interface mapping error names to types, then create a union via [keyof IErrors]:

// features/createEntity/abstractions.ts
import { createAbstraction, Result } from "webiny/api";
import { NotAuthorizedError } from "webiny/api/security";
import {
  EntityPersistenceError,
  EntityModelNotFoundError,
  EntityCreationError
} from "~/api/domain/errors.js";

// REPOSITORY errors
export interface ICreateEntityRepositoryErrors {
  persistence: EntityPersistenceError;
  modelNotFound: EntityModelNotFoundError;
  creation: EntityCreationError;
}

type RepositoryError = ICreateEntityRepositoryErrors[keyof ICreateEntityRepositoryErrors];

export interface ICreateEntityRepository {
  execute(entity: Entity): Promise<Result<Entity, RepositoryError>>;
}

export const CreateEntityRepository = createAbstraction<ICreateEntityRepository>(
  "MyExt/CreateEntityRepository"
);

export namespace CreateEntityRepository {
  export type Interface = ICreateEntityRepository;
  export type Error = RepositoryError;
  export type Return = Promise<Result<Entity, RepositoryError>>;
}

// U
자주 묻는 질문

유스케이스는 무엇을 반환하나요?

성공 값 또는 오류 중 하나인 결과를 반환하므로, 호출하는 쪽은 실패를 반드시 확인해야 합니다.

기본 유스케이스를 바꿀 수 있나요?

네. 교체 구현을 등록하는 방법을 설명합니다.

리포지토리는 어떻게 쓰이나요?

CMS를 통해 데이터를 저장하는 리포지토리와 항목 매퍼를 다룹니다.

상세 정보

작성자의 원본 설명

UseCase implementation pattern — DI, Result handling, error types, decorators, CMS repositories, entry mappers, and schema-based permissions. Use this skill to implement, inject, override, or decorate any Webiny UseCase, or to build repositories that persist data via CMS.

repo: webiny/webiny-js

인기도

GitHub 스타
8.1k
순위
#12590
라이선스
—
업데이트
2026. 11. 2.

이 스킬이 유용한가요?

0

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

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬