@qikdev/sdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,667 @@
1
+ import _ from 'lodash';
2
+ import axios from 'axios';
3
+ import { isBrowser, isNode } from 'browser-or-node';
4
+
5
+
6
+ ///////////////////////////////////////////////////////////////////////////////
7
+
8
+ /**
9
+ * @classdesc A static service that provides useful helper functions and tools for other Qik services
10
+ * @alias utils
11
+ * @class
12
+ * @hideconstructor
13
+ */
14
+ var QikUtils = {};
15
+
16
+ ///////////////////////////////////////////////////////////////////////////////
17
+
18
+ /**
19
+ * A helpful function that can take a keyed object literal and map it to url query string parameters
20
+ * @alias utils.mapParameters
21
+ * @param {Object} parameters The object you want to transalte
22
+ * @return {String} The query string
23
+ * @example
24
+ * //Returns &this=that&hello=world
25
+ * qik.utils.mapParameters({"this":"that", "hello":"world"})
26
+ */
27
+ QikUtils.mapParameters = function(parameters) {
28
+ return _.chain(parameters)
29
+ .reduce(function(set, v, k) {
30
+ if (v === undefined || v === null || v === false) {
31
+ return set;
32
+ }
33
+
34
+ if (_.isArray(v)) {
35
+ _.each(v, function(value) {
36
+ set.push(`${k}=${encodeURIComponent(value)}`);
37
+ })
38
+
39
+ } else {
40
+ set.push(encodeURIComponent(k) + '=' + encodeURIComponent(v));
41
+ }
42
+
43
+ return set;
44
+ }, [])
45
+ .compact()
46
+ .value()
47
+ .join('&');
48
+ }
49
+
50
+ ///////////////////////////////////////////////////////////////////////////////
51
+
52
+ /**
53
+ * A function that will take an integer and a currency string and return a formatted numeric amount rounded to 2 decimal places
54
+ * @alias utils.formatCurrency
55
+ * @param {Integer} value The amount in cents
56
+ * @param {String} currency The currency to format
57
+ * @return {String} The formatted value
58
+ * @example
59
+ *
60
+ * //Returns £10.00
61
+ * qik.utils.formatCurrency(1000, 'gbp');
62
+ *
63
+ * //Returns $10.00
64
+ * qik.utils.formatCurrency(1000, 'usd');
65
+ *
66
+ */
67
+ QikUtils.formatCurrency = function(value, currency) {
68
+
69
+ if (!value || isNaN(value)) {
70
+ value = 0;
71
+ }
72
+
73
+ var currencyPrefix = QikUtils.currencySymbol(currency);
74
+ return `${currencyPrefix}${parseFloat(parseInt(value) / 100).toFixed(2)}`;
75
+
76
+ }
77
+
78
+
79
+ /**
80
+ * A function that will take a currency string and return the symbol
81
+ * @alias utils.currencySymbol
82
+ * @param {String} currency The currency
83
+ * @return {String} The symbol
84
+ * @example
85
+ *
86
+ * //Returns £
87
+ * qik.utils.currencySymbol('gbp');
88
+ *
89
+ * //Returns $
90
+ * qik.utils.currencySymbol('usd');
91
+ *
92
+ */
93
+ QikUtils.currencySymbol = function(currency) {
94
+ //Ensure lowercase currency
95
+ currency = String(currency).toLowerCase();
96
+
97
+ switch (String(currency).toLowerCase()) {
98
+ case 'gbp':
99
+ return '£';
100
+ break;
101
+ case 'eur':
102
+ return '€';
103
+ break;
104
+ default:
105
+ return '$';
106
+ break;
107
+ }
108
+ }
109
+
110
+
111
+
112
+ QikUtils.getAvailableCurrencies = function(defaultCountryCode) {
113
+
114
+
115
+ var array = [];
116
+
117
+ array.push({
118
+ name: `USD (${QikUtils.currencySymbol("usd")})`,
119
+ value: "usd",
120
+ countryCode: { 'US': true },
121
+ });
122
+
123
+ array.push({
124
+ name: `GBP (${QikUtils.currencySymbol("gbp")})`,
125
+ value: "gbp",
126
+ countryCode: { 'GB': true, 'UK': true },
127
+ });
128
+
129
+ array.push({
130
+ name: `CAD (${QikUtils.currencySymbol("cad")})`,
131
+ value: "cad",
132
+ countryCode: { 'CA': true },
133
+ });
134
+
135
+ array.push({
136
+ name: `AUD (${QikUtils.currencySymbol("aud")})`,
137
+ value: "aud",
138
+ countryCode: { 'AU': true },
139
+ });
140
+
141
+
142
+ array.push({
143
+ name: `NZD (${QikUtils.currencySymbol("nzd")})`,
144
+ value: "nzd",
145
+ countryCode: { 'NZ': true },
146
+ });
147
+
148
+ array.push({
149
+ name: `SGD (${QikUtils.currencySymbol("sgd")})`,
150
+ value: "sgd",
151
+ countryCode: { 'SG': true },
152
+ });
153
+
154
+
155
+ if (defaultCountryCode) {
156
+
157
+ var findMatch = array.findIndex(function(currency) {
158
+ return currency.countryCode[defaultCountryCode];
159
+ })
160
+
161
+ const moveArrayItem = (array, fromIndex, toIndex) => {
162
+ const arr = [...array];
163
+ arr.splice(toIndex, 0, ...arr.splice(fromIndex, 1));
164
+ return arr;
165
+ }
166
+
167
+ if (findMatch != -1) {
168
+ array = moveArrayItem(array, findMatch, 0)
169
+ }
170
+ }
171
+
172
+ return array;
173
+ }
174
+
175
+ ///////////////////////////////////////////////////////////////////////////////
176
+
177
+ /**
178
+ * A helpful function for creating a fast hash object that can be used for more efficient loops
179
+ * @alias utils.hash
180
+ * @param {Array} array The array to reduce
181
+ * @param {String} key The key or path to the property to group by
182
+ * @return {Object} A hash object literal
183
+ * @example
184
+ * //Returns {something:[{title:'test', definition:'something'}]}
185
+ * qik.utils.mapReduce([{title:'test', definition:'something'}], 'definition');
186
+ *
187
+ */
188
+ QikUtils.hash = function(array, key) {
189
+ if (!Array.isArray(array)) {
190
+ array = [];
191
+ }
192
+ return array.reduce(function(set, item) {
193
+ var key = _.get(item, key);
194
+ set[key] = item;
195
+ return set;
196
+ }, {});
197
+ }
198
+
199
+
200
+
201
+ ///////////////////////////////////////////////////////////////////////////////
202
+
203
+ /**
204
+ * A helpful function that can create a globally unique id
205
+ * @alias utils.guid
206
+ * @return {String} The new guid
207
+ * @example
208
+ * //Returns 20354d7a-e4fe-47af-8ff6-187bca92f3f9
209
+ * qik.utils.guid()
210
+ */
211
+ QikUtils.guid = function() {
212
+ var u = (new Date()).getTime().toString(16) +
213
+ Math.random().toString(16).substring(2) + "0".repeat(16);
214
+ var guid = u.substr(0, 8) + '-' + u.substr(8, 4) + '-4000-8' +
215
+ u.substr(12, 3) + '-' + u.substr(15, 12);
216
+
217
+ return guid;
218
+ }
219
+
220
+ //////////////////////////////////////////////////
221
+
222
+ /**
223
+ * A helpful function that can return a subset of an array compared to specified criteria, This is usually used
224
+ * to evaluate expressions on Qik forms
225
+ * @alias utils.extractFromArray
226
+ * @param {Array} array The array you want to filter
227
+ * @param {String} path The path to the property you want to compare on each item in the array
228
+ * @param {Boolean} sum Whether to sum the resulting values together as a number
229
+ * @param {Boolean} flatten Whether to flatten nested arrays
230
+ * @param {Boolean} unique Whether to only return unique values
231
+ * @param {Boolean} exclude Whether to exclude null or undefined values
232
+ * @param {Object} options Pass through extra options for how to extract the values
233
+ * @return {Array} An array of all values retrieved from the array, unless options specifies otherwise
234
+ * @example
235
+ * //Returns [26, 19] as all the values
236
+ * qik.utils.extractFromArray([{name:'Jerry', age:26}, {name:'Susan', age:19}], 'age');
237
+ *
238
+ * //Returns 45
239
+ * qik.utils.extractFromArray([{name:'Jerry', age:26}, {name:'Susan', age:19}], 'age', {sum:true});
240
+ *
241
+ */
242
+ QikUtils.extractFromArray = function(array, key, sum, flatten, unique, exclude, options) {
243
+
244
+ if (!options) {
245
+ options = {}
246
+ }
247
+
248
+ if (sum) {
249
+ options.sum = sum;
250
+ }
251
+
252
+ if (flatten) {
253
+ options.flatten = true;
254
+ }
255
+
256
+ if (unique) {
257
+ options.unique = true;
258
+ }
259
+
260
+ if (exclude) {
261
+ options.excludeNull = true;
262
+ }
263
+
264
+ /////////////////
265
+
266
+ //Filter the array options by a certain value and operator
267
+ var matches = _.reduce(array, function(set, entry) {
268
+ //Get the value from the object
269
+ var retrievedValue = _.get(entry, key);
270
+
271
+ ///////////////////////
272
+
273
+ var isNull = (!retrievedValue && (retrievedValue !== false && retrievedValue !== 0));
274
+ if (options.excludeNull && isNull) {
275
+ return set;
276
+ }
277
+
278
+ set.push(retrievedValue);
279
+ return set;
280
+ }, [])
281
+
282
+ /////////////////
283
+
284
+ if (options.flatten) {
285
+ matches = _.flatten(matches);
286
+ }
287
+
288
+ /////////////////
289
+
290
+ if (options.unique) {
291
+ matches = _.uniq(matches);
292
+ }
293
+
294
+ /////////////////
295
+
296
+ if (options.sum) {
297
+ matches = matches.reduce(function(a, b) {
298
+ return a + b;
299
+ }, 0);
300
+ }
301
+
302
+
303
+
304
+ /////////////////
305
+
306
+ return matches;
307
+ }
308
+
309
+
310
+ //////////////////////////////////////////////////////
311
+
312
+ /**
313
+ * A helpful function that can return a subset of an array compared to specified criteria, This is usually used
314
+ * to evaluate expressions on Qik forms
315
+ * @alias utils.matchInArray
316
+ * @param {Array} array The array you want to filter
317
+ * @param {String} path The path to the property you want to compare on each item in the array
318
+ * @param {String} value The value to compare with
319
+ * @param {String} operator Can be Possible options are ('>', '<', '>=', '<=', 'in', '==') Defaults to '==' (Is equal to)
320
+ * @return {Array} An array that contains all items that matched
321
+ * @example
322
+ * //Returns [{name:'Jerry', age:26}] as that is only item in the array that matches the criteria
323
+ * qik.utils.matchInArray([{name:'Jerry', age:26}, {name:'Susan', age:19}], 'age', 26, '>=');
324
+ *
325
+ */
326
+ QikUtils.matchInArray = function(array, key, value, operator) {
327
+
328
+ //Filter the array options by a certain value and operator
329
+ var matches = _.filter(array, function(entry) {
330
+ //Get the value from the object
331
+ var retrievedValue = _.get(entry, key);
332
+ var isMatch;
333
+
334
+ ///////////////////////
335
+
336
+ //Check how to operate
337
+ switch (operator) {
338
+ case '>':
339
+ isMatch = (retrievedValue > value);
340
+ break;
341
+ case '<':
342
+ isMatch = (retrievedValue < value);
343
+ break;
344
+ case '>=':
345
+ isMatch = (retrievedValue >= value);
346
+ break;
347
+ case '<=':
348
+ isMatch = (retrievedValue <= value);
349
+ break;
350
+ case 'in':
351
+ isMatch = _.includes(retrievedValue, value);
352
+ break;
353
+ default:
354
+ //operator is strict equals
355
+ if (value === undefined) {
356
+ isMatch = retrievedValue;
357
+ } else {
358
+ isMatch = (retrievedValue == value);
359
+ }
360
+ break;
361
+ }
362
+
363
+ ///////////////////////
364
+
365
+ // console.log('MATCH IN ARRAY', isMatch, key, value, retrievedValue,operator)
366
+ return isMatch;
367
+ })
368
+
369
+ return matches;
370
+ }
371
+
372
+ ///////////////////////////////////////////////////////////////////////////////
373
+
374
+ /**
375
+ * A helpful class that can take an array of values and return them as a comma seperated
376
+ * string, If the values are objects, then a property to use as the string representation can be specified
377
+ * @alias utils.comma
378
+ * @param {Array} array The array of values to translate
379
+ * @param {String} path An optional property key to use for each value
380
+ * @return {String} The resulting comma seperated string
381
+ * @example
382
+ * //Returns 'cat, dog, bird'
383
+ * qik.utils.comma(['cat', 'dog', 'bird']);
384
+ *
385
+ * //Returns 'cat, dog, bird'
386
+ * qik.utils.comma([{title:'cat'}, {title:'dog'}, {title:'bird'}], 'title');
387
+ */
388
+ QikUtils.comma = function(array, path, limit) {
389
+
390
+ if (limit) {
391
+ array = array.slice(0, limit);
392
+ }
393
+
394
+ return _.chain(array)
395
+ .compact()
396
+ .map(function(item) {
397
+ if (path && path.length) {
398
+ return _.get(item, path);
399
+ }
400
+
401
+ return item;
402
+ })
403
+ .value()
404
+ .join(', ');
405
+
406
+ }
407
+
408
+ ///////////////////////////////////////////////////////////////////////////////
409
+
410
+ //Helper function to get an id of an object
411
+
412
+ /**
413
+ * Returns a specified _id for an object
414
+ * @alias utils.id
415
+ * @param {Object} input An object that is or has an _id property
416
+ * @param {Boolean} asObjectID Whether to convert to a Mongo ObjectId
417
+ * @return {String} Will return either a string or a Mongo ObjectId
418
+ *
419
+ * @example
420
+ *
421
+ * //Returns '5cb3d8b3a2219970e6f86927'
422
+ * qik.utils.id('5cb3d8b3a2219970e6f86927')
423
+ *
424
+ * //Returns true
425
+ * typeof QikUtils.id({_id:'5cb3d8b3a2219970e6f86927', title, ...}) == 'string';
426
+
427
+ * //Returns true
428
+ * typeof QikUtils.id({_id:'5cb3d8b3a2219970e6f86927'}, true) == 'object';
429
+ */
430
+ QikUtils.id = function(source) {
431
+
432
+ if (!source) {
433
+ return;
434
+ }
435
+
436
+ /////////////////////////////////
437
+
438
+ var output;
439
+
440
+ if (source._id) {
441
+ output = String(source._id);
442
+ } else {
443
+ output = String(source);
444
+ }
445
+
446
+
447
+ var isValid = service.isValidID(output);
448
+ if (!isValid) {
449
+ return;
450
+ }
451
+
452
+ return output;
453
+ }
454
+
455
+ ///////////////////////////////////////////////////////////////////////////////
456
+
457
+ /**
458
+ * Cleans and maps an array of objects to an array of IDs
459
+ * @alias utils.ids
460
+ * @param {Array} array An array of objects or object ids
461
+ * @param {Boolean} asObjectID Whether or not to map the ids as Mongo ObjectIds
462
+ * @return {Array} An array of Ids
463
+ *
464
+ * @example
465
+ * //Returns ['5cb3d8b3a2219970e6f86927', '5cb3d8b3a2219970e6f86927', '5cb3d8b3a2219970e6f86927']
466
+ * qik.utils.ids([{_id:'5cb3d8b3a2219970e6f86927'}, {_id:'5cb3d8b3a2219970e6f86927'}, null, '5cb3d8b3a2219970e6f86927'])
467
+ */
468
+ QikUtils.ids = function(array) {
469
+ return _.chain(array)
470
+ .reduce(function(set, entry) {
471
+
472
+ if (!entry) {
473
+ return set;
474
+ }
475
+
476
+ var cleaned = service.id(entry)
477
+
478
+ if (cleaned) {
479
+ set[cleaned] = 1;
480
+ }
481
+
482
+ return set;
483
+ }, {})
484
+ .keys()
485
+ .value();
486
+ }
487
+
488
+ ///////////////////////////////////////////////////////////////////////////////
489
+
490
+ QikUtils.isValidID = function(input) {
491
+ var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$")
492
+ return checkForHexRegExp.test(String(input));
493
+
494
+ }
495
+
496
+ ///////////////////////////////////////////////////////////////////////////////
497
+
498
+ /**
499
+ * Helper function for retrieving a human readable error message from server error response objects
500
+ * @alias utils.errorMessage
501
+ * @param {Object} error The error object to translate
502
+ * @return {String} The resulting human readable error message
503
+ */
504
+ QikUtils.errorMessage = function(err) {
505
+
506
+
507
+ if (_.isArray(err)) {
508
+ err = _.first(err);
509
+ }
510
+
511
+ ////////////////////////////////////
512
+
513
+ var candidates = [
514
+ 'response.data.message',
515
+ 'response.data',
516
+ 'message',
517
+ ]
518
+
519
+ ////////////////////////////////////
520
+
521
+ var message = _.chain(candidates)
522
+ .map(function(path) {
523
+ return _.get(err, path);
524
+ })
525
+ .compact()
526
+ .first()
527
+ .value();
528
+
529
+ ////////////////////////////////////
530
+
531
+ if (Array.isArray(message)) {
532
+ message = message[0];
533
+ }
534
+
535
+ ////////////////////////////////////
536
+
537
+ if (!message || !message.length) {
538
+ return String(err);
539
+ }
540
+
541
+ ////////////////////////////////////
542
+
543
+ return message;
544
+ }
545
+
546
+
547
+ /////////////////////////////////////////////
548
+ /////////////////////////////////////////////
549
+
550
+
551
+
552
+ ////////////////////////////////////
553
+ ////////////////////////////////////
554
+ ////////////////////////////////////
555
+
556
+ /**
557
+ * Helper function for cleaning strings to use as database ids
558
+ * @alias utils.machineName
559
+ * @param {String} string The string to clean eg. (Awesome Event!)
560
+ * @return {String} A cleaned and formatted string eg. (awesomeEvent)
561
+ */
562
+
563
+ QikUtils.machineName = function(string) {
564
+
565
+ if (!string || !string.length) {
566
+ return;
567
+ }
568
+
569
+ var regexp = /[^a-zA-Z0-9-_]+/g;
570
+ return string.replace(regexp, '');
571
+ }
572
+
573
+ /////////////////////////////////////////////
574
+ /////////////////////////////////////////////
575
+ /////////////////////////////////////////////
576
+
577
+
578
+ export default QikUtils;
579
+
580
+
581
+ /////////////////////////////////////////////
582
+
583
+ //Export the event dispatcher
584
+ export function EventDispatcher() {
585
+
586
+ var listeners = {};
587
+
588
+ /////////////////////////////////////////////
589
+
590
+ var dispatcher = {}
591
+
592
+ /////////////////////////////////////////////
593
+
594
+ //Remove all listeners
595
+ dispatcher.removeAllListeners = function() {
596
+ listeners = {};
597
+ }
598
+
599
+ /////////////////////////////////////////////
600
+
601
+ dispatcher.dispatch = function(event, details) {
602
+
603
+ if (listeners[event]) {
604
+
605
+ // console.log('Listeners', event, listeners[event]);
606
+ //For each listener
607
+ listeners[event].forEach(function(callback) {
608
+ //Fire the callback
609
+ // console.log('Fire listener', event, details);
610
+ return callback(details);
611
+ });
612
+ }
613
+ }
614
+
615
+ /////////////////////////////////////////////
616
+
617
+ dispatcher.addEventListener = function(event, callback) {
618
+
619
+ if (!listeners[event]) {
620
+ listeners[event] = [];
621
+ }
622
+
623
+ if (listeners[event].indexOf(callback) == -1) {
624
+ //Add to the listeners
625
+ listeners[event].push(callback)
626
+ } else {
627
+ //Already listening
628
+ }
629
+ }
630
+
631
+ /////////////////////////////////////////////
632
+
633
+ dispatcher.removeEventListener = function(event, callback) {
634
+
635
+ if (!listeners[event]) {
636
+ listeners[event] = [];
637
+ }
638
+
639
+ //Get the index of the listener
640
+ var index = listeners[event].indexOf(callback);
641
+
642
+ if (index != -1) {
643
+ //Remove from the listeners
644
+ listeners[event].splice(index, 1);
645
+ }
646
+ }
647
+
648
+
649
+ /////////////////////////////////////////////
650
+
651
+ //Wrap the event listener functionality
652
+ dispatcher.bootstrap = function(service) {
653
+ if (!service) {
654
+ // console.log('No service to bootstrap to')
655
+ return;
656
+ }
657
+
658
+ service.dispatch = dispatcher.dispatch;
659
+ service.addEventListener = dispatcher.addEventListener;
660
+ service.removeEventListener = dispatcher.removeEventListener;
661
+ service.removeAllListeners = dispatcher.removeAllListeners;
662
+ }
663
+
664
+ /////////////////////////////////////////////
665
+
666
+ return dispatcher;
667
+ }
package/src/index.js ADDED
@@ -0,0 +1,13 @@
1
+
2
+
3
+ var versionName = `qik 0.1.0`;
4
+ console.log(versionName)
5
+
6
+ ////////////////////////////////////////////
7
+
8
+ //Import the pieces we need
9
+ import QikCore from './api/qik.core.js';
10
+
11
+ ////////////////////////////////////////////
12
+
13
+ export default QikCore;