-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
57 lines (55 loc) · 1.56 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
var jp = require("jsonpath");
module.exports.responseHooks = [
(context) => {
const jsonPath = context.request.getHeader("INSOMNIA-RESPONSE-JSON-PARSE");
let errors = 0;
if (jsonPath) {
let response = {};
try {
response = JSON.parse(context.response.getBody().toString());
} catch (error) {
console.error("Error parsing response body", error);
return;
} finally {
try {
var values = jp
.query(response, jsonPath)
.map((value) => JSON.parse(value));
var paths = jp
.paths(response, jsonPath)
.map((path) => path.slice(1).join("."));
var modVals = {};
for (let index = 0; index < paths.length; index++) {
modVals[paths[index]] = values[index];
}
Object.entries(modVals).forEach(([key, value]) => {
setAttributeFromPath(key, response, value);
});
} catch (error) {
errors++;
console.error(error);
}
}
if (errors == 0) {
context.response.setBody(Buffer.from(JSON.stringify(response)));
} else {
console.error(
"Error in plugin response-json-parse, not modifying response"
);
}
}
},
];
const setAttributeFromPath = (path, entity, value) => {
const pathParts = path.split(".");
let obj = entity;
pathParts.forEach((part, index) => {
if (obj[part]) {
if (index < pathParts.length - 1) {
obj = obj[part];
} else {
obj[part] = value;
}
}
});
};