Fair simple decorator based router, with GET/POST and middleware support.
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 {
@get(
"/users")
getAllUsers(
) {
return users;
}
@get(
"/getUserByName")
getUserByName(
{ name }: Record<string, string>) {
const user = users.
find(
(u) => u.
name === name);
if (user) {
return user;
}
return Response.
json({
error:
"not found" }, {
status:
404 });
}
@get(
"/user/:id")
user(
_: unknown, { params: { id } }: Context) {
return users.
find(
(u) => u.
id ===
Number(id));
}
@post(
"/user")
async createUser(
user: User) {
if (users.
find(
(u) => u.
id === user.
id)) {
return {
error:
"already exists!" };
}
await users.
push(user);
return {
ok:
true, users };
}
@post(
"/user/:id")
async updateUser(
user: User, { params: { id }, request }: Context) {
const token =
parseBearerAuth(request.
headers.
get(
"Authorization")!);
}
@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") ||
"*",
},
});
}
}
Deno.
serve(handler);
export default handler;
So cool!
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!