Initial commit with decorator router, and some basic subsonic api code
This commit is contained in:
@@ -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[]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user