webiny-use-case-pattern
できること
このスキルは、Webinyのバックエンドで一つの業務の処理を書くとき、AIを導きます。ユースケースや、その背後にあるリポジトリを作成したり上書きしたりする開発者向けです。
使う場面
- ✓レコードを作成したり公開したりするなど、新しい業務の処理が必要なとき。
- ✓既存のユースケースを置き換えたり、機能を装飾したりしたいとき。
- ✓ユースケースがCMSのリポジトリを通じてデータを保存する必要があるとき。
スキルのリンク
https://github.com/webiny/webiny-js/blob/next/skills/user-skills/api/use-case-pattern/SKILL.mdコピーしてAI(Claude、ChatGPT、Cursor)に貼り付け、指示に従うよう頼んでください。
使い方
いちばん簡単な方法:メッセージをコピーしてAIに貼り付けるだけ。AIがスキルを読んで指示に従います。
貼り付け用メッセージ
Claude Code、Codex、Cursorの場合:プロジェクトのフォルダで実行するとスキルがインストールされます。
SKILL.mdをダウンロードして、エージェントのスキル用フォルダに入れてください。
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>fromwebiny/api - Error — extends
BaseErrorwith a uniquecode
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
コメント
- …
このリポジトリの他のスキル
prd-to-plan
8.1k製品要件書を、それぞれ端から端まで成立する小さなスライスの段階的な計画に変え、Markdownファイルとして保存するよう、エージェントを支援します。
webiny-admin-architect
8.1kビジネスロジックの層とプレゼンターのパターンを使い、Webinyプラットフォームの管理画面を作る方法をエージェントに教えます。
webiny-admin-permissions
8.1k自動生成される権限フォームや、表示・非表示のチェックを含め、Webinyの管理画面に権限の制御を追加するよう、エージェントに教えます。
webiny-form-model
8.1kビルダーで宣言的にフィールドを定義し、レイアウト、検証、条件付きのルールを使って、Webinyのフォームを作るよう、エージェントに教えます。
似ているスキル
api-connector-builder
280kエージェントが既存のパターンに従って、新しいAPI連携を構築します。新しい方式を作らずに、もう一つ連携を追加したいときに使います。
api-design
280kエージェントがベストプラクティスに沿ってREST APIを設計できるようにします。APIの通信方法、エラーの表示方法、データの整理方法を決めるのに役立ちます。
backend-patterns
280kエージェントのサーバーサイドのアーキテクチャパターンとデータベースの最適化を支援します。サーバー上で動くコードを作成またはレビューするときに役立ちます。