Initial commit with decorator router, and some basic subsonic api code

This commit is contained in:
2026-04-08 19:40:39 +01:00
commit 8e5a8d073f
19 changed files with 1178 additions and 0 deletions
+80
View File
@@ -0,0 +1,80 @@
import Router from "@koa/router";
import Koa from "koa";
type Constructor<T = {}> = new (...args: any[]) => T;
type Route = {
method: string;
path: string;
fn: any;
};
export class BaseRouter {
public router!: Router;
processRoutes(routes: Route[]) {
for (const route of routes) switch (route.method) {
case "get": this.router.get(route.path, route.fn); break;
case "post": this.router.post(route.path, route.fn); break;
case 'use': this.router.use(route.path, route.fn); break;
}
}
injectInto(app: Koa) {
app.use(this.router.routes()).use(this.router.allowedMethods());
}
}
export function get(path: string) {
return function getDecorator (originalMethod: any, context: ClassMethodDecoratorContext) {
if (context.metadata) {
if (!context.metadata.routes) {
context.metadata.routes = [];
}
// @ts-ignore
context.metadata.routes.push({method: 'get', path, fn: originalMethod});
}
return originalMethod;
}
}
export function post(path: string) {
return function getDecorator (originalMethod: any, context: ClassMethodDecoratorContext) {
if (context.metadata) {
if (!context.metadata.routes) {
context.metadata.routes = [];
}
// @ts-ignore
context.metadata.routes.push({method: 'post', path, fn: originalMethod});
}
return originalMethod;
}
}
export function middleware(fn: any, path: string = '') {
return function middlewareDecorator (constructor: any, context: ClassDecoratorContext) {
if (context.metadata) {
if (!context.metadata.routes) {
context.metadata.routes = [];
}
// @ts-ignore
context.metadata.routes.unshift({method: 'use', path, fn});
}
return constructor;
}
}
export function router(prefix: string) {
return function routerDecorator<T extends Constructor>(constructor: T, context: ClassDecoratorContext<T>) {
return class extends constructor {
constructor(...args: any[]) {
super(...args);
if (this instanceof BaseRouter) {
this.router = new Router({prefix});
// @ts-ignore
this.processRoutes(context.metadata?.routes || [] satisfies Route[]);
}
}
}
}
}