|
@@ -2,17 +2,18 @@
|
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
exports.PRAS = void 0;
|
|
|
class PRAS {
|
|
|
- getPRASResultObject(statusCode, status, message, data, code, extra) {
|
|
|
+ getPRASResultObject(statusCode = 200, status = "OK", message = "", data = null, code = "UNKNOWN_CODE", extra = null) {
|
|
|
return {
|
|
|
- statusCode: statusCode || 200,
|
|
|
- status: status || "OK",
|
|
|
- message: message || "",
|
|
|
- data: data || null,
|
|
|
- code: code || "UNKNOWN_CODE",
|
|
|
- extra: extra || null,
|
|
|
+ statusCode,
|
|
|
+ status,
|
|
|
+ message,
|
|
|
+ data,
|
|
|
+ code,
|
|
|
+ extra,
|
|
|
};
|
|
|
}
|
|
|
responseMiddleware() {
|
|
|
+ // eslint-disable-next-line @typescript-eslint/ban-types
|
|
|
return (req, res, next) => {
|
|
|
res.pras = {
|
|
|
ok: (message, data, code, extra) => {
|
|
@@ -50,22 +51,38 @@ class PRAS {
|
|
|
res.json(this.getPRASResultObject(statusCode, status, message, data, code, extra));
|
|
|
},
|
|
|
};
|
|
|
- const originalSend = res.send;
|
|
|
- res.send = (body) => {
|
|
|
- if (typeof body === "string") {
|
|
|
- body = JSON.parse(body);
|
|
|
+ const rawHeaders = req.rawHeaders;
|
|
|
+ let foundHeaderIndex = -1;
|
|
|
+ for (let i = 0; i < rawHeaders.length; i++) {
|
|
|
+ if (rawHeaders[i] === "Accept") {
|
|
|
+ foundHeaderIndex = i;
|
|
|
+ break;
|
|
|
}
|
|
|
- if (typeof body === "string") {
|
|
|
- body = { data: body };
|
|
|
- }
|
|
|
- else if (!body.hasOwnProperty("data")) {
|
|
|
- body = { data: body };
|
|
|
- }
|
|
|
- const prasBody = this.getPRASResultObject(body.statusCode, body.status, body.message, body.data, body.code, body.extra);
|
|
|
- res.status(Number(prasBody.statusCode) || 200);
|
|
|
- delete prasBody.statusCode;
|
|
|
- return originalSend.call(res, JSON.stringify(prasBody));
|
|
|
- };
|
|
|
+ }
|
|
|
+ if (rawHeaders.hasOwnProperty("Accept") &&
|
|
|
+ rawHeaders[foundHeaderIndex].includes("application/json")) {
|
|
|
+ const send = res.send;
|
|
|
+ res.send = (body) => {
|
|
|
+ try {
|
|
|
+ if (typeof body === "string") {
|
|
|
+ body = JSON.parse(body);
|
|
|
+ }
|
|
|
+ if (typeof body === "string") {
|
|
|
+ body = { data: body };
|
|
|
+ }
|
|
|
+ else if (!body.hasOwnProperty("data")) {
|
|
|
+ body = { data: body };
|
|
|
+ }
|
|
|
+ const prasBody = this.getPRASResultObject(body.statusCode, body.status, body.message, body.data, body.code, body.extra);
|
|
|
+ res.status(prasBody.statusCode || 200);
|
|
|
+ delete prasBody.statusCode;
|
|
|
+ return send.call(res, JSON.stringify(prasBody));
|
|
|
+ }
|
|
|
+ catch (err) {
|
|
|
+ return send.call(res, body);
|
|
|
+ }
|
|
|
+ };
|
|
|
+ }
|
|
|
next();
|
|
|
};
|
|
|
}
|