Chuyển đến nội dung
Skillpedia
API và máy chủ (backend)8.1k · #12586

webiny-event-handler-pattern

Skill này làm gì

Skill này hướng dẫn AI của bạn khi viết mã chạy khi có thay đổi trong Webiny, như một mục được tạo. Dành cho lập trình viên muốn thêm kiểm tra hoặc tác dụng phụ vào những thời điểm đó.

Khi nào nên dùng

  • ✓Khi bạn muốn mã chạy trước khi một mục hoặc bản ghi khác được lưu, để kiểm tra hoặc thay đổi nó.
  • ✓Khi bạn muốn một tác dụng phụ xảy ra sau khi bản ghi được tạo, cập nhật hoặc xóa.
  • ✓Khi bạn cần định nghĩa và phát một sự kiện miền riêng.

Liên kết skill

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

Sao 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

Hãy dùng skill này để giúp tôi: https://github.com/webiny/webiny-js/blob/next/skills/user-skills/api/event-handler-pattern/SKILL.md Đọc tệp SKILL.md tại liên kết đó và làm theo hướng dẫn cho việc của tôi.
Bạn muốn AI tự tìm những skill như thế này?Cài MCP Skillpedia miễn phí: chỉ một dòng, và AI sẽ tìm trong 15.000+ skill trước mỗi việc.Cài đặt trong 1 phút →

Ví dụ cách nhờ AI

“Sau khi một mục CMS được tạo, hãy gửi tiêu đề của nó đến chỉ mục tìm kiếm của chúng tôi bằng một event handler.”

5 skill mới mỗi tuần. Đọc chỉ 1 phút.

Cách hoạt động

Skill giải thích một event handler với một phương thức handle duy nhất, giữ mỏng để gọi một service có thể tái sử dụng. Nó bao gồm mẫu đặt tên cho handler trước và sau, và cách phát sự kiện.

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.

EventHandler Pattern

What It Is

An EventHandler reacts to domain events in the Webiny lifecycle (e.g., EntryBeforeCreateEventHandler, TenantAfterDeleteEventHandler). Each handler is a DI abstraction with a single handle method.

Naming Convention

  • {Entity}Before{Operation}EventHandler — fires before persistence, can validate/transform/reject
  • {Entity}After{Operation}EventHandler — fires after persistence, for side effects

Interface Shape

interface SomeEventHandler.Interface {
    handle(event: SomeEventHandler.Event): Promise<void>;
}

The Event is a DomainEvent<Payload> where the payload contains the entity and input data.

Architecture Rule: Always Wrap Logic in a Reusable Abstraction (MANDATORY)

Never put business logic directly inside an EventHandler. EventHandlers are thin orchestrators — they receive an event and delegate to an injected service or use case. The real logic lives in a dedicated abstraction.

Why: Inline handler logic cannot be reused by other handlers, GraphQL resolvers, or CLI commands.

Always follow this structure:

features/
├── myService/             ← the reusable abstraction
│   ├── abstractions.ts
│   ├── feature.ts
│   └── MyService.ts
└── syncOnCreate/          ← thin handler that injects the service
    ├── feature.ts
    └── EntryAfterCreateHandler.ts

The EventHandler feature and the service feature are registered separately in Extension.ts.

How to Implement

import { SomeEventHandler } from "webiny/api/<category>";
import { MyService } from "../myService/abstractions.js";

// ✅ Handler is a thin orchestrator — no business logic here
class MyHandler implements SomeEventHandler.Interface {
  constructor(private myService: MyService.Interface) {}

  async handle(event: SomeEventHandler.Event) {
    const { entity, model } = event.payload;

    // For CMS handlers: ALWAYS filter by model
    if (model.modelId !== "myModel") return;

    await this.myService.doWork(entity);
  }
}

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

See webiny-api-architect for how to define MyService as a proper abstraction.

Injecting Dependencies

EventHandlers can depend on UseCases, platform services, or custom abstractions:

import { SomeEventHandler } from "webiny/api/<category>";
import { SomeUseCase } 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({/* ... */});
  }
}

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

Defining Your Own Domain Events

When your feature needs to notify other parts of the system about important domain actions, define your own events.

Event Payload Types (in abstractions.ts)

Event payloads and handler abstractions live in abstractions.ts. The events.ts file only contains the event classes.

// features/disableEntity/abstractions.ts
import { createAbstraction, type DomainEvent } from "webiny/api";
import type { Entity } from "~/shared/Entity.js";
// Forward declaration — actual classes are in events.ts
import type { EntityBeforeDisableEvent, EntityAfterDisableEvent } from "./events.js";

// Event Payload Types
export interface EntityBeforeDisablePayload {
  entity: Entity;
}

export interface EntityAfterDisablePayload {
  entity: Entity;
}

// Handler Abstractions — one per event
interface IEventHandler<TEvent extends DomainEvent<any>> {
  handle(event: TEvent): Promise<void>;
}

export const EntityBeforeDisableEventHandler = createAbstraction<
  IEventHandler<EntityBeforeDisableEvent>
>("MyPackage/EntityBeforeDisableEventHandler");

export namespace EntityBeforeDisableEventHandler {
  export type Interface = IEventHandler<EntityBeforeDisableEvent>;
  export type Event = EntityBeforeDisableEvent;
}

export const EntityAfterDisableEventHandler = createAbstraction<
  IEventHandler<EntityAfterDisableEvent>
>("MyPackage/EntityAfterDisableEventHandler");

export namespace EntityAfterDisableEventHandler {
  export type Interface = IEventHandler<EntityAfterDisableEvent>;
  export type Event = EntityAfterDisableEvent;
}

Event Class Definition (events.ts)

Event classes import payload types and handler abst

Câu hỏi thường gặp

Handler nên được đặt tên thế nào?

Dùng tên entity, sau đó là Before hoặc After, rồi thao tác, rồi EventHandler.

Logic nên đặt ở đâu?

Trong một service hoặc use case có thể tái sử dụng, còn handler chỉ gọi nó.

Một handler có thể dừng một thay đổi không?

Theo skill, handler before có thể kiểm tra, biến đổi hoặc từ chối.

Chi tiết

Mô tả gốc của tác giả

EventHandler implementation pattern — handle method, event payloads, filtering, DI, domain event definition, publishing events from UseCases, and reacting to external events. Use this skill to implement any Webiny EventHandler (before/after hooks) or to define and publish your own domain events.

repo: webiny/webiny-js

Độ phổ biến

Sao GitHub
8.1k
Vị trí xếp hạng
#12586
Giấy phép
—
Cập nhật
2/11/2026

Skill này có hữu ích không?

0

Đăng nhập để bình chọn.

Bình luận

  • …

Thêm skill từ kho mã này

Skill tương tự