UNPKG

2.39 kBJavaScriptView Raw
1const _ = require('lodash');
2const Mustache = require('mustache');
3
4module.exports = class DialogParsing {
5 constructor() {}
6
7 static resolveDialog(session, item) {
8 session = _.cloneDeep(session);
9 item = _.cloneDeep(item);
10 let result = item;
11 if (item) {
12 if (
13 item.iterator &&
14 item.iterator.enabled &&
15 item.iterator.itemName &&
16 item.iterator.variableName
17 ) {
18 result = DialogParsing.resolveIterator(session, item);
19 } else {
20 result = DialogParsing.replaceVariablesDialog(session, item);
21 }
22 }
23
24 // Clean up remaining mustache variables
25 return JSON.parse(Mustache.render(JSON.stringify(result), {}));
26 }
27
28 static replaceVariablesDialog(session, item) {
29 let jsonString = null;
30
31 if (item) {
32 jsonString = JSON.stringify(item);
33 jsonString = Mustache.render(jsonString, session);
34 }
35 try {
36 if (!jsonString) {
37 throw new Error('Empty jsonString');
38 }
39 return JSON.parse(jsonString);
40 } catch (e) {
41 console.log(e);
42 return item;
43 }
44 }
45
46 static resolveIterator(session, item) {
47 try {
48 const itemClone = _.cloneDeep(item);
49 if (itemClone.value && itemClone.value.length === 1) {
50 const iterateVariable = _.get(session, itemClone.iterator.variableName);
51 const itemVariable = itemClone.iterator.itemName;
52 if (iterateVariable && itemVariable) {
53 const template = itemClone.value[0];
54 itemClone.value = [];
55
56 if (iterateVariable.length) {
57 for (const newContext of iterateVariable) {
58 const one = _.cloneDeep(template);
59 session[itemVariable] = newContext;
60 const newOne = DialogParsing.replaceVariablesDialog(session, one);
61 itemClone.value.push(newOne);
62 }
63 } else {
64 throw new Error('Returned array has empty data');
65 }
66 } else {
67 throw new Error("Input variables don't exist");
68 }
69
70 return itemClone;
71 }
72 throw new Error("Item doesn't have value property or value is not unique");
73 } catch (e) {
74 console.log(e);
75 item.value = []; // Prevent showing result
76 if (item.iterator && item.iterator.onEmptyGoToDialog) {
77 item.goToDialog = item.iterator.onEmptyGoToDialog;
78 }
79 return item;
80 }
81 }
82};