typedrequest/ts/classes.typedhandler.ts

58 lines
1.7 KiB
TypeScript
Raw Permalink Normal View History

2024-02-20 16:40:30 +00:00
import * as plugins from './plugins.js';
2024-05-30 17:01:39 +00:00
import { TypedResponseError } from './classes.typedresponseerror.js';
2024-05-30 20:41:49 +00:00
import { TypedTools } from './classes.typedtools.js';
2019-08-25 15:19:12 +00:00
2020-10-06 16:37:25 +00:00
export type THandlerFunction<T extends plugins.typedRequestInterfaces.ITypedRequest> = (
2024-05-30 20:41:49 +00:00
requestArg: T['request'],
2024-05-30 20:47:02 +00:00
typedToolsArg?: TypedTools
2020-02-11 18:55:07 +00:00
) => 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
}
2020-06-16 15:03:10 +00:00
let typedResponseError: TypedResponseError;
2024-05-30 20:41:49 +00:00
const typedtoolsInstance = new TypedTools();
const response = await this.handlerFunction(typedRequestArg.request, typedtoolsInstance).catch((e) => {
2020-06-16 15:03:10 +00:00
if (e instanceof TypedResponseError) {
typedResponseError = e;
} else {
2022-07-29 02:48:34 +00:00
console.log(e);
2020-06-16 15:03:10 +00:00
}
});
if (typedResponseError) {
typedRequestArg.error = {
text: typedResponseError.errorText,
2020-10-06 15:05:29 +00:00
data: typedResponseError.errorData,
2020-06-16 15:03:10 +00:00
};
}
2020-06-25 23:53:05 +00:00
2020-06-16 15:03:10 +00:00
if (response) {
typedRequestArg.response = response;
}
2020-10-06 15:05:29 +00:00
typedRequestArg?.correlation?.phase ? (typedRequestArg.correlation.phase = 'response') : null;
2020-07-14 02:20:15 +00:00
2019-08-25 15:19:12 +00:00
return typedRequestArg;
}
}