webiny-use-case-pattern
Skill này làm gì
Skill này hướng dẫn AI của bạn khi viết một thao tác nghiệp vụ trong backend Webiny. Skill dành cho lập trình viên xây dựng hoặc ghi đè use case và các repository đi kèm.
Khi nào nên dùng
- ✓Khi bạn cần một thao tác nghiệp vụ mới, chẳng hạn tạo hoặc xuất bản một bản ghi.
- ✓Khi bạn muốn thay thế hoặc bọc thêm một use case có sẵn.
- ✓Khi một use case phải lưu dữ liệu qua các repository của CMS.
Liên kết skill
https://github.com/webiny/webiny-js/blob/next/skills/user-skills/api/use-case-pattern/SKILL.mdSao chép rồi dán vào AI của bạn (Claude, ChatGPT hoặc Cursor) và nhờ nó làm theo hướng dẫn.
Cách dùng
Cách dễ nhất: sao chép tin nhắn và dán vào AI của bạn. AI sẽ đọc skill và làm theo hướng dẫn.
Tin nhắn có sẵn để dán
Dành cho Claude Code, Codex hoặc Cursor: chạy lệnh trong thư mục dự án của bạn và skill sẽ được cài đặt.
Tải tệp SKILL.md về và thả vào thư mục skill của agent.
Ví dụ cách nhờ AI
“Viết một use case xuất bản mục CMS và trả về lỗi rõ ràng nếu mục đó đã được xuất bản.”
5 skill mới mỗi tuần. Đọc chỉ 1 phút.
Cách hoạt động
Skill giải thích phương thức execute duy nhất, đầu vào có kiểu, kết quả báo thành công hoặc thất bại, và các loại lỗi có kèm mã. Skill cũng chỉ cách đưa use case vào các đoạn code khác.
Nội dung kỹ thuật (SKILL.md gốc)
Lấy nguyên văn từ GitHub, do tác giả viết bằng tiếng Anh.
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
Câu hỏi thường gặp
Use case trả về gì?
Một kết quả, hoặc là giá trị thành công hoặc là lỗi, nên nơi gọi phải kiểm tra trường hợp thất bại.
Tôi có thể ghi đè một use case mặc định không?
Có. Skill giải thích cách đăng ký một triển khai thay thế.
Các repository được dùng như thế nào?
Skill nói về các repository lưu dữ liệu qua CMS, cùng với các mapper cho mục.
Chi tiết
Mô tả gốc của tác giả
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
Độ phổ biến
- Sao GitHub
- 8.1k
- Vị trí xếp hạng
- #12590
- Giấy phép
- —
- Cập nhật
- 2/11/2026
Bình luận
- …
Thêm skill từ kho mã này
prd-to-plan
8.1kGiúp agent của bạn biến tài liệu yêu cầu sản phẩm thành kế hoạch theo giai đoạn gồm các lát cắt đầu-cuối nhỏ, lưu thành file Markdown.
webiny-admin-architect
8.1kDạy agent của bạn cách xây dựng màn hình quản trị cho nền tảng Webiny, dùng các tầng logic nghiệp vụ và mẫu presenter.
webiny-admin-permissions
8.1kDạy agent của bạn thêm kiểm soát quyền vào màn hình quản trị Webiny, gồm form quyền tự sinh và kiểm tra ẩn hoặc hiện.
webiny-form-model
8.1kDạy agent của bạn xây dựng form trong Webiny bằng trình tạo trường khai báo, bố cục, kiểm tra hợp lệ và quy tắc có điều kiện.
Skill tương tự
api-connector-builder
280kGiúp agent của bạn xây dựng kết nối API mới theo đúng mẫu đã có, dùng khi bạn cần thêm một tích hợp mà không tạo cách làm mới.
api-design
280kGiúp agent của bạn thiết kế REST API theo các thực hành tốt nhất, hữu ích để định nghĩa cách API giao tiếp, hiển thị lỗi và tổ chức dữ liệu.
backend-patterns
280kGiúp agent của bạn với các mẫu kiến trúc phía máy chủ và tối ưu cơ sở dữ liệu, hữu ích khi xây dựng hoặc rà soát code chạy trên máy chủ.