2019-06-20 10:24:23 +00:00
|
|
|
import { Container, interfaces as inversify_interfaces } from 'inversify'
|
|
|
|
import { TYPE, interfaces as express_interfaces } from 'inversify-express-utils'
|
2019-06-21 04:30:30 +00:00
|
|
|
import { METADATA_KEY } from './constants'
|
|
|
|
import { VaildError } from './interfaces'
|
2019-06-20 10:24:23 +00:00
|
|
|
import { getVaildMethodMetadata, getVaildControllerMetadata, getVaildModelMetadata } from './utils'
|
|
|
|
|
|
|
|
let handler = {
|
|
|
|
apply: function(target: Function, thisArgument: Object, argumentsList: any[]) {
|
|
|
|
let methodParams = getVaildMethodMetadata(target);
|
|
|
|
let [req, res, next] = [...argumentsList.slice(-3)];
|
|
|
|
try {
|
|
|
|
// loop @Valid params
|
|
|
|
for (const param of methodParams) {
|
|
|
|
// get function argument value
|
2019-06-21 04:30:30 +00:00
|
|
|
let origin = argumentsList[param.index];
|
2019-06-20 10:24:23 +00:00
|
|
|
let props = getVaildModelMetadata(param.type);
|
|
|
|
for (const prop of props) {
|
2019-06-21 04:30:30 +00:00
|
|
|
if (!prop.handle(origin[prop.name])) {
|
|
|
|
throw new VaildError(prop.message);
|
2019-06-20 10:24:23 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return target.apply(thisArgument, argumentsList);
|
|
|
|
} catch (ex) {
|
2019-06-21 04:30:30 +00:00
|
|
|
if (ex instanceof VaildError) {
|
|
|
|
res.status(400).json({
|
|
|
|
status: 400,
|
|
|
|
message: ex.message
|
|
|
|
})
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
throw ex;
|
2019-06-20 10:24:23 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
function rebuildServer(container: Container) {
|
|
|
|
// get all controller
|
|
|
|
let controllers = container.getAll<express_interfaces.Controller>(TYPE.Controller)
|
|
|
|
// for loop controllers and inject proxy to each method
|
2019-06-21 15:26:22 +00:00
|
|
|
container.unbind(TYPE.Controller);
|
2019-06-20 10:24:23 +00:00
|
|
|
for (const controller of controllers) {
|
2019-06-21 15:26:22 +00:00
|
|
|
container.bind(TYPE.Controller)
|
2019-06-20 10:24:23 +00:00
|
|
|
.to(controller.constructor as any)
|
|
|
|
.inSingletonScope()
|
|
|
|
.whenTargetNamed(controller.constructor.name)
|
|
|
|
.onActivation((ctx: inversify_interfaces.Context, controller: express_interfaces.Controller) => {
|
|
|
|
let prop = controller.constructor.prototype
|
|
|
|
// funcs => { create: [ { index: 0, type: [Function: ExampleModel] } ] }
|
|
|
|
let funcs = getVaildControllerMetadata(controller.constructor);
|
|
|
|
//Reflect.getMetadata(METADATA_KEY.controllerParameter, controller.constructor);
|
|
|
|
for (const func in funcs) {
|
|
|
|
Reflect.defineMetadata(METADATA_KEY.vaildMethod, funcs[func], prop[func])
|
|
|
|
// Define Proxy handle model vaild
|
|
|
|
Reflect.defineProperty(prop, func, { value: new Proxy(prop[func], handler) })
|
|
|
|
}
|
|
|
|
return controller;
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export { rebuildServer }
|