forked from pencilblue/pencilblue
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.js
executable file
·581 lines (525 loc) · 15.6 KB
/
util.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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
/*
Copyright (C) 2014 PencilBlue, LLC
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//dependencies
var extend = require('node.extend');
/**
* Provides a set of utility functions used throughout the code base
*
* @module Services
* @class Util
* @constructor
*/
function Util(){};
/**
* Clones an object by serializing it and then re-parsing it.
* WARNING: Objects with circular dependencies will cause an error to be thrown.
* @static
* @method clone
* @param {Object} object The object to clone
* @return {Object} Cloned object
*/
Util.clone = function(object){
return JSON.parse(JSON.stringify(object));
};
/**
* Performs a deep merge and returns the result. <b>NOTE:</b> DO NOT ATTEMPT
* TO MERGE PROPERTIES THAT REFERENCE OTHER PROPERTIES. This could have
* unintended side-effects as well as cause errors due to circular dependencies.
* @static
* @method deepMerge
* @param {Object} from
* @param {Object} to
* @return {Object}
*/
Util.deepMerge = function(from, to) {
return extend(true, to, from);
};
/**
* Checks if the supplied object is an errof. If the object is an error the
* function will throw the error.
* @static
* @method ane
* @param {Object} obj The object to check
*/
Util.ane = function(obj){
if (util.isError(obj)) {
throw obj;
}
};
/**
* Initializes an array with the specified number of values. The value at each
* index can be static or a function may be provided. In the event that a
* function is provided the function will be called for each item to be placed
* into the array. The return value of the function will be placed into the
* array.
* @static
* @method initArray
* @param {Integer} cnt The length of the array to create
* @param {Function|String|Number} val The value to initialize each index of
* the array
* @return {Array} The initialized array
*/
Util.initArray = function(cnt, val) {
var v = [];
var isFunc = Util.isFunction(val);
for(var i = 0; i < cnt; i++) {
v.push(isFunc ? val(i) : val);
}
return v;
};
/**
* Escapes a regular expression.
* @static
* @method escapeRegExp
* @param {String} The expression to escape
* @return {String} Escaped regular expression.
*/
Util.escapeRegExp = function(str) {
if (!Util.isString(str)) {
return null;
}
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
};
/**
* Merges the properties from the first parameter into the second. This modifies
* the second parameter instead of creating a new object.
*
* @method merge
* @param {Object} from
* @param {Object} to
*/
Util.merge = function(from, to) {
for (var prop in from) {
to[prop] = from[prop];
}
};
/**
* Creates an object that has both the properties of "a" and "b". When both
* objects have a property with the same name, "b"'s value will be preserved.
* @static
* @method union
* @return {Object} The union of properties from both a and b.
*/
Util.union = function(a, b) {
var union = {};
Util.merge(a, union);
Util.merge(b, union);
return union;
};
/**
* Creates a set of tasks that can be executed by the "async" module.
* @static
* @method getTasks
* @param {Array} iterable The array of items to build tasks for
* @param {Function} getTaskFunction The function that creates and returns the
* task to be executed.
* @example
* <code>
* var items = ['apple', 'orange'];
* var tasks = pb.utils.getTasks(items, function(items, i) {
* return function(callback) {
* console.log(items[i]);
* callback(null, null);
* };
* });
* async.series(tasks, pb.utils.cb);
* <code>
*/
Util.getTasks = function (iterable, getTaskFunction) {
var tasks = [];
for (var i = 0; i < iterable.length; i++) {
tasks.push(getTaskFunction(iterable, i));
}
return tasks;
};
/**
* Hashes an array
* @static
* @method arrayToHash
* @param {Array} array The array to hash
* @param {*} defaultVal Default value if the hashing fails
* @return {Object} Hash
*/
Util.arrayToHash = function(array, defaultVal) {
if (!util.isArray(array)) {
return null;
}
defaultVal = defaultVal || true;
var hash = {};
for(var i = 0; i < array.length; i++) {
if (typeof defaultVal === 'function') {
hash[defaultVal(array, i)] = array[i];
}
else {
hash[array[i]] = defaultVal;
}
}
return hash;
};
/**
* Converts an array to an object.
* @static
* @method arrayToObj
* @param {Array} array The array of items to transform from an array to an
* object
* @param {String|Function} keyFieldOrTransform When this field is a string it
* is expected that the array contains objects and that the objects contain a
* property that the string represents. The value of that field will be used
* as the property name in the new object. When this parameter is a function
* it is passed two parameters: the array being operated on and the index of
* the current item. It is expected that the function will return a value
* representing the key in the new object.
* @param {String|Function} [valFieldOrTransform] When this value is a string
* it is expected that the array contains objects and that the objects contain
* a property that the string represents. The value of that field will be used
* as the property value in the new object. When this parameter is a function
* it is passed two parameters: the array being operated on and the index of
* the current item. It is expected that the function return a value
* representing the value of the derived property for that item.
* @return {Object} The converted array.
*/
Util.arrayToObj = function(array, keyFieldOrTransform, valFieldOrTransform) {
if (!util.isArray(array)) {
return null;
}
var keyIsString = Util.isString(keyFieldOrTransform);
var keyIsFunc = Util.isFunction(keyFieldOrTransform);
if (!keyIsString && !keyIsFunc) {
return null;
}
var valIsString = Util.isString(valFieldOrTransform);
var valIsFunc = Util.isFunction(valFieldOrTransform);
if (!Util.isString(valFieldOrTransform) && !Util.isFunction(valFieldOrTransform)) {
valFieldOrTransform = null;
}
var obj = {};
for (var i = 0; i < array.length; i++) {
var item = array[i];
var key = keyIsString ? item[keyFieldOrTransform] : keyFieldOrTransform(array, i);
var val;
if (valIsString) {
obj[key] = item[valFieldOrTransform];
}
else if (valIsFunc) {
obj[key] = valFieldOrTransform(array, i);
}
else {
obj[key] = item;
}
}
return obj;
};
/**
* Converts an array of objects into a hash where the key the value of the
* specified property. If multiple objects in the array have the same value for
* the specified value then the last one found will be kept.
* @static
* @method objArrayToHash
* @param {Array} array The array to convert
* @param {String} hashProp The property who's value will be used as the key
* for each object in the array.
* @return {Object} A hash of the values in the array
*/
Util.objArrayToHash = function(array, hashProp) {
if (!util.isArray(array)) {
return null;
}
var hash = {};
for(var i = 0; i < array.length; i++) {
hash[array[i][hashProp]] = array[i];
}
return hash;
};
/**
* Converts a hash to an array. When provided, the hashKeyProp will be the
* property name of each object in the array that holds the hash key.
* @static
* @method hashToArray
* @param {Object} obj The object to convert
* @param {String} [hashKeyProp] The property name that will hold the hash key.
* @return {Array} An array of each property value in the hash.
*/
Util.hashToArray = function(obj, hashKeyProp) {
if (!Util.isObject(obj)) {
return null;
}
var a = [];
var doHashKeyTransform = Util.isString(hashKeyProp);
for (var prop in obj) {
a.push(obj[prop]);
if (doHashKeyTransform) {
obj[prop][hashKeyProp] = prop;
}
}
return a;
};
/**
* Inverts a hash
* @static
* @method invertHash
* @param {Object} obj Hash object
* @return {Object} Inverted hash
*/
Util.invertHash = function(obj) {
if (!Util.isObject(obj)) {
return null;
}
var new_obj = {};
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
new_obj[obj[prop]] = prop;
}
}
return new_obj;
};
/**
* Clones an array
* @static
* @method copyArray
* @param {Array} array
* @return {Array} Cloned array
*/
Util.copyArray = function(array) {
if (!util.isArray(array)) {
return null;
}
var clone = [];
for (var i = 0; i < array.length; i++) {
clone.push(array[i]);
}
return clone;
};
/**
* Pushes all of one array's values into another
* @static
* @method arrayPushAll
* @param {Array} from
* @param {Array} to
*/
Util.arrayPushAll = function(from, to) {
if (!util.isArray(from) || !util.isArray(to)) {
return;
}
for (var i = 0; i < from.length; i++) {
to.push(from[i]);
}
};
/**
* Empty callback function just used as a place holder if a callback is required
* and the result is not needed.
* @static
* @method cb
*/
Util.cb = function(err, result){
//do nothing
};
/**
* Creates a unique Id
* @static
* @method uniqueId
* @return {ObjectID} Unique Id Object
*/
Util.uniqueId = function(){
return new ObjectID();
};
/**
* Tests if a value is an object
* @static
* @method isObject
* @param {*} value
* @return {Boolean}
*/
Util.isObject = function(value) {
return value != undefined && value != null && typeof value === 'object';
};
/**
* Tests if a value is an string
* @static
* @method isString
* @param {*} value
* @return {Boolean}
*/
Util.isString = function(value) {
return value != undefined && value != null && typeof value === 'string';
};
/**
* Tests if a value is a function
* @static
* @method isFunction
* @param {*} value
* @return {Boolean}
*/
Util.isFunction = function(value) {
return value != undefined && value != null && typeof value === 'function';
};
/**
* Tests if a value is a boolean
* @static
* @method isBoolean
* @param {*} value
* @return {Boolean}
*/
Util.isBoolean = function(value) {
return value === true || value === false;
}
/**
* Retrieves the subdirectories of a path
* @static
* @method getDirectories
* @param {String} dirPath The starting path
* @param {Function} cb Callback function
*/
Util.getDirectories = function(dirPath, cb) {
var dirs = [];
fs.readdir(dirPath, function(err, files) {
if (util.isError(err)) {
cb(err, null);
return;
}
var tasks = pb.utils.getTasks(files, function(files, index) {
return function(callback) {
var fullPath = path.join(dirPath, files[index]);
fs.stat(fullPath, function(err, stat) {
if (util.isError(err)) {
pb.log.error("Failed to get stats on file ["+fullPath+"]: "+err);
}
else if (stat.isDirectory()) {
dirs.push(fullPath);
}
callback(err, null);
});
};
});
async.parallel(tasks, function(err, results) {
cb(err, dirs);
});
});
};
/**
* Retrieves file and/or directorie absolute paths under a given directory path.
* @static
* @method getFiles
* @param {String} dirPath The path to the directory to be examined
* @param {Object} [options] Options that customize the results
* @param {Boolean} [options.recursive=false] A flag that indicates if
* directories should be recursively searched.
* @param {Function} [options.filter] A function that returns a boolean
* indicating if the file should be included in the result set. The function
* should take two parameters. The first is a string value representing the
* absolute path of the file. The second is the stat object for the file.
* @param {Function} cb A callback that takes two parameters. The first is an
* Error, if occurred. The second is an array of strings representing the
* absolute paths for files that met the criteria specified by the filter
* function.
*/
Util.getFiles = function(dirPath, options, cb) {
if (Util.isFunction(options)) {
cb = options;
options = {
recursive: false,
filter: function(fullPath, stat) { return true; }
};
}
//read files from dir
fs.readdir(dirPath, function(err, q) {
if (util.isError(err)) {
return cb(err);
}
//seed the queue
for (var i = 0; i < q.length; i++) {
q[i] = path.join(dirPath, q[i]);
}
//process the q
var filePaths = [];
async.whilst(
function() { return q.length > 0; },
function(callback) {
var fullPath = q.shift();
fs.stat(fullPath, function(err, stat) {
if (util.isError(err)) {
pb.log.error("Failed to get stats on file DP=[%s] FILE=[%s] AP=[%s]: %s", dirPath, item, fullPath, err.stack);
return callback(err);
}
//apply filter
var meetsCriteria = true;
if (Util.isFunction(options.filter)) {
meetsCriteria = options.filter(fullPath, stat);
}
//examine result and add it when criteria is met
if (meetsCriteria) {
filePaths.push(fullPath);
}
//when recursive queue up directory's for processing
if (options.recursive && stat.isDirectory()) {
fs.readdir(fullPath, function(err, childFiles) {
if (util.isError(err)) {
return callback(err);
}
childFiles.forEach(function(item) {
q.push(path.join(fullPath, item));
});
callback(null);
});
}
else {
callback(null);
}
});
},
function(err) {
cb(err, filePaths);
}
);
});
};
/**
* Retrieves the extension off of the end of a string that represents a URI to
* a resource
* @static
* @method getExtension
* @param {String} path URI to the resource
* @param {Object} [options]
* @param {Boolean} [options.lower=false] When TRUE the extension will be returned as lower case
* @return {String} The value after the last '.' character
*/
Util.getExtension = function(path, options) {
if (!pb.validation.isNonEmptyStr(path, true)) {
return null;
}
var ext = null;
var index = path.lastIndexOf('.');
if (index >= 0) {
ext = path.substring(index + 1);
//apply options
if (options && options.lower) {
ext = ext.toLowerCase();
}
}
return ext;
};
/**
* Provides typical conversions for time
* @static
* @readonly
* @property TIME
* @type {Object}
*/
Util.TIME = Object.freeze({
MILLIS_PER_SEC: 1000,
MILLIS_PER_MIN: 60000,
MILLIS_PER_HOUR: 3600000,
MILLIS_PER_DAY: 86400000
});
//exports
module.exports = Util;