typedrequest/ts/typedrequest.classes.typedhandler.ts

34 lines
1.0 KiB
TypeScript
Raw Normal View History

2019-08-25 15:19:12 +00:00
import * as plugins from './typedrequest.plugins';
2020-02-11 18:55:07 +00:00
type THandlerFunction<T extends plugins.typedRequestInterfaces.ITypedRequest> = (
requestArg: T['request']
) => Promise<T['response']>;
2019-08-25 15:19:12 +00:00
/**
* typed handler for dealing with typed requests
*/
export class TypedHandler<T extends plugins.typedRequestInterfaces.ITypedRequest> {
public method: string;
private handlerFunction: THandlerFunction<T>;
constructor(methodArg: T['method'], handlerFunctionArg: THandlerFunction<T>) {
this.method = methodArg;
this.handlerFunction = handlerFunctionArg;
}
/**
* adds a response to the typedRequest
* @param typedRequestArg
*/
public async addResponse(typedRequestArg: T) {
if (typedRequestArg.method !== this.method) {
2020-02-11 18:55:07 +00:00
throw new Error(
'this handler has been given a wrong method to answer to. Please use a TypedRouter to filter requests'
);
2019-08-25 15:19:12 +00:00
}
const response = await this.handlerFunction(typedRequestArg.request);
typedRequestArg.response = response;
return typedRequestArg;
}
}