UNPKG

2.44 kBPlain TextView Raw
1
2export const ResponseParser: any = {
3 /**
4 * Method to parse plain API response into js object
5 * @param raw API plain response
6 * @returns API response as JS Object (hash)
7 */
8 parse: (raw: string): any => {
9 const hash: any = {};
10 const regexp = /^([^=]*[^\t= ])[\t ]*=[\t ]*(.*)$/;
11 const r = raw.replace(/\r\n/g, "\n").split("\n");
12 while (r.length) {
13 const row = r.shift();
14 let m;
15 if (row) {
16 m = row.match(regexp);
17 if (m) {
18 const mm = m[1].match(/^property\[([^\]]*)\]/i);
19 if (mm) {
20 if (!Object.prototype.hasOwnProperty.call(hash, "PROPERTY")) {
21 hash.PROPERTY = {};
22 }
23 mm[1] = mm[1].toUpperCase().replace(/\s/g, "");
24 if (!Object.prototype.hasOwnProperty.call(hash.PROPERTY, mm[1])) {
25 hash.PROPERTY[mm[1]] = [];
26 }
27 hash.PROPERTY[mm[1]].push(m[2].replace(/[\t ]*$/, ""));
28 } else {
29 hash[m[1].toUpperCase()] = m[2].replace(/[\t ]*$/, "");
30 }
31 }
32 }
33 }
34 return hash;
35 },
36 /**
37 * Serialize given parsed response hash back to plain text
38 * @param r API response as JS Object (hash)
39 * @returns plain API response
40 */
41 serialize: (r: any): string => {
42 let plain = "[RESPONSE]";
43 if (Object.prototype.hasOwnProperty.call(r, "PROPERTY")) {
44 Object.keys(r.PROPERTY).forEach((key) => {
45 r.PROPERTY[key].forEach((val: string, index: number) => {
46 plain += `\r\nPROPERTY[${key}][${index}]=${val}`;
47 });
48 });
49 }
50 if (Object.prototype.hasOwnProperty.call(r, "CODE")) {
51 plain += `\r\nCODE=${r.CODE}`;
52 }
53 if (Object.prototype.hasOwnProperty.call(r, "DESCRIPTION")) {
54 plain += `\r\nDESCRIPTION=${r.DESCRIPTION}`;
55 }
56 if (Object.prototype.hasOwnProperty.call(r, "QUEUETIME")) {
57 plain += `\r\nQUEUETIME=${r.QUEUETIME}`;
58 }
59 if (Object.prototype.hasOwnProperty.call(r, "RUNTIME")) {
60 plain += `\r\nRUNTIME=${r.RUNTIME}`;
61 }
62 plain += "\r\nEOF\r\n";
63 return plain;
64 }
65};