Comparing version 0.0.1 to 0.0.2
49
index.ts
@@ -1,3 +0,3 @@ | ||
import { Express } from "express"; | ||
import { Express } from 'express'; | ||
/* tslint:disable: no-any */ | ||
export class JsonResponse { | ||
@@ -8,3 +8,3 @@ private data: any; | ||
} | ||
getData() { | ||
getData(): any { | ||
return this.data; | ||
@@ -14,22 +14,41 @@ } | ||
interface ControllerRoute { path: string, controller: any, action: string }; | ||
interface ControllerRoute { path: string; controller: any; action: string; } | ||
const controllers = new Map(); | ||
export function Route(path: string) { | ||
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) { | ||
if (!controllers.has(target)) { | ||
controllers.set(target, []); | ||
} | ||
const routes: ControllerRoute[] = controllers.get(target); | ||
routes.push({ path, controller: target, action: propertyKey }); | ||
}; | ||
/* tslint:disable-next-line: variable-name */ | ||
export const Route = (path: string) => (target: any, propertyKey: string, descriptor: PropertyDescriptor) => { | ||
if (!controllers.has(target)) { | ||
controllers.set(target, []); | ||
} | ||
const routes: ControllerRoute[] = controllers.get(target) as ControllerRoute[]; | ||
const route: ControllerRoute = { path, controller: target as any, action: propertyKey }; | ||
routes.push(route); | ||
}; | ||
export const isPromise = (result: any): result is PromiseLike<any> => result.then !== undefined; | ||
interface ControllerInstance { | ||
[key: string]: () => any; | ||
} | ||
interface ControllerClass { | ||
constructor: new() => ControllerInstance; | ||
} | ||
export const init = (app: Express) => { | ||
controllers.forEach((routes: ControllerRoute[], ControllerClass: any) => { | ||
const controller = new ControllerClass.constructor(); | ||
controllers.forEach((routes: ControllerRoute[], controllerClassType: ControllerClass) => { | ||
const controller = new controllerClassType.constructor(); | ||
routes.forEach(route => { | ||
app.get(route.path, (request, response) => { | ||
const result = controller[route.action](); | ||
if (isPromise(result)) { | ||
result.then(result2 => { | ||
if (result2 instanceof JsonResponse) { | ||
response.json(result2.getData()); | ||
return; | ||
} | ||
}); | ||
} | ||
if (result instanceof JsonResponse) { | ||
@@ -36,0 +55,0 @@ response.json(result.getData()); |
{ | ||
"name": "core-mvc", | ||
"version": "0.0.1", | ||
"version": "0.0.2", | ||
"description": "Symfony like MVC implmentation on top of Express.", | ||
@@ -5,0 +5,0 @@ "main": "index.ts", |
2663
50