Langsung ke konten
Skillpedia
API & server (backend)8.1k Β· #12590

webiny-use-case-pattern

Fungsinya

Skill ini memandu AI Anda saat menulis satu operasi bisnis di backend Webiny. Skill ini untuk developer yang membuat atau mengganti use case beserta repository di baliknya.

Kapan dipakai

  • βœ“Saat Anda membutuhkan operasi bisnis baru, misalnya membuat atau menerbitkan sebuah record.
  • βœ“Saat Anda ingin mengganti atau menghias use case yang sudah ada.
  • βœ“Saat use case harus menyimpan data melalui repository CMS.

Link skill

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

Salin lalu tempelkan ke AI Anda (Claude, ChatGPT, atau Cursor) dan minta AI mengikuti instruksinya.

Cara pakai

Cara paling mudah: salin pesan ini dan tempelkan ke AI Anda. AI akan membaca skill dan mengikuti instruksinya.

Pesan siap tempel

Gunakan skill ini untuk membantu saya: https://github.com/webiny/webiny-js/blob/next/skills/user-skills/api/use-case-pattern/SKILL.md Baca file SKILL.md di link tersebut dan ikuti instruksinya untuk tugas saya.
Mau AI Anda menemukan skill seperti ini sendiri?Pasang MCP Skillpedia gratis: cukup satu baris, dan AI mencari di antara 15.000+ skill sebelum tiap tugas.Pasang dalam 1 menit β†’

Contoh permintaan ke AI

β€œTulis use case yang menerbitkan entri CMS dan mengembalikan pesan error yang jelas jika entri itu sudah diterbitkan.”

5 skill baru setiap minggu. 1 menit baca.

Cara kerjanya

Skill ini menjelaskan metode execute tunggal, input yang bertipe, hasil yang melaporkan sukses atau gagal, dan tipe error yang menyertakan kode. Skill ini juga menunjukkan cara use case disuntikkan ke kode lain.

Konten teknis (SKILL.md asli)

Teks asli dari pembuat, dalam bahasa Inggris, langsung dari 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
Pertanyaan umum

Apa yang dikembalikan use case?

Hasil yang berupa nilai sukses atau error, sehingga pemanggil harus memeriksa kegagalan.

Bisakah saya mengganti use case default?

Bisa. Skill ini menjelaskan cara mendaftarkan implementasi pengganti.

Bagaimana repository digunakan?

Skill ini membahas repository yang menyimpan data lewat CMS, beserta entry mapper.

Detail

Deskripsi asli dari pembuat

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

Popularitas

Bintang GitHub
8.1k
Peringkat
#12590
Lisensi
β€”
Diperbarui
2/11/2026

Apakah skill ini berguna?

0

Masuk untuk memberi suara.

Komentar

  • …

Skill lain dari repositori ini

Skill serupa