Koa

This is how your API handler would typically look like:

src/main.ts
import Koa from "koa";
import Router from "@koa/router";
import * as fs from "node:fs/promises";
import { bootstrapAuth, getUser } from "./auth"; // See below

async function startKoaServer() {

    bootstrapAuth({
        implementation: "real", // or "mock", see: https://docs.oidc-spa.dev/v/v8/integration-guides/backend-token-validation/mock-modes
        issuerUri: process.env.OIDC_ISSUER_URI!,
        expectedAudience: process.env.OIDC_AUDIENCE
    });

    const app = new Koa();

    const router = new Router();

    router.get("/api/todos", async ctx => {

        const user = await getUser({ ctx });

        const json = await fs.readFile(
            `todos_${user.id}.json`,
            "utf8"
        );

        ctx.status = 200;
        ctx.type = "application/json";
        ctx.body = json;

    });

    router.get("/api/todos-for-support/:userId", async ctx => {

        // Will reject the request if user making the request
        // doesn't have "support-staff" role
        await getUser({ ctx, requiredRole: "support-staff" });

        const json = await fs.readFile(
            `todos_${ctx.params.userId}.json`,
            "utf8"
        );

        ctx.status = 200;
        ctx.type = "application/json";
        ctx.body = json;

    });

    app.use(router.routes());
    app.use(router.allowedMethods());

    app.listen(parseInt(process.env.PORT ?? "3000"), () => {
        console.log("Server running");
    });
}

Let's see how to export the utils to make it happen:

Last updated

Was this helpful?