Skip to content

Commit

Permalink
Custom Response Structure Implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
Ganesh A authored and Ganesh A committed Sep 26, 2023
2 parents 917e617 + a4e99a9 commit 745bab6
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 30 deletions.
81 changes: 52 additions & 29 deletions base/executor.class.js
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,15 @@ const ParameterProcessor = require('./parameterProcessor.class');
const { encrypt, decrypt } = require('../helper/encryption');
const { ENC_MODE, DEFAULT_LNG_KEY, ENC_ENABLED } = require('../helper/globalConstants');
const jwt = require('../helper/jwt');
const _ = require("lodash");
const multiReplace = require('string-multiple-replace');

class executor {
constructor() {
this.responseData = {};
}

async executeRequest(request) {

try {
this.setResponse('UNKNOWN_ERROR');

Expand All @@ -38,9 +39,9 @@ class executor {
throw new Error();
}
const encryptionState = (ENCRYPTION_MODE == ENC_MODE.STRICT || (ENCRYPTION_MODE == ENC_MODE.OPTIONAL && encState == ENC_ENABLED));

// Set member variables
this.setMemberVariable('encryptionState', encryptionState);
this.setMemberVariable('encryptionState', this.encryptionState);
if (lngKey) this.setMemberVariable('lng_key', lngKey);

// Finalize methodName including custom route
Expand Down Expand Up @@ -101,7 +102,7 @@ class executor {
let requestData = baseHelper.parseRequestData(request, isFileExpected);

// If encyption is enabled, then decrypt the request data
if (!isFileExpected && encryptionState) {
if (!isFileExpected &&this.encryptionState) {
requestData = decrypt(requestData.data);
if (typeof requestData === 'string')
requestData = JSON.parse(requestData);
Expand All @@ -125,28 +126,21 @@ class executor {
// Initiate and Execute method
this.responseData = await actionInstance.executeMethod();
const { responseString, responseOptions, packageName } = actionInstance.getResponseString();
const { responseCode, responseMessage } = this.getResponse(responseString, responseOptions, packageName);


// If encryption mode is enabled then encrypt the response data
if (encryptionState) {
// this.responseData = new URLSearchParams({data: encrypt(this.responseData)}).toString().replace("data=",'');
this.responseData = encrypt(this.responseData);
}

return {
responseCode,
responseMessage,
responseData: this.responseData
};
const response = this.getResponse(responseString, responseOptions, packageName);
return response;

} catch (e) {
console.log("Exception caught", e);
const { responseCode, responseMessage } = this.getResponse();
const response = this.getResponse(e === "NODE_VERSION_ERROR" ? e : "");
if (process.env.MODE == "DEV" && e.message) this.setDebugMessage(e.message);
return {
responseCode,
responseMessage,
responseData: {}
};
return response;
}
}

Expand Down Expand Up @@ -206,12 +200,14 @@ class executor {
const BASE_RESPONSE = require(path.resolve(process.cwd(), `src/global/i18n/response.js`)).RESPONSE;
const PROJECT_RESPONSE = require(`../i18n/response.js`).RESPONSE;

const CUSTOM_RESPONSE_TEMPLATE = require(path.resolve(process.cwd(), `src/config/responseTemplate.json`));

let RESP = { ...PROJECT_RESPONSE, ...BASE_RESPONSE };

if (packageName) {
try {
let packageVals = packageName.split('/');
const PACKAGE_RESPONSE = require(path.resolve(process.cwd(), `njs2_modules/${[...packageVals.slice(0, packageVals.length - 1)].join('/')}/contract/response.json`));
const PACKAGE_RESPONSE = require(path.resolve(process.cwd(), `node_modules/${[...packageVals.slice(0, packageVals.length - 1)].join('/')}/contract/response.json`));
RESP = { ...RESP, ...PACKAGE_RESPONSE };
} catch {
}
Expand All @@ -220,25 +216,52 @@ class executor {
if (!RESP[this.responseString]) {
RESP = RESP["RESPONSE_CODE_NOT_FOUND"];
} else {
RESP = RESP[this.responseString];
RESP = {...RESP[this.responseString]};
}

this.responseCode = RESP.responseCode;
this.responseMessage = this.lng_key && RESP.responseMessage[this.lng_key]
RESP.responseMessage = this.lng_key && RESP.responseMessage[this.lng_key]
? RESP.responseMessage[this.lng_key]
: RESP.responseMessage[DEFAULT_LNG_KEY];

if (this.responseOptions)
Object.keys(this.responseOptions).map(keyName => {
this.responseMessage = this.responseMessage.replace(keyName, this.responseOptions[keyName]);
RESP.responseData = this.responseData;

if(this.responseOptions)
Object.keys(this.responseOptions).map(keyName => {
RESP.responseMessage = RESP.responseMessage.replace(keyName, this.responseOptions[keyName]);
});

return this.parseResponseData(CUSTOM_RESPONSE_TEMPLATE,RESP);

}

parseResponseData(CUSTOM_RESPONSE_TEMPLATE,RESP){
try{
Object.entries(RESP).forEach(array => {
const [key,value] = array;
if(typeof value === 'object'){
RESP[key] = "{" + JSON.stringify(value) + "}";
}
});

const compiled = _.template(typeof CUSTOM_RESPONSE_TEMPLATE === 'string' ? CUSTOM_RESPONSE_TEMPLATE : JSON.stringify(CUSTOM_RESPONSE_TEMPLATE));

return {
responseCode: this.responseCode,
responseMessage: this.responseMessage,
responseData: this.responseData
};
const resultTemplate = compiled(RESP);

const matcherObj = {
'"{{': '{',
'}}"': '}',
'"{[': '[',
']}"': ']'
}

const replacedString = multiReplace(resultTemplate, matcherObj);

return typeof CUSTOM_RESPONSE_TEMPLATE === 'string' ? replacedString : JSON.parse(replacedString);
}catch(error){
throw new Error("parseResponseData Error:"+error);
}
}

}

module.exports = executor;
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@njs2/base",
"version": "2.3.0",
"version": "2.3.1",
"description": "",
"main": "index.js",
"scripts": {
Expand Down
5 changes: 5 additions & 0 deletions template/frameworkStructure/src/config/responseTemplate.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"responseCode":"<%=responseCode%>",
"responseMessage":"<%=responseMessage%>",
"responseData":"<%=responseData%>"
}

0 comments on commit 745bab6

Please sign in to comment.