This repository has been archived by the owner on Nov 2, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 13
/
es5.js
937 lines (891 loc) · 27.9 KB
/
es5.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
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
/*!
* grappling-hook
* https://github.com/keystonejs/grappling-hook
*
* Copyright 2015-2016 Keystone.js
* Released under the MIT license
*
*/
'use strict';
/**
* Middleware are callbacks that will be executed when a hook is called. The type of middleware is determined through the parameters it declares.
* @example
* function(){
* //synchronous execution
* }
* @example
* function(){
* //create promise, i.e. further execution is halted until the promise is resolved.
* return promise;
* }
* @example
* function(next){
* //asynchronous execution, i.e. further execution is halted until `next` is called.
* setTimeout(next, 1000);
* }
* @example
* function(next, done){
* //asynchronous execution, i.e. further execution is halted until `next` is called.
* setTimeout(next, 1000);
* //full middleware queue handling is halted until `done` is called.
* setTimeout(done, 2000);
* }
* @callback middleware
* @param {...*} [parameters] - parameters passed to the hook
* @param {function} [next] - pass control to the next middleware
* @param {function} [done] - mark parallel middleware to have completed
*/
/**
* @typedef {Object} options
* @property {Boolean} [strict=true] - Will disallow subscribing to middleware bar the explicitly registered ones.
* @property {Object} [qualifiers]
* @property {String} [qualifiers.pre='pre'] - Declares the 'pre' qualifier
* @property {String} [qualifiers.post='post'] - Declares the 'post' qualifier
* @property {Function} [createThenable=undefined] - Set a Promise A+ compliant factory function for creating promises.
* @example
* //creates a GrapplingHook instance with `before` and `after` hooking
* var instance = grappling.create({
* qualifiers: {
* pre: 'before',
* post: 'after'
* }
* });
* instance.before('save', console.log);
* @example
* //creates a GrapplingHook instance with a promise factory
* var P = require('bluebird');
* var instance = grappling.create({
* createThenable: function(fn){
* return new P(fn);
* }
* });
* instance.allowHooks('save');
* instance.pre('save', console.log);
* instance.callThenableHook('pre:save', 'Here we go!').then(function(){
* console.log('And finish!');
* });
* //outputs:
* //Here we go!
* //And finish!
*/
/**
* The GrapplingHook documentation uses the term "thenable" instead of "promise", since what we need here is not _necessarily_ a promise, but a thenable, as defined in the <a href="https://promisesaplus.com/">Promises A+ spec</a>.
* Thenable middleware for instance can be _any_ object that has a `then` function.
* Strictly speaking the only instance where we adhere to the full Promises A+ definition of a promise is in {@link options}.createThenable.
* For reasons of clarity, uniformity and symmetry we chose `createThenable`, although strictly speaking it should've been `createPromise`.
* Most people would find it confusing if part of the API uses 'thenable' and another part 'promise'.
* @typedef {Object} thenable
* @property {Function} then - see <a href="https://promisesaplus.com/">Promises A+ spec</a>
* @see {@link options}.createThenable
* @see {@link module:grappling-hook.isThenable isThenable}
*/
var _ = require('lodash');
var async = {};
/*!
*=====================================
* Parts copied from/based on *
*=====================================
*
* async
* https://github.com/caolan/async
*
* Copyright 2010-2014 Caolan McMahon
* Released under the MIT license
*/
/**
*
* @param {{}} tasks - MUST BE OBJECT
* @param {function} callback
*/
async.series = function (tasks, callback) {
callback = callback || _.noop;
var results = {};
async.eachSeries(_.keys(tasks), function (k, callback) {
tasks[k](function (err) {
//optimised to avoid arguments leakage
var args = new Array(arguments.length);
for (var i = 1; i < args.length; i++) {
args[i] = arguments[i];
}
if (args.length <= 1) {
args = args[0];
}
results[k] = args;
callback(err);
});
}, function (err) {
callback(err, results);
});
};
/**
*
* @param {[]} arr
* @param {function} iterator
* @param {function} callback
* @returns {*}
*/
async.eachSeries = function (arr, iterator, callback) {
callback = callback || _.noop;
if (!arr.length) {
return callback();
}
var completed = 0;
var iterate = function iterate() {
iterator(arr[completed], function (err) {
if (err) {
callback(err);
callback = _.noop;
} else {
completed += 1;
if (completed >= arr.length) {
callback();
} else {
iterate();
}
}
});
};
iterate();
};
/*!
*=====================================
*/
var presets = {};
function parseHook(hook) {
var parsed = hook ? hook.split(':') : [];
var n = parsed.length;
return {
type: parsed[n - 2],
name: parsed[n - 1]
};
}
/**
*
* @param instance - grappling-hook instance
* @param hook - hook
* @param args
* @private
*/
function addMiddleware(instance, hook, args) {
var fns = _.flatten(args);
var cache = instance.__grappling;
var mw = [];
if (!cache.middleware[hook]) {
if (cache.opts.strict) throw new Error('Hooks for ' + hook + ' are not supported.');
} else {
mw = cache.middleware[hook];
}
cache.middleware[hook] = mw.concat(fns);
}
function attachQualifier(instance, qualifier) {
/**
* Registers `middleware` to be executed _before_ `hook`.
* This is a dynamically added method, that may not be present if otherwise configured in {@link options}.qualifiers.
* @method pre
* @instance
* @memberof GrapplingHook
* @param {string} hook - hook name, e.g. `'save'`
* @param {(...middleware|middleware[])} [middleware] - middleware to register
* @returns {GrapplingHook|thenable} the {@link GrapplingHook} instance itself, or a {@link thenable} if no middleware was provided.
* @example
* instance.pre('save', function(){
* console.log('before saving');
* });
* @see {@link GrapplingHook#post} for registering middleware functions to `post` hooks.
*/
/**
* Registers `middleware` to be executed _after_ `hook`.
* This is a dynamically added method, that may not be present if otherwise configured in {@link options}.qualifiers.
* @method post
* @instance
* @memberof GrapplingHook
* @param {string} hook - hook name, e.g. `'save'`
* @param {(...middleware|middleware[])} [middleware] - middleware to register
* @returns {GrapplingHook|thenable} the {@link GrapplingHook} instance itself, or a {@link thenable} if no middleware was provided.
* @example
* instance.post('save', function(){
* console.log('after saving');
* });
* @see {@link GrapplingHook#pre} for registering middleware functions to `post` hooks.
*/
instance[qualifier] = function () {
var fns = _.toArray(arguments);
var hookName = fns.shift();
var output = void 0;
if (fns.length) {
//old skool way with callbacks
output = this;
} else {
output = this.__grappling.opts.createThenable(function (resolve) {
fns = [resolve];
});
}
addMiddleware(this, qualifier + ':' + hookName, fns);
return output;
};
}
function init(name, opts) {
if (arguments.length === 1 && _.isObject(name)) {
opts = name;
name = undefined;
}
var presets = void 0;
if (name) {
presets = module.exports.get(name);
}
this.__grappling = {
middleware: {},
opts: _.defaults({}, opts, presets, {
strict: true,
qualifiers: {
pre: 'pre',
post: 'post'
},
createThenable: function createThenable() {
throw new Error('Instance not set up for thenable creation, please set `opts.createThenable`');
}
})
};
var q = this.__grappling.opts.qualifiers;
attachQualifier(this, q.pre);
attachQualifier(this, q.post);
}
/*
based on code from Isaac Schlueter's blog post:
http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony
*/
function dezalgofy(fn, done) {
var isSync = true;
fn(safeDone); //eslint-disable-line no-use-before-define
isSync = false;
function safeDone() {
var args = arguments;
if (isSync) {
process.nextTick(function () {
done.apply(null, args);
});
} else {
done.apply(null, args);
}
}
}
function iterateAsyncMiddleware(context, middleware, args, done) {
done = done || function (err) {
/* istanbul ignore next: untestable */
if (err) {
throw err;
}
};
var asyncFinished = false;
var waiting = [];
var wait = function wait(callback) {
waiting.push(callback);
return function (err) {
waiting.splice(waiting.indexOf(callback), 1);
if (asyncFinished !== done) {
if (err || asyncFinished && !waiting.length) {
done(err);
}
}
};
};
async.eachSeries(middleware, function (callback, next) {
var d = callback.length - args.length;
switch (d) {
case 1:
//async series
callback.apply(context, args.concat(next));
break;
case 2:
//async parallel
callback.apply(context, args.concat(next, wait(callback)));
break;
default:
//synced
var err = void 0;
var result = void 0;
try {
result = callback.apply(context, args);
} catch (e) {
err = e;
}
if (!err && module.exports.isThenable(result)) {
//thenable
result.then(function () {
next();
}, next);
} else {
//synced
next(err);
}
}
}, function (err) {
asyncFinished = err ? done : true;
if (err || !waiting.length) {
done(err);
}
});
}
function iterateSyncMiddleware(context, middleware, args) {
middleware.forEach(function (callback) {
callback.apply(context, args);
});
}
/**
*
* @param hookObj
* @returns {*}
* @private
*/
function qualifyHook(hookObj) {
if (!hookObj.name || !hookObj.type) {
throw new Error('Only qualified hooks are allowed, e.g. "pre:save", not "save"');
}
return hookObj;
}
function createHooks(instance, config) {
var q = instance.__grappling.opts.qualifiers;
_.forEach(config, function (fn, hook) {
var hookObj = parseHook(hook);
instance[hookObj.name] = function () {
var args = _.toArray(arguments);
var done = args.pop();
if (!_.isFunction(done)) {
throw new Error('Async methods should receive a callback as a final parameter');
}
var results = void 0;
dezalgofy(function (safeDone) {
async.series([function (next) {
iterateAsyncMiddleware(instance, instance.getMiddleware(q.pre + ':' + hookObj.name), args, next);
}, function (next) {
fn.apply(instance, args.concat(function () {
var args = _.toArray(arguments);
var err = args.shift();
results = args;
next(err);
}));
}, function (next) {
iterateAsyncMiddleware(instance, instance.getMiddleware(q.post + ':' + hookObj.name), args, next);
}], function (err) {
safeDone.apply(null, [err].concat(results));
});
}, done);
};
});
}
function createSyncHooks(instance, config) {
var q = instance.__grappling.opts.qualifiers;
_.forEach(config, function (fn, hook) {
var hookObj = parseHook(hook);
instance[hookObj.name] = function () {
var args = _.toArray(arguments);
var middleware = instance.getMiddleware(q.pre + ':' + hookObj.name);
var result = void 0;
middleware.push(function () {
result = fn.apply(instance, args);
});
middleware = middleware.concat(instance.getMiddleware(q.post + ':' + hookObj.name));
iterateSyncMiddleware(instance, middleware, args);
return result;
};
});
}
function createThenableHooks(instance, config) {
var opts = instance.__grappling.opts;
var q = instance.__grappling.opts.qualifiers;
_.forEach(config, function (fn, hook) {
var hookObj = parseHook(hook);
instance[hookObj.name] = function () {
var args = _.toArray(arguments);
var deferred = {};
var thenable = opts.createThenable(function (resolve, reject) {
deferred.resolve = resolve;
deferred.reject = reject;
});
async.series([function (next) {
iterateAsyncMiddleware(instance, instance.getMiddleware(q.pre + ':' + hookObj.name), args, next);
}, function (next) {
fn.apply(instance, args).then(function (result) {
deferred.result = result;
next();
}, next);
}, function (next) {
iterateAsyncMiddleware(instance, instance.getMiddleware(q.post + ':' + hookObj.name), args, next);
}], function (err) {
if (err) {
return deferred.reject(err);
}
return deferred.resolve(deferred.result);
});
return thenable;
};
});
}
function _addHooks(instance, args) {
var config = {};
_.forEach(args, function (mixed) {
if (_.isString(mixed)) {
var hookObj = parseHook(mixed);
var fn = instance[hookObj.name];
if (!fn) throw new Error('Cannot add hooks to undeclared method:"' + hookObj.name + '"'); //non-existing method
config[mixed] = fn;
} else if (_.isObject(mixed)) {
_.defaults(config, mixed);
} else {
throw new Error('`addHooks` expects (arrays of) Strings or Objects');
}
});
instance.allowHooks(_.keys(config));
return config;
}
function parseCallHookParams(instance, args) {
return {
context: _.isString(args[0]) ? instance : args.shift(),
hook: args.shift(),
args: args
};
}
/**
* Grappling hook
* @alias GrapplingHook
* @mixin
*/
var methods = {
/**
* Adds middleware to a qualified hook.
* Convenience method which allows you to add middleware dynamically more easily.
*
* @param {String} qualifiedHook - qualified hook e.g. `pre:save`
* @param {(...middleware|middleware[])} middleware - middleware to call
* @instance
* @public
* @example
* instance.hook('pre:save', function(next) {
* console.log('before saving');
* next();
* }
* @returns {GrapplingHook|thenable}
*/
hook: function hook() {
var fns = _.toArray(arguments);
var hook = fns.shift();
var output = void 0;
qualifyHook(parseHook(hook));
if (fns.length) {
output = this;
} else {
output = this.__grappling.opts.createThenable(function (resolve) {
fns = [resolve];
});
}
addMiddleware(this, hook, fns);
return output;
},
/**
* Removes {@link middleware} for `hook`
* @instance
* @example
* //removes `onPreSave` Function as a `pre:save` middleware
* instance.unhook('pre:save', onPreSave);
* @example
* //removes all middleware for `pre:save`
* instance.unhook('pre:save');
* @example
* //removes all middleware for `pre:save` and `post:save`
* instance.unhook('save');
* @example
* //removes ALL middleware
* instance.unhook();
* @param {String} [hook] - (qualified) hooks e.g. `pre:save` or `save`
* @param {(...middleware|middleware[])} [middleware] - function(s) to be removed
* @returns {GrapplingHook}
*/
unhook: function unhook() {
var fns = _.toArray(arguments);
var hook = fns.shift();
var hookObj = parseHook(hook);
var middleware = this.__grappling.middleware;
var q = this.__grappling.opts.qualifiers;
if (hookObj.type || fns.length) {
qualifyHook(hookObj);
if (middleware[hook]) {
middleware[hook] = fns.length ? _.without.apply(null, [middleware[hook]].concat(fns)) : [];
}
} else if (hookObj.name) {
/* istanbul ignore else: nothing _should_ happen */
if (middleware[q.pre + ':' + hookObj.name]) middleware[q.pre + ':' + hookObj.name] = [];
/* istanbul ignore else: nothing _should_ happen */
if (middleware[q.post + ':' + hookObj.name]) middleware[q.post + ':' + hookObj.name] = [];
} else {
_.forEach(middleware, function (callbacks, hook) {
middleware[hook] = [];
});
}
return this;
},
/**
* Determines whether registration of middleware to `qualifiedHook` is allowed. (Always returns `true` for lenient instances)
* @instance
* @param {String|String[]} qualifiedHook - qualified hook e.g. `pre:save`
* @returns {boolean}
*/
hookable: function hookable(qualifiedHook) {
var _this = this;
//eslint-disable-line no-unused-vars
if (!this.__grappling.opts.strict) {
return true;
}
var args = _.flatten(_.toArray(arguments));
return _.every(args, function (qualifiedHook) {
qualifyHook(parseHook(qualifiedHook));
return !!_this.__grappling.middleware[qualifiedHook];
});
},
/**
* Explicitly declare hooks
* @instance
* @param {(...string|string[])} hooks - (qualified) hooks e.g. `pre:save` or `save`
* @returns {GrapplingHook}
*/
allowHooks: function allowHooks() {
var _this2 = this;
var args = _.flatten(_.toArray(arguments));
var q = this.__grappling.opts.qualifiers;
_.forEach(args, function (hook) {
if (!_.isString(hook)) {
throw new Error('`allowHooks` expects (arrays of) Strings');
}
var hookObj = parseHook(hook);
var middleware = _this2.__grappling.middleware;
if (hookObj.type) {
if (hookObj.type !== q.pre && hookObj.type !== q.post) {
throw new Error('Only "' + q.pre + '" and "' + q.post + '" types are allowed, not "' + hookObj.type + '"');
}
middleware[hook] = middleware[hook] || [];
} else {
middleware[q.pre + ':' + hookObj.name] = middleware[q.pre + ':' + hookObj.name] || [];
middleware[q.post + ':' + hookObj.name] = middleware[q.post + ':' + hookObj.name] || [];
}
});
return this;
},
/**
* Wraps asynchronous methods/functions with `pre` and/or `post` hooks
* @instance
* @see {@link GrapplingHook#addSyncHooks} for wrapping synchronous methods
* @see {@link GrapplingHook#addThenableHooks} for wrapping thenable methods
* @example
* //wrap existing methods
* instance.addHooks('save', 'pre:remove');
* @example
* //add method and wrap it
* instance.addHooks({
* save: instance._upload,
* "pre:remove": function(){
* //...
* }
* });
* @param {(...String|String[]|...Object|Object[])} methods - method(s) that need(s) to emit `pre` and `post` events
* @returns {GrapplingHook}
*/
addHooks: function addHooks() {
var config = _addHooks(this, _.flatten(_.toArray(arguments)));
createHooks(this, config);
return this;
},
/**
* Wraps synchronous methods/functions with `pre` and/or `post` hooks
* @since 2.4.0
* @instance
* @see {@link GrapplingHook#addHooks} for wrapping asynchronous methods
* @see {@link GrapplingHook#addThenableHooks} for wrapping thenable methods
* @param {(...String|String[]|...Object|Object[])} methods - method(s) that need(s) to emit `pre` and `post` events
* @returns {GrapplingHook}
*/
addSyncHooks: function addSyncHooks() {
var config = _addHooks(this, _.flatten(_.toArray(arguments)));
createSyncHooks(this, config);
return this;
},
/**
* Wraps thenable methods/functions with `pre` and/or `post` hooks
* @since 3.0.0
* @instance
* @see {@link GrapplingHook#addHooks} for wrapping asynchronous methods
* @see {@link GrapplingHook#addSyncHooks} for wrapping synchronous methods
* @param {(...String|String[]|...Object|Object[])} methods - method(s) that need(s) to emit `pre` and `post` events
* @returns {GrapplingHook}
*/
addThenableHooks: function addThenableHooks() {
var config = _addHooks(this, _.flatten(_.toArray(arguments)));
createThenableHooks(this, config);
return this;
},
/**
* Calls all middleware subscribed to the asynchronous `qualifiedHook` and passes remaining parameters to them
* @instance
* @see {@link GrapplingHook#callSyncHook} for calling synchronous hooks
* @see {@link GrapplingHook#callThenableHook} for calling thenable hooks
* @param {*} [context] - the context in which the middleware will be called
* @param {String} qualifiedHook - qualified hook e.g. `pre:save`
* @param {...*} [parameters] - any parameters you wish to pass to the middleware.
* @param {Function} [callback] - will be called when all middleware have finished
* @returns {GrapplingHook}
*/
callHook: function callHook() {
var _this3 = this;
//todo: decide whether we should enforce passing a callback
var i = arguments.length;
var args = [];
while (i--) {
args[i] = arguments[i];
}
var params = parseCallHookParams(this, args);
params.done = _.isFunction(params.args[params.args.length - 1]) ? params.args.pop() : null;
if (params.done) {
dezalgofy(function (safeDone) {
iterateAsyncMiddleware(params.context, _this3.getMiddleware(params.hook), params.args, safeDone);
}, params.done);
} else {
iterateAsyncMiddleware(params.context, this.getMiddleware(params.hook), params.args);
}
return this;
},
/**
* Calls all middleware subscribed to the synchronous `qualifiedHook` and passes remaining parameters to them
* @since 2.4.0
* @instance
* @see {@link GrapplingHook#callHook} for calling asynchronous hooks
* @see {@link GrapplingHook#callThenableHook} for calling thenable hooks
* @param {*} [context] - the context in which the middleware will be called
* @param {String} qualifiedHook - qualified hook e.g. `pre:save`
* @param {...*} [parameters] - any parameters you wish to pass to the middleware.
* @returns {GrapplingHook}
*/
callSyncHook: function callSyncHook() {
var i = arguments.length;
var args = [];
while (i--) {
args[i] = arguments[i];
}
var params = parseCallHookParams(this, args);
iterateSyncMiddleware(params.context, this.getMiddleware(params.hook), params.args);
return this;
},
/**
* Calls all middleware subscribed to the synchronous `qualifiedHook` and passes remaining parameters to them
* @since 3.0.0
* @instance
* @see {@link GrapplingHook#callHook} for calling asynchronous hooks
* @see {@link GrapplingHook#callSyncHook} for calling synchronous hooks
* @param {*} [context] - the context in which the middleware will be called
* @param {String} qualifiedHook - qualified hook e.g. `pre:save`
* @param {...*} [parameters] - any parameters you wish to pass to the middleware.
* @returns {thenable} - a thenable, as created with {@link options}.createThenable
*/
callThenableHook: function callThenableHook() {
var _this4 = this;
var params = parseCallHookParams(this, _.toArray(arguments));
var deferred = {};
var thenable = this.__grappling.opts.createThenable(function (resolve, reject) {
deferred.resolve = resolve;
deferred.reject = reject;
});
dezalgofy(function (safeDone) {
iterateAsyncMiddleware(params.context, _this4.getMiddleware(params.hook), params.args, safeDone);
}, function (err) {
if (err) {
return deferred.reject(err);
}
return deferred.resolve();
});
return thenable;
},
/**
* Retrieve all {@link middleware} registered to `qualifiedHook`
* @instance
* @param qualifiedHook - qualified hook, e.g. `pre:save`
* @returns {middleware[]}
*/
getMiddleware: function getMiddleware(qualifiedHook) {
qualifyHook(parseHook(qualifiedHook));
var middleware = this.__grappling.middleware[qualifiedHook];
if (middleware) {
return middleware.slice(0);
}
return [];
},
/**
* Determines whether any {@link middleware} is registered to `qualifiedHook`.
* @instance
* @param {string} qualifiedHook - qualified hook, e.g. `pre:save`
* @returns {boolean}
*/
hasMiddleware: function hasMiddleware(qualifiedHook) {
return this.getMiddleware(qualifiedHook).length > 0;
}
};
/**
* alias for {@link GrapplingHook#addHooks}.
* @since 3.0.0
* @name GrapplingHook#addAsyncHooks
* @instance
* @method
*/
methods.addAsyncHooks = methods.addHooks;
/**
* alias for {@link GrapplingHook#callHook}.
* @since 3.0.0
* @name GrapplingHook#callAsyncHook
* @instance
* @method
*/
methods.callAsyncHook = methods.callHook;
/**
* @module grappling-hook
* @type {exports|module.exports}
*/
module.exports = {
/**
* Mixes {@link GrapplingHook} methods into `instance`.
* @see {@link module:grappling-hook.attach attach} for attaching {@link GrapplingHook} methods to prototypes.
* @see {@link module:grappling-hook.create create} for creating {@link GrapplingHook} instances.
* @param {Object} instance
* @param {string} [presets] - presets name, see {@link module:grappling-hook.set set}
* @param {options} [opts] - {@link options}.
* @mixes GrapplingHook
* @returns {GrapplingHook}
* @example
* var grappling = require('grappling-hook');
* var instance = {
* };
* grappling.mixin(instance); // add grappling-hook functionality to an existing object
*/
mixin: function mixin(instance, presets, opts) {
//eslint-disable-line no-unused-vars
var args = new Array(arguments.length);
for (var i = 0; i < args.length; ++i) {
args[i] = arguments[i];
}
instance = args.shift();
init.apply(instance, args);
_.assignIn(instance, methods);
return instance;
},
/**
* Creates an object with {@link GrapplingHook} functionality.
* @see {@link module:grappling-hook.attach attach} for attaching {@link GrapplingHook} methods to prototypes.
* @see {@link module:grappling-hook.mixin mixin} for mixing {@link GrapplingHook} methods into instances.
* @param {string} [presets] - presets name, see {@link module:grappling-hook.set set}
* @param {options} [opts] - {@link options}.
* @returns {GrapplingHook}
* @example
* var grappling = require('grappling-hook');
* var instance = grappling.create(); // create an instance
*/
create: function create(presets, opts) {
//eslint-disable-line no-unused-vars
var args = new Array(arguments.length);
for (var i = 0; i < args.length; ++i) {
args[i] = arguments[i];
}
var instance = {};
init.apply(instance, args);
_.assignIn(instance, methods);
return instance;
},
/**
* Attaches {@link GrapplingHook} methods to `base`'s `prototype`.
* @see {@link module:grappling-hook.create create} for creating {@link GrapplingHook} instances.
* @see {@link module:grappling-hook.mixin mixin} for mixing {@link GrapplingHook} methods into instances.
* @param {Function} base
* @param {string} [presets] - presets name, see {@link module:grappling-hook.set set}
* @param {options} [opts] - {@link options}.
* @mixes GrapplingHook
* @returns {Function}
* @example
* var grappling = require('grappling-hook');
* var MyClass = function() {
* };
* MyClass.prototype.save = function(done) {
* console.log('save!');
* done();
* };
* grappling.attach(MyClass); // attach grappling-hook functionality to a 'class'
*/
attach: function attach(base, presets, opts) {
//eslint-disable-line no-unused-vars
var args = new Array(arguments.length);
for (var i = 0; i < args.length; ++i) {
args[i] = arguments[i];
}
args.shift();
var proto = base.prototype ? base.prototype : base;
_.forEach(methods, function (fn, methodName) {
proto[methodName] = function () {
var _this5 = this;
init.apply(this, args);
_.forEach(methods, function (fn, methodName) {
_this5[methodName] = fn.bind(_this5);
});
return fn.apply(this, arguments);
};
});
return base;
},
/**
* Store `presets` as `name`. Or set a specific value of a preset.
* (The use of namespaces is to avoid the very unlikely case of name conflicts with deduped node_modules)
* @since 3.0.0
* @see {@link module:grappling-hook.get get} for retrieving presets
* @param {string} name
* @param {options} options
* @returns {module:grappling-hook}
* @example
* //index.js - declaration
* var grappling = require('grappling-hook');
* grappling.set('grapplinghook:example', {
* strict: false,
* qualifiers: {
* pre: 'before',
* post: 'after'
* }
* });
*
* //foo.js - usage
* var instance = grappling.create('grapplinghook:example'); // uses options as cached for 'grapplinghook:example'
* @example
* grappling.set('grapplinghook:example.qualifiers.pre', 'first');
* grappling.set('grapplinghook:example.qualifiers.post', 'last');
*/
set: function set(name, options) {
_.set(presets, name, options);
return module.exports;
},
/**
* Retrieves presets stored as `name`. Or a specific value of a preset.
* (The use of namespaces is to avoid the very unlikely case of name conflicts with deduped node_modules)
* @since 3.0.0
* @see {@link module:grappling-hook.set set} for storing presets
* @param {string} name
* @returns {*}
* @example
* grappling.get('grapplinghook:example.qualifiers.pre');
* @example
* grappling.get('grapplinghook:example.qualifiers');
* @example
* grappling.get('grapplinghook:example');
*/
get: function get(name) {
return _.get(presets, name);
},
/**
* Determines whether `subject` is a {@link thenable}.
* @param {*} subject
* @returns {Boolean}
* @see {@link thenable}
*/
isThenable: function isThenable(subject) {
return subject && subject.then && _.isFunction(subject.then);
}
};