UNPKG

3.02 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3const APIConfig_1 = require("./APIConfig");
4const APIError_1 = require("./APIError");
5const lodash_1 = require("lodash");
6const url_1 = require("url");
7class APIResponse {
8 constructor(req, res, next) {
9 this.req = req;
10 this.res = res;
11 this.next = next;
12 }
13 static withError(req, res, error, hapiOutput = APIConfig_1.APIConfig.OUTPUT_HAPI_RESULTS) {
14 return new APIResponse(req, res).withError(error, hapiOutput);
15 }
16 processHandlerFunction(target, handlerFunction, handlerArgs = [], successResponseHandler) {
17 // Add the req, and res to the end arguments if the function wants it
18 handlerArgs = handlerArgs.concat([this.req, this.res]);
19 let handlerPromise = handlerFunction.apply(target, handlerArgs);
20 if (!(handlerPromise instanceof Promise)) {
21 throw new Error(`API function named '${handlerFunction.name}' doesn't return a promise.`);
22 }
23 else {
24 handlerPromise.then((data) => {
25 // If the data is a URL, consider this a redirect.
26 if (data instanceof url_1.URL) {
27 this.res.redirect(data.toString());
28 return;
29 }
30 if (!lodash_1.isNil(successResponseHandler)) {
31 successResponseHandler(data, this.res);
32 }
33 else {
34 this.withSuccess(data, 200);
35 }
36 }).catch((error) => {
37 this.withError(error);
38 });
39 }
40 }
41 withError(error, hapiOutput = APIConfig_1.APIConfig.OUTPUT_HAPI_RESULTS) {
42 if (this.res.headersSent || lodash_1.isNil(error)) {
43 return;
44 }
45 let apiError;
46 if (error instanceof APIError_1.APIError) {
47 apiError = error;
48 }
49 else {
50 apiError = new APIError_1.APIError("unknown", error);
51 }
52 if ((apiError.statusCode >= 500 && apiError.statusCode <= 599 && APIConfig_1.APIConfig.LOG_500_ERRORS) ||
53 (apiError.statusCode >= 400 && apiError.statusCode <= 499 && APIConfig_1.APIConfig.LOG_400_ERRORS)) {
54 console.error(JSON.stringify(apiError.out(true)));
55 }
56 if (this.next) {
57 // Let the standard error handler handle it
58 this.next(apiError);
59 }
60 else {
61 this.res.status(apiError.statusCode).send(hapiOutput ? apiError.hapiOut() : apiError.out());
62 }
63 }
64 withSuccess(data, statusCode = 200, hapiOutput = APIConfig_1.APIConfig.OUTPUT_HAPI_RESULTS) {
65 if (this.res.headersSent) {
66 return;
67 }
68 let output = data;
69 if (hapiOutput) {
70 output = {
71 "this": "succeeded",
72 "with": data
73 };
74 }
75 this.res.status(statusCode).send(output);
76 }
77}
78exports.APIResponse = APIResponse;
79//# sourceMappingURL=APIResponse.js.map
\No newline at end of file