2019-08-25 15:19:12 +00:00
|
|
|
import * as plugins from './typedrequest.plugins';
|
|
|
|
|
|
|
|
import { TypedHandler } from './typedrequest.classes.typedhandler';
|
|
|
|
|
|
|
|
/**
|
|
|
|
* A typed router decides on which typed handler to call based on the method
|
|
|
|
* specified in the typed request
|
|
|
|
* This is thought for reusing the same url endpoint for different methods
|
|
|
|
*/
|
|
|
|
export class TypedRouter {
|
|
|
|
public handlerMap = new plugins.lik.Objectmap<
|
|
|
|
TypedHandler<plugins.typedRequestInterfaces.ITypedRequest>
|
|
|
|
>();
|
|
|
|
|
|
|
|
/**
|
|
|
|
* adds the handler to the routing map
|
|
|
|
* @param handlerArg
|
|
|
|
*/
|
2020-02-11 18:55:07 +00:00
|
|
|
public addTypedHandler<T extends plugins.typedRequestInterfaces.ITypedRequest>(
|
|
|
|
handlerArg: TypedHandler<T>
|
|
|
|
) {
|
2019-08-25 15:19:12 +00:00
|
|
|
this.handlerMap.add(handlerArg);
|
|
|
|
}
|
|
|
|
|
|
|
|
public async addResponse(typedRequest: plugins.typedRequestInterfaces.ITypedRequest) {
|
|
|
|
const typedHandler = this.handlerMap.find(handler => {
|
|
|
|
return handler.method === typedRequest.method;
|
|
|
|
});
|
|
|
|
|
2019-08-31 12:11:56 +00:00
|
|
|
if (!typedHandler) {
|
|
|
|
const availableMethods: string[] = [];
|
2020-02-11 18:55:07 +00:00
|
|
|
await this.handlerMap.forEach(async handler => {
|
2019-08-31 12:11:56 +00:00
|
|
|
availableMethods.push(handler.method);
|
|
|
|
});
|
|
|
|
console.log(`Cannot find method for ${typedHandler}`);
|
|
|
|
console.log(`Available methods are:`);
|
|
|
|
console.log(availableMethods);
|
2019-09-01 13:39:08 +00:00
|
|
|
typedRequest.error = {
|
|
|
|
text: 'There is no available method for this call on the server side',
|
|
|
|
data: {}
|
|
|
|
};
|
|
|
|
return typedRequest;
|
2019-08-31 12:11:56 +00:00
|
|
|
}
|
|
|
|
|
2019-08-25 15:19:12 +00:00
|
|
|
typedRequest = await typedHandler.addResponse(typedRequest);
|
|
|
|
return typedRequest;
|
|
|
|
}
|
|
|
|
}
|