Kora/developer documentation/Handlers

Handlers

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

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

modules/example/src/handlers/Items.js
import { Handlers } from "#kora/modules";

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

    get items() {
        return this.kora.modules.models.get(this.module, "example_items");
    }

    async create(identifier, name) {
        if (!identifier) this.fail(400, "An identifier is required.");
        if (await this.items.get({ identifier })) this.fail(409, `${identifier} already exists.`);
        return this.items.create({ identifier, name });
    }

    async remove(identifier) {
        if (!await this.items.delete({ identifier })) this.fail(404, `${identifier} was not found.`);
        return { removed: identifier };
    }
}

this.module is your module ID, set by Kora when it loads the file.

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.kora.events.
emitAsync(event, ...args)Fires an event and waits for every listener.
getName()The handler name.

Using Another Module's Handler

const licenses = this.kora.modules.handlers.get("core", "licenses");

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