Prism/developer documentation/Handlers

Handlers

Where your module's logic lives, shared by routes, clocks and events.

A handler holds your module's logic. Routes, clocks and events stay short and call into it. Put handlers in src/handlers/.

modules/example/src/handlers/items.js
import { Handlers } from "#prism/modules";

export class ItemsHandler extends Handlers {
    constructor(prism) {
        super(prism, { name: "items" });
    }

    get items() {
        return this.prism.modules.models.get("example", "example_items");
    }

    async create(identifier, name) {
        if (!identifier) this.fail(400, this.prism.modules.lang.phrase("example", "messages", "identifier_required"));
        if (await this.items.get({ identifier })) this.fail(409, this.prism.modules.lang.phrase("example", "messages", "exists", { identifier }));
        return this.items.plain(await this.items.create({ identifier, name }));
    }
}

this.module is your module ID, set by Prism when it loads the file. Messages that reach customers come from your lang files, never inline strings.

Methods

MethodWhat it does
fail(status, message)Throws an error with that HTTP status. A route that hits it answers with the status and { error: message }.
emit(event, ...args)Fires an event on this.prism.events.
emitAsync(event, ...args)Fires an event and waits for every listener.
getName()The handler name.

Using Another Module's Handler

const catalog = this.prism.modules.handlers.get("core", "catalog");

get returns null when that module is not loaded. If your module cannot work without it, add it to requires in main.js instead of checking each time.