Plugins

Overview

Katal plugins let you modularize framework setup with lifecycle hooks.

Each plugin can participate in: - onRegister: one-time registration before boot (services, routes, middleware) - onBoot: executed during app boot - onReady: executed after server starts - onClose: executed when app stops

Plugin Contract

import type { KatalPlugin } from "katal";

interface CachePluginOptions {
    ttl: number;
}

const cachePlugin: KatalPlugin<CachePluginOptions> = {
    name: "cache-plugin",
    onRegister({ app, container }, options) {
        container.singleton("cacheTtl", () => options.ttl);
        app.middleware("plugin-logger", {
            before(ctx) {
                ctx.state.plugin = "cache-plugin";
                return null;
            },
        });
    },
    onBoot({ app }) {
        app.group("/plugin", (router) => {
            class PingController {
                async handle() {
                    return new Response("pong");
                }
            }
            router.get("/ping", PingController as any);
        });
    },
    onReady() {
        console.log("Plugin is ready");
    },
    onClose() {
        console.log("Plugin stopped");
    },
};

Register Plugin

import { Application } from "katal";

const app = new Application({ port: 3000 });

app.registerPlugin(cachePlugin, { ttl: 60 });

await app.listen();

Notes

  • Hooks are executed in registration order.
  • Plugin hooks can be async.
  • onRegister and onBoot run once during the first boot.
  • onReady runs each time the server starts.
  • onClose runs when app.stop() is called.

See Also