-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathambush.js
400 lines (346 loc) · 9.5 KB
/
ambush.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
const _ = require('lodash');
const JSONfn = require('json-fn');
const goblin = require('./goblin');
const Storage = require('./storage').ambush;
const logger = require('./logger');
/**
* Ambush function data object.
*
* @typedef {object} Ambush
* @property {string} id Id of the ambush function.
* @property {string} description Optional. Describe what the action does.
* @property {array} category Optional. Category/ies to filter ambush functions later.
* @property {function} action Action perform by this ambush function when calling method
* run() {@see #run}
*/
// Goblin Internal Events + Hooks Execution
goblin.ambushEmitter.on('change', function(details) {
Storage.save(goblin.config.files.ambush, compileFn(goblin.ambush), function(err) {
err && logger('AMBUSH_SAVE_FS', err);
});
// Hooks management
goblin.hooks.repository.forEach(function(hook) {
if (hook.event === 'ambush-' + details.type || hook.event === 'ambush-change') {
hook.callback({'value': details.value, 'oldValue': details.oldValue});
}
});
});
/**
* Initialize ambush functions database. Try to read from the configured file route,
* if the file don't exist then try to create it with the default db.
*
* @param {function} cb Callback function called when the ambush db is initialized,
* meaning the functions have been restored from file. The function
* gets a parameter which is an error message if any.
* @returns {void}
*/
function init(cb) {
Storage.read(goblin.config.files.ambush, [], function(err, db) {
if (err) {
return cb(err);
}
goblin.ambush = restoreFn(db);
cb();
});
}
/**
* Parse functions when loading file restoring then to js valid objects.
*
* @param {array} db Ambush functions db
* @returns {arrat} Parsed db ready to use.
*/
function restoreFn(db) {
return db.map(function(amb) {
return Object.assign({}, amb, {action: JSONfn.parse(amb.action)});
});
}
/**
* Turn actions in every ambush function into valid json strings.
*
* @param {array} db Ambush functions db.
* @returns {arrat} Compiled db ready to save.
*/
function compileFn(db) {
return db.map(function(amb) {
return Object.assign({}, amb, {action: JSONfn.stringify(amb.action)});
});
return result;
}
/**
* Store a new ambush function. Validates id doesn't exist already, etc.
*
* @param {Ambush} object Ambush function data.
* @returns {void} Nothing.
*/
function add(object) {
if (!_isValidAmbush(object)) {
return false;
}
object.description = _cleanDescription(object.description);
if (!_belongToAStoredAmbush(object.id)) {
const newObject = Object.assign({}, object);
goblin.ambush.push(newObject);
goblin.ambushEmitter.emit('change', { type: 'add', value: newObject });
} else {
logger('AMBUSH_ADD_ERROR');
}
}
/**
* Remove an ambush function from the database.
*
* @param {string} id Ambush function id.
* @returns {void} Nothing.
*/
function remove(id) {
if (!_isValidId(id)) {
return false;
}
const oldValue = JSONfn.clone(goblin.ambush);
_.remove(goblin.ambush, function(current) {
return current.id === id;
});
goblin.ambushEmitter.emit('change', {
type: 'remove',
oldValue: oldValue
});
}
/**
* Updates an ambush function.
*
* @param {string} id Ambush function id.
* @param {Ambush} object Ambush function data.
* @returns {bool} If updated or not.
*/
function update(id, object) {
// Validations
if (!_isValidId(id)) {
return false;
}
// Action
const index = _getIndexOfId(id);
if (index > -1) {
if (_isValidAmbushOnUpdate(id, object)) {
const current = goblin.ambush[index];
const newAmbush = Object.assign({}, current, object);
newAmbush.description = _cleanDescription(newAmbush.description);
// Set updated ambush
goblin.ambush[index] = newAmbush;
goblin.ambushEmitter.emit(
'change',
{
type: 'update',
oldValue: JSONfn.clone(current),
value: JSONfn.clone(goblin.ambush[index])
}
);
}
} else {
logger('AMBUSH_UPDATE_INVALID_REFERENCE');
}
return true;
}
/**
* Gets an ambush function data.
*
* @param {string} id Ambush function id.
* @returns {Ambush} Ambush function data.
*/
function details(id) {
if (!_isValidId(id)) {
return false;
}
const index = _getIndexOfId(id);
if (index === -1) {
return logger('AMBUSH_NOT_STORED_ID');
}
return goblin.ambush[index];
}
/**
* List all ambush function ids that match the passed category. If actegory is a falsy
* then all ambush functions will be listed.
*
* @param {string} category Ambush function category.
* @returns {array} Ids of the ambush functions of that category.
*/
function list(category){
let list = [];
if (category && typeof(category) === 'string') {
list = _(goblin.ambush).filter(function(current) {
return _.includes(current.category, category);
}).map('id').value();
} else {
list = _(goblin.ambush).map('id').value();
}
return list;
}
/**
* Run an ambush function action.
*
* @param {string} id Ambush function id.
* @param {any} parameter First parameter for the ambush function action.
* @param {function} callback Second parameter for the ambush function action.
* @returns {array} Ids of the ambush functions of that category.
*/
function run(id, parameter, callback) {
if (!_isValidId(id)) {
return false;
}
if (callback && typeof(callback) !== 'function') {
logger('AMBUSH_NO_CALLBACK');
}
const index = _getIndexOfId(id);
if (index > -1) {
goblin.ambush[index].action(parameter, callback);
} else {
logger('AMBUSH_INVALID_REFERENCE');
}
}
// Internal Functions
/**
* Validate description returning the description only if valid and false otherwise.
*
* @param {string} id Ambush function id.
* @returns {(string | bool)} The description string if valid or false.
*/
function _cleanDescription(description) {
return (description && typeof(description) === 'string') ? description : false;
}
/**
* Validates ambush function data object on create.
*
* @param {Ambush} object Ambush function data.
* @returns {bool} If it's valid or not.
*/
function _isValidAmbush(object) {
return _isValidObject(object) &&
_isValidId(object.id) &&
_isUniqueId(null, object.id) &&
_isValidCategory(object.category) &&
_isValidAction(object.action);
}
/**
* Validates ambush function data object on update.
*
* @param {string} id Ambush function id.
* @param {Ambush} object Ambush function data.
* @returns {bool} If it's valid or not.
*/
function _isValidAmbushOnUpdate(id, object) {
return _isValidObject(object) &&
_isValidNotRequired(object.id, _isValidId) &&
_isUniqueId(id, object.id) &&
_isValidNotRequired(object.category, _isValidCategory) &&
_isValidNotRequired(object.action, _isValidAction);
}
/**
* Tells if the passed element is a valid object (not an array).
*
* @param {object} object The object to be validated.
* @returns {bool} If it's valid or not.
*/
function _isValidObject(object) {
if (!object || Array.isArray(object) || typeof(object) !== 'object') {
logger('AMBUSH_INVALID_DATA');
return false;
}
return true;
}
/**
* Validates passed if is a string and it's not empty.
*
* @param {string} id Ambush function id.
* @returns {bool} If it's valid or not.
*/
function _isValidId(id) {
if (!id || typeof(id) !== 'string') {
logger('AMBUSH_INVALID_ID');
return false;
}
return true;
}
/**
* Validates passed action checking if it's a function.
*
* @param {function} action Ambush function action.
* @returns {bool} If it's valid or not.
*/
function _isValidAction(action) {
if (!action || typeof(action) !== 'function') {
logger('AMBUSH_INVALID_ACTION');
return false;
}
return true;
}
/**
* Validates passed category.
*
* @param {array} category Ambush function categories.
* @returns {bool} If it's valid or not.
*/
function _isValidCategory(category) {
if (!category || !Array.isArray(category)) {
logger('AMBUSH_INVALID_CATEGORY');
return false;
}
return true;
}
/**
* Validates an id doesn't belong to an already stored ambush function. When updating
* an ambush function id check if the new id it's already in use.
*
* @param {string} currentId Ambush function current id.
* @param {string} newId Ambush function new id.
* @returns {bool} If it already exist or not.
*/
function _isUniqueId(currentId, newId) {
if (
newId !== undefined &&
currentId !== newId &&
_belongToAStoredAmbush(newId)
) {
logger('AMBUSH_PROVIDED_ID_ALREADY_EXIST');
return false;
}
return true;
}
/**
* Takes two arguments, one of then is the element that may or may not exist and the
* other one is the validation function to apply over it when it exist.
*
* @param {any} element The element to be validated.
* @param {function} validatorCallback The validator to apply over that element.
* @returns {bool} True if there's no element or pass validation, false otherwise.
*/
function _isValidNotRequired(element, validatorCallback) {
if (element !== undefined) {
return validatorCallback(element);
}
return true;
}
/**
* Gets the index of an stored ambush function given its id (or -1 if not exist).
*
* @param {string} id Ambush function id.
* @returns {int} Index of the ambush function or -1.
*/
function _getIndexOfId(id) {
return _.indexOf(goblin.ambush, _.find(goblin.ambush, {id}))
}
/**
* Check if the passed id belongs to an stored ambush function.
*
* @param {string} id Ambush function id.
* @returns {bool} If exist or not.
*/
function _belongToAStoredAmbush(id) {
return _getIndexOfId(id) > -1
}
module.exports = {
init: init,
add: add,
remove: remove,
update: update,
details: details,
list: list,
run: run
};