UNPKG

2.97 kBPlain TextView Raw
1import {APIConfig} from "./APIConfig";
2import {APIError} from "./APIError";
3import {get, isNil} from "lodash";
4import {URL} from "url";
5
6export class APIResponse {
7 req;
8 res;
9 next;
10
11 constructor(req?, res?, next?) {
12 this.req = req;
13 this.res = res;
14 this.next = next;
15 }
16
17 static withError(req, res, error: any, hapiOutput: boolean = APIConfig.OUTPUT_HAPI_RESULTS) {
18 return new APIResponse(req, res).withError(error, hapiOutput);
19 }
20
21 async processHandlerFunction(target: any, handlerFunction: Function, handlerArgs: any[] = [], disableFriendlyResponse?: boolean, successResponseHandler?: (responseData: any, res) => void) {
22 // Add the req, and res to the end arguments if the function wants it
23 handlerArgs = handlerArgs.concat([this.req, this.res]);
24
25 let handlerData;
26
27 try {
28 const handlerOutput = handlerFunction.apply(target, handlerArgs);
29 if (!(handlerOutput instanceof Promise)) {
30 handlerData = handlerOutput;
31 } else {
32 handlerData = await handlerOutput;
33 }
34 } catch (error) {
35 this.withError(error);
36 return;
37 }
38
39 // If the data is a URL, consider this a redirect.
40 if (handlerData instanceof URL) {
41 this.res.redirect((<URL>handlerData).toString());
42 return;
43 }
44
45 if (disableFriendlyResponse) {
46 this.res.json(handlerData);
47 } else if (!isNil(successResponseHandler)) {
48 successResponseHandler(handlerData, this.res);
49 } else {
50 this.withSuccess(handlerData, 200);
51 }
52 }
53
54 withError(error: any, hapiOutput: boolean = APIConfig.OUTPUT_HAPI_RESULTS) {
55
56 if (this.res.headersSent || isNil(error)) {
57 return;
58 }
59
60 let apiError: APIError;
61
62 if (error instanceof APIError) {
63 apiError = error;
64 } else {
65 apiError = new APIError("unknown", error);
66 }
67
68 if ((apiError.statusCode >= 500 && apiError.statusCode <= 599 && APIConfig.LOG_500_ERRORS) ||
69 (apiError.statusCode >= 400 && apiError.statusCode <= 499 && APIConfig.LOG_400_ERRORS)) {
70 console.error(JSON.stringify(apiError.out(true)));
71 }
72
73 if (this.next) {
74 // Let the standard error handler handle it
75 this.next(apiError);
76 } else {
77 this.res.status(apiError.statusCode).send(hapiOutput ? apiError.hapiOut() : apiError.out());
78 }
79 }
80
81 withSuccess(data?: any, statusCode: number = 200, hapiOutput: boolean = APIConfig.OUTPUT_HAPI_RESULTS) {
82
83 if (this.res.headersSent) {
84 return;
85 }
86
87 let output = data;
88
89 if (hapiOutput) {
90 output = {
91 "this": "succeeded",
92 "with": data
93 }
94 }
95
96 this.res.status(statusCode).send(output);
97 }
98}
\No newline at end of file