Back to packages list

Vals using serve-router

Description from the NPM package:
tiny router library that routes for your web standard http server
yieldray avatar
yieldray
decorator_router
Script
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;
0
yieldray avatar
yieldray
gists
HTTP
Get A Website for Your Gists Example: https://yieldray-gists.web.val.run Usage: fork this val and replace with your github usename
0
yieldray avatar
yieldray
notebook
HTTP
https://yieldray-notebook.web.val.run/
0
yieldray avatar
yieldray
serve_router
HTTP
serve-router Example https://yieldray-serve_router.web.val.run https://yieldray-serve_router.web.val.run/user/ray https://yieldray-serve_router.web.val.run/headers https://yieldray-serve_router.web.val.run/api https://yieldray-serve_router.web.val.run/api/one
0
1
Next