webiny-use-case-pattern
它能做什么
这个技能指导你的 AI 在 Webiny 后端编写一个业务操作。适用于构建或覆盖用例及其背后仓储的开发者。
适用场景
- ✓需要新的业务操作,例如创建或发布记录的时候。
- ✓想替换或装饰现有用例的时候。
- ✓用例必须通过 CMS 仓储保存数据时。
技能链接
https://github.com/webiny/webiny-js/blob/next/skills/user-skills/api/use-case-pattern/SKILL.md复制后粘贴给你的 AI(Claude、ChatGPT 或 Cursor),让它按照说明操作。
使用方法
最简单的方法:复制下面的消息,粘贴给你的 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 中构建表单。