-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
527 lines (442 loc) · 12.3 KB
/
index.js
File metadata and controls
527 lines (442 loc) · 12.3 KB
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
var Promise = require('bluebird');
var sugar = require('sugar');
module.exports = {
isEmptyObject: isEmptyObject,
isEmpty: isEmpty,
isTrue: isTrue,
isFalse: isFalse,
propEquals: propEquals,
strtotime: strtotime,
convertVideoLinksToEmbeds: convertVideoLinksToEmbeds,
overwriteObjectUndefineds: overwriteObjectUndefineds,
capitalizeFirstLetter: capitalizeFirstLetter,
getBasicHtml: getBasicHtml,
nonEmptyValueOr: nonEmptyValueOr,
fullHttpGet: fullHttpGet,
fullHttpsGet: fullHttpsGet,
chainDeferreds: chainDeferreds,
chainDeferredFunctions: chainDeferredFunctions,
rejectedPromise: rejectedPromise,
resolvedPromise: resolvedPromise,
arrayUnique: arrayUnique,
deepLog: deepLog,
objectHash: objectHash,
objectToArray: objectToArray,
setProperty: setProperty,
pushIntoArray: pushIntoArray,
removeEmptyKeys: removeEmptyKeys,
convertRange: convertRange,
checkRequiredFields: checkRequiredFields,
hasObject: hasObject,
setSessionUser: setSessionUser,
isJsonString: isJsonString,
parseUrlParams: parseUrlParams,
setResultsKeys: setResultsKeys,
mergeByKey: mergeByKey,
flattenObject: flattenObject,
unFlattenObject: unFlattenObject,
};
function isEmptyObject(obj) {
for(var prop in obj){
return false;
}
return true;
}
//allows deep object checking for empty (empty is 0, '', false, null, [], {}, undefined);
function isEmpty(_obj /*, level1, level2, ... levelN*/ ){
var i = 0;
var obj = _obj;
while(i < arguments.length){
if(i !== 0){
obj = obj[arguments[i]];
}
//below is same as :
// typeof obj === 'undefined'
// || obj === null
// || obj === false
// || (typeof obj === 'string' && !obj)
// || (typeof obj === 'number' && !obj)
if(!obj){
return true;
}
if(typeof obj.constructor !== 'undefined'){
var proto = obj.constructor.prototype;
if(
(
proto === Object.prototype //plain object
|| proto === Array.prototype //plain array
)
&& isEmptyObject(obj)
){
return true;
//NOTE: cannot just test length of array because a property may have been added to it (not pushed, added)
}
}
i++;
}
return false;
}
//GET variables are string, POST variables are bool
function isTrue(param){
return ['true', true].some(param);
}
//GET variables are string, POST variables are bool
function isFalse(param){
return ['false', false].some(param);
}
//Utils.propEquals(obj, 'prop1', 'prop2', 123); //returns true if obj.prop1.prop2 == 123
function propEquals(obj){
/*var obj = arguments.slice(0, 1);
var val = arguments.pop();
if(isEmpty.apply(this, arguments)){
return false;
}*/
if(typeof obj === 'undefined'){
return false;
}
for(var i = 1; i < arguments.length - 1; i++){
var obj = obj[arguments[i]];
if(typeof obj === 'undefined'){
return false;
}
}
return obj == arguments[arguments.length-1];
}
function strtotime(text){
return parseInt(Date.create(text).getTime() / 1000);
}
function convertVideoLinksToEmbeds(string) {
//youtube
string = string.replace(/[a-zA-Z\/\/:\.]*youtube.com\/watch\?v=([a-zA-Z0-9\-_]+)([a-zA-Z0-9\/\*\-\_\?\&\;\%\=\.]*)/i, "<iframe class=\"embed\" src=\"//www.youtube.com/embed/$1\" frameborder=\"0\" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>");
//vimeo
string = string.replace(/[a-zA-Z\/\/:\.]*vimeo.com\/([a-zA-Z0-9\-_]+)([a-zA-Z0-9\/\*\-\_\?\&\;\%\=\.]*)/i, "<iframe class=\"embed\" src=\"//player.vimeo.com/video/$1\" frameborder=\"0\" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>");
return string;
}
//will overwrite obj1 property values with those from obj2, unless they are already defined
function overwriteObjectUndefineds(obj1, obj2){
for(var prop in obj2){
if(typeof obj1[prop] === 'undefined'){
obj1[prop] = obj2[prop];
}
}
return obj1;
}
function capitalizeFirstLetter(string){
return string.charAt(0).toUpperCase() + string.slice(1);
}
function getBasicHtml(body){
return '<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"></head><body>' + body + '</body></html>';
}
// Utils.nonEmptyValueOr(data, '_json.hometown.name', 'alternative');
function nonEmptyValueOr(object, dotString, otherValue){
var keys = dotString.split('.');
var isEmptyParams = [object].concat(keys);
if(!isEmpty.apply(this, isEmptyParams)){
var value = object;
while(keys.length){
value = value[keys.splice(0, 1)];
}
return value;
}else{
return otherValue;
}
}
//removes the need to do chunking
function fullHttpGet(options, callback){
var request = require('http').get(options, function(res){
var data = '';
res.on('data', function(chunk){
data += chunk;
}).on('error', function(e){
callback(e);
console.log(e.stack);
}).on('end', function(){
callback(null, data);
});
}).on('error', function(e){
callback(e);
console.log(e.stack);
});
request.setTimeout(5000, function(){
request.abort();
//callback('timed out'); error callback is handled in normail callback
});
request.end();
}
//removes the need to do chunking
function fullHttpsGet(options, callback){
require('https').get(options, function(res){
var data = '';
res.on('data', function(chunk){
data += chunk;
});
res.on('end', function(){
callback(null, data);
});
}).on('error', function(e){
callback(e);
});
}
//this can never work because the deferred is ran at the time it is added to the deferreds array. must use chainDeferredFunctions below
function chainDeferreds(deferreds){
/*return deferreds.reduce(function(previous, current){
return previous.then(current);
}, resolvedPromise());*/
var promise = deferreds[0];
for(var i = 1; i < deferreds.length; i++){
promise = promise.then(deferreds[i]);
}
return deferreds[deferreds.length-1];
}
/*
//https://github.com/kriskowal/q#sequences
function chainDeferredFunctions(funcs){
return funcs.reduce(q.when, q(null));
*//*return funcs.reduce(function(soFar, f){
return soFar.then(f);
}, q(null));*//*
}*/
function chainDeferredFunctions(funcs){
return Promise.reduce(funcs, function(previousValue, task) {
return task(previousValue);
}, null);
}
/*function rejectedPromise(error){
var deferred = Promise.defer();
deferred.reject(error);
return deferred.promise;
}*/
function rejectedPromise(error, props){
var deferred = Promise.defer();
error = error instanceof Array ? error.map(function(error){
return transformError(error, props);
}) : transformError(error, props);
deferred.reject(error);
return deferred.promise;
}
function resolvedPromise(data){
var deferred = Promise.defer();
deferred.resolve(data);
return deferred.promise;
}
function arrayUnique(array){
return array.unique(); //added with sugarjs
}
function deepLog(){
objectToArray(arguments).forEach(function(arg){
//if(typeof arg === 'object'){
console.log(require('util').inspect(arg, true, 100));
//}else{
// console.log(arg);
//}
});
}
//creates a unique hash of an object
// http://stackoverflow.com/a/8076436
function objectHash(obj){
var objString = JSON.stringify(obj);
var hash = 0;
if(objString.length === 0){
return hash;
}
for(var i = 0; i < objString.length; i++){
var character = objString.charCodeAt(i);
hash = ((hash << 5) - hash) + character;
hash = hash & hash; // Convert to 32bit integer
}
return 'c' + hash;
}
function objectToArray(obj){
var values = [];
var keys = Object.keys(obj);
for(var i = 0; i < keys.length; i++){
var key = keys[i];
values.push(obj[key]);
}
return values;
}
//setProperty(obj, 'prop, 'subprop', 'subsubprop', 314);
function setProperty(obj){
if(arguments.length < 3){
console.log('Utils.setProperty: less than 3 arguments');
return false;
}
if(typeof obj !== 'object'){
console.log('Utils.setProperty: first argument is not an object');
return false;
}
var tempObj = obj;
for(var i = 1; i < arguments.length - 1; i++){
if(typeof arguments[i] !== 'string'){
console.log('Utils.setProperty: argument ' + i + ' is not a string');
return false;
}
if(i < arguments.length - 2){
if(typeof tempObj[arguments[i]] === 'undefined'){
tempObj[arguments[i]] = {};
}
else if(typeof tempObj[arguments[i]] !== 'object'){
console.log('Utils.setProperty: object at property ' + arguments[i] + ' is not an object');
return false;
}
tempObj = tempObj[arguments[i]];
}
}
tempObj[arguments[arguments.length - 2]] = arguments[arguments.length - 1];
}
//makes sure that prop or obj is an array
function pushIntoArray(obj, prop, item){
if(!(obj[prop] instanceof Array)){
if(typeof obj[prop] == 'undefined'){
obj[prop] = [];
}else{
obj[prop] = [obj[prop]];
}
}
obj[prop].push(item);
}
//modifies original obj
function removeEmptyKeys(obj){
Object.keys(obj).forEach(function(key){
if(!obj[key]){
delete obj[key];
}
});
return obj;
}
//converts a number's value in one range to it's corresponding value in another range
function convertRange(value, r1, r2){
return (value - r1[0]) * (r2[1] - r2[0]) / (r1[1] - r1[0]) + r2[0];
}
//fields can be object or array
function checkRequiredFields(data, fields, errors){
var obj = {};
var keys = [];
if(fields instanceof Array){
for(var i = 0; i < fields.length; i++){
var field = fields[i];
obj[field] = field;
keys.push(field);
}
}else{
obj = fields;
keys = Object.keys(obj);
}
for(var i = 0; i < keys.length; i++){
var key = keys[i];
if(typeof data === 'undefined' || typeof data[key] === 'undefined'){
errors.push('ERROR: ' + obj[key] + ' is required');
}
}
}
//determines if array has a object who's key matches value
function hasObject(objects, key, value){
return objects.some(function(object){
return object[key] == value;
});
}
//turns the session save method into a promise
function setSessionUser(req, user){
var deferred = Promise.defer();
req.session.user = user;
req.session.save(function(){
deferred.resolve(user);
});
return deferred.promise;
}
function isJsonString(str){
try{
JSON.parse(str);
}catch(e){
return false;
}
return true;
}
function transformError(error, props){
if(typeof error === 'string'){
error = new Error(error);
}
if(typeof props !== 'undefined'){
for(var prop in props){
error[prop] = props[prop];
}
}
if(typeof error.type === 'undefined' && error.message.substr(0, 7) !== 'ERROR: '){
error.type = 'internal';
}
return error;
}
function parseUrlParams(format, url){
var formatParts = format.split('/');
var urlParts = url.split('/');
var params = {};
for(var i = 0; i < Math.min(formatParts.length, urlParts.length); i++){
if(formatParts[i][0] === ':'){
params[formatParts[i].substr(1)] = urlParts[i];
}
else if(formatParts[i] !== urlParts[i]){
throw new Error('mismatched urls: ', format, url);
}
}
return params;
}
// takes an array of db results and returns an object of the same values but with "key" as the key value
function setResultsKeys(results, key){
var resultsByKey = {};
for(var i = 0; i < results.length; i++){
var result = results[i];
resultsByKey[result[key]] = result;
}
return resultsByKey;
}
//merges rows from arr2 into the matching (by key) row from arr1
function mergeByKey(arr1, arr2, key){
var arr2ByIds = setResultsKeys(arr2, key);
for(var i = 0; i < arr1.length; i++){
var user = arr1[i];
if(!isEmpty(arr2ByIds, user.Users_id)){
Object.merge(user, arr2ByIds[user.Users_id]);
}
}
return arr1; //arr1 is updated by reference, but return it anyway
}
function flattenObject(obj){
var result = {};
function recurse (cur, prop) {
if (Object(cur) !== cur) {
result[prop] = cur;
} else if (Array.isArray(cur)) {
for(var i=0, l=cur.length; i<l; i++)
recurse(cur[i], prop + "[" + i + "]");
if (l == 0)
result[prop] = [];
} else {
var isEmpty = true;
for (var p in cur) {
isEmpty = false;
recurse(cur[p], prop ? prop+"."+p : p);
}
if (isEmpty && prop)
result[prop] = {};
}
}
recurse(obj, "");
return result;
}
function unFlattenObject(obj){
if (Object(obj) !== obj || Array.isArray(obj))
return obj;
var regex = /\.?([^.\[\]]+)|\[(\d+)\]/g,
resultholder = {};
for (var p in obj) {
var cur = resultholder,
prop = "",
m;
while (m = regex.exec(p)) {
cur = cur[prop] || (cur[prop] = (m[2] ? [] : {}));
prop = m[2] || m[1];
}
cur[prop] = obj[p];
}
return resultholder[""] || resultholder;
}