Deno.serve

This is how your API handler would typically look like:

src/main.ts
import { bootstrapAuth, getUser } from "./auth.ts"; // See below

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

Deno.serve(async (request: Request) => {
    const url = new URL(request.url);

    if (request.method === "GET" && url.pathname === "/api/todos") {

        const user = await getUser({ req: request });

        // We got an exception, validation failed
        if (user instanceof Response) {
            const response = user;
            return response;
        }

        const json = await Deno.readTextFile(
            `todos_${user.id}.json`
        );

        return new Response(json, {
            status: 200,
            headers: { "content-type": "application/json" }
        });

    }

    /**
     * Support staff endpoint.
     * Example: GET /api/todos/1234
     */
    if (request.method === "GET" && url.pathname.startsWith("/api/todos/")) {
        let userId: string;

        try {
            userId = decodeURIComponent(url.pathname.replace("/api/todos/", ""));
        } catch {
            return new Response("bad request", { status: 400 });
        }

        if (!userId || userId.includes("/")) {
            return new Response("bad request", { status: 400 });
        }
        
        {

            // Will reject the request if user making the request
            // doesn't have "support-staff" role
            const user = await getUser({ req: request, requiredRole: "support-staff" });
    
            // We got an exception, validation failed
            if (user instanceof Response) {
                const response = user;
                return response;
            }
        
        }

        const json = await Deno.readTextFile(`todos_${userId}.json`);

        return new Response(json, {
            status: 200,
            headers: { "content-type": "application/json" }
        });
    }

    return new Response("not found", { status: 404 });
});

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

Last updated

Was this helpful?