Readme

Decorator Router

Fair simple decorator based router, with GET/POST and middleware support.

demo

live demo: https://yieldray-decorator_router_demo.web.val.run/

import { get, post, all, use, registered, handler, type Context } from "https://esm.town/v/yieldray/decorator_router"; import { parseBearerAuth, transformResponse } from "https://esm.sh/serve-router@1.1.0/utils"; interface User { id: number; name: string; } const users: User[] = [ { id: 0, name: "Alice" }, { id: 1, name: "Ray" }, ]; class _Server { /** * Decorator @get: Parses URLSearchParams into an object as the first parameter. */ @get("/users") getAllUsers() { return users; // Automatically wrapped in a Response.json } @get("/getUserByName") // GET /getUserByName?name=Alice getUserByName({ name }: Record<string, string>) { const user = users.find((u) => u.name === name); if (user) { return user; // Automatically wrapped as Response.json(user) } // Optionally, manually return a Response object return Response.json({ error: "not found" }, { status: 404 }); } @get("/user/:id") // GET /user/123 user(_: unknown, { params: { id } }: Context) { return users.find((u) => u.id === Number(id)); } /** * Decorator @post: Parses the request body into an object as the first parameter. */ @post("/user") // POST /user async createUser(user: User) { if (users.find((u) => u.id === user.id)) { return { error: "already exists!" }; } await users.push(user); // Assume insertion into a database return { ok: true, users }; } @post("/user/:id") // POST /user/123 async updateUser(user: User, { params: { id }, request }: Context) { const token = parseBearerAuth(request.headers.get("Authorization")!); // Additional logic here... } @all("/") home({ request }: { request: Request }) { return { registered, method: request.method, url: request.url, headers: Object.fromEntries(request.headers.entries()), }; } @use("/*") async corsMiddleware({ next, request }: Context) { const resp = await next(); return transformResponse(resp, { headers: { "Access-Control-Allow-Origin": request.headers.get("origin") || "*", }, }); } } // For Deno: Deno.serve(handler); // For val.town: export default handler;
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
2
stevekrouse avatar
yieldray avatar

Thanks @stevekrouse! However, I've noticed that currently, decorators can only be applied to methods. If we had parameter decorators and function decorators, we could do much more!

May 16, 2024