UNPKG

8.4 kBJavaScriptView Raw
1'use strict';
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6
7var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
8
9var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
10
11var _fact = require('./fact');
12
13var _fact2 = _interopRequireDefault(_fact);
14
15var _errors = require('./errors');
16
17var _debug = require('./debug');
18
19var _debug2 = _interopRequireDefault(_debug);
20
21var _jsonpathPlus = require('jsonpath-plus');
22
23var _lodash = require('lodash.isobjectlike');
24
25var _lodash2 = _interopRequireDefault(_lodash);
26
27function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
28
29function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
30
31/**
32 * Fact results lookup
33 * Triggers fact computations and saves the results
34 * A new almanac is used for every engine run()
35 */
36var Almanac = function () {
37 function Almanac(factMap) {
38 var runtimeFacts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
39 var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
40
41 _classCallCheck(this, Almanac);
42
43 this.factMap = new Map(factMap);
44 this.factResultsCache = new Map(); // { cacheKey: Promise<factValu> }
45 this.allowUndefinedFacts = Boolean(options.allowUndefinedFacts);
46
47 for (var factId in runtimeFacts) {
48 var fact = void 0;
49 if (runtimeFacts[factId] instanceof _fact2.default) {
50 fact = runtimeFacts[factId];
51 } else {
52 fact = new _fact2.default(factId, runtimeFacts[factId]);
53 }
54
55 this._addConstantFact(fact);
56 (0, _debug2.default)('almanac::constructor initialized runtime fact:' + fact.id + ' with ' + fact.value + '<' + _typeof(fact.value) + '>');
57 }
58 }
59
60 /**
61 * Retrieve fact by id, raising an exception if it DNE
62 * @param {String} factId
63 * @return {Fact}
64 */
65
66
67 _createClass(Almanac, [{
68 key: '_getFact',
69 value: function _getFact(factId) {
70 return this.factMap.get(factId);
71 }
72
73 /**
74 * Registers fact with the almanac
75 * @param {[type]} fact [description]
76 */
77
78 }, {
79 key: '_addConstantFact',
80 value: function _addConstantFact(fact) {
81 this.factMap.set(fact.id, fact);
82 this._setFactValue(fact, {}, fact.value);
83 }
84
85 /**
86 * Sets the computed value of a fact
87 * @param {Fact} fact
88 * @param {Object} params - values for differentiating this fact value from others, used for cache key
89 * @param {Mixed} value - computed value
90 */
91
92 }, {
93 key: '_setFactValue',
94 value: function _setFactValue(fact, params, value) {
95 var cacheKey = fact.getCacheKey(params);
96 var factValue = Promise.resolve(value);
97 if (cacheKey) {
98 this.factResultsCache.set(cacheKey, factValue);
99 }
100 return factValue;
101 }
102
103 /**
104 * Adds a constant fact during runtime. Can be used mid-run() to add additional information
105 * @param {String} fact - fact identifier
106 * @param {Mixed} value - constant value of the fact
107 */
108
109 }, {
110 key: 'addRuntimeFact',
111 value: function addRuntimeFact(factId, value) {
112 var fact = new _fact2.default(factId, value);
113 return this._addConstantFact(fact);
114 }
115
116 /**
117 * Returns the value of a fact, based on the given parameters. Utilizes the 'almanac' maintained
118 * by the engine, which cache's fact computations based on parameters provided
119 * @param {string} factId - fact identifier
120 * @param {Object} params - parameters to feed into the fact. By default, these will also be used to compute the cache key
121 * @param {String} path - object
122 * @return {Promise} a promise which will resolve with the fact computation.
123 */
124
125 }, {
126 key: 'factValue',
127 value: function factValue(factId) {
128 var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
129 var path = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';
130
131 var factValuePromise = void 0;
132 var fact = this._getFact(factId);
133 if (fact === undefined) {
134 if (this.allowUndefinedFacts) {
135 return Promise.resolve(undefined);
136 } else {
137 return Promise.reject(new _errors.UndefinedFactError('Undefined fact: ' + factId));
138 }
139 }
140 if (fact.isConstant()) {
141 factValuePromise = Promise.resolve(fact.calculate(params, this));
142 } else {
143 var cacheKey = fact.getCacheKey(params);
144 var cacheVal = cacheKey && this.factResultsCache.get(cacheKey);
145 if (cacheVal) {
146 factValuePromise = Promise.resolve(cacheVal);
147 (0, _debug2.default)('almanac::factValue cache hit for fact:' + factId);
148 } else {
149 (0, _debug2.default)('almanac::factValue cache miss for fact:' + factId + '; calculating');
150 factValuePromise = this._setFactValue(fact, params, fact.calculate(params, this));
151 }
152 }
153 if (path) {
154 // selectn supports arrays and strings as a 'path'
155 // strings starting with '$' denotes json path. otherwise fall back to deprecated 'selectn' syntax
156 if (typeof path === 'string' && path.startsWith('$')) {
157 (0, _debug2.default)('condition::evaluate extracting object property ' + path);
158 return factValuePromise.then(function (factValue) {
159 if ((0, _lodash2.default)(factValue)) {
160 var pathValue = (0, _jsonpathPlus.JSONPath)({ path: path, json: factValue, wrap: false });
161 (0, _debug2.default)('condition::evaluate extracting object property ' + path + ', received: ' + pathValue);
162 return pathValue;
163 } else {
164 (0, _debug2.default)('condition::evaluate could not compute object path(' + path + ') of non-object: ' + factValue + ' <' + (typeof factValue === 'undefined' ? 'undefined' : _typeof(factValue)) + '>; continuing with ' + factValue);
165 return factValue;
166 }
167 });
168 } else {
169 var selectn = void 0;
170 try {
171 selectn = require('selectn');
172 } catch (err) {
173 console.error('Oops! Looks like you\'re trying to use the deprecated syntax for the ".path" property.');
174 console.error('Please convert your "path" properties to JsonPath syntax (ensure your path starts with "$")');
175 console.error('Alternatively, if you wish to continue using old syntax (provided by selectn), you may "npm install selectn" as a direct dependency.');
176 console.error('See https://github.com/CacheControl/json-rules-engine/blob/master/CHANGELOG.md#500--2019-10-27 for more information.');
177 throw new Error('json-rules-engine: Unmet peer dependency "selectn" required for use of deprecated ".path" syntax. please "npm install selectn" or convert to json-path syntax');
178 }
179 return factValuePromise.then(function (factValue) {
180 if ((0, _lodash2.default)(factValue)) {
181 var pathValue = selectn(path)(factValue);
182 (0, _debug2.default)('condition::evaluate extracting object property ' + path + ', received: ' + pathValue);
183 return pathValue;
184 } else {
185 (0, _debug2.default)('condition::evaluate could not compute object path(' + path + ') of non-object: ' + factValue + ' <' + (typeof factValue === 'undefined' ? 'undefined' : _typeof(factValue)) + '>; continuing with ' + factValue);
186 return factValue;
187 }
188 });
189 }
190 }
191
192 return factValuePromise;
193 }
194 }]);
195
196 return Almanac;
197}();
198
199exports.default = Almanac;
\No newline at end of file