forked from vs-kurkin/Response
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathResponse.js
More file actions
1315 lines (1115 loc) · 28.7 KB
/
Copy pathResponse.js
File metadata and controls
1315 lines (1115 loc) · 28.7 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
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
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
/**
* @fileOverview Response.
*/
var EventEmitter = require('EventEmitter');
var toString = Object.prototype.toString;
var nativeEmit = EventEmitter.prototype.emit;
/**
*
* @param {String|Number} [state] Начальное состояние объекта.
* @returns {State}
* @constructor
* @extends EventEmitter
*/
function State(state) {
EventEmitter.call(this);
this.state = arguments.length ? state : this.state;
this.stateData = new Array(0);
return this;
}
/**
* Проверяет, я вляется ли объект экземпляром конструктора {@link State}.
* @param {Object} [object] Проверяемый объект.
* @returns {Boolean}
*/
State.isState = function (object) {
return object instanceof State;
};
/**
* Создает объект, который наследует от объекта {@link State}.
* @function
* @static
* @returns {Object}
* @example
* function Const () {}
*
* Const.prototype = State.create(Const);
*
* new Const() instanceof State; // true
* Const.prototype.constructor === Const; // true
*/
State.create = create;
State.prototype = create.call(EventEmitter, State);
/**
* Событие изменения состояния.
* @default 'changeState'
* @type {String}
*/
State.prototype.EVENT_CHANGE_STATE = 'changeState';
/**
* Текущее состояние объекта.
* @readonly
* @type {String}
*/
State.prototype.state = null;
/**
* Данные для обработчиков стостояния.
* @readonly
* @type {Array}
* @default []
*/
State.prototype.stateData = null;
/**
* Сбрасывает объект в первоначальное состояние.
* Так же удаляются все обработчики событий.
* @function
* @returns {State}
* @example
* new State('foo')
* .reset()
* .state; // null
*/
State.prototype.reset = function () {
return this.constructor();
};
/**
* Обнуляет все собственные свойства объекта.
* @returns {State}
*/
State.prototype.destroy = function () {
for (var property in this) {
if (this.hasOwnProperty(property)) {
this[property] = null;
}
}
return this;
};
/**
* Сравнивает текущее состояние объекта со значение state.
* @param {String|Number} state Состояние, с которым необходимо ставнить текущее.
* @returns {Boolean} Результат сравнения.
*/
State.prototype.is = function (state) {
return this.state === state;
};
/**
* Изменяет состояние объекта.
* После изменения состояния, первым будет вызвано событие с именем, соответствуюшим новому значению состояния.
* Затем событие {@link State#EVENT_CHANGE_STATE}.
* Если новое состояние не передано или объект уже находится в указаном состоянии, события не будут вызваны.
* @param {String|Number} state Новое сотояние объекта.
* @param {Array|*} [data] Данные, которые будут переданы аргументом в обработчики нового состояния.
* Если был передан массив, аргументами для обработчиков будут его элементы.
* @returns {State}
* @example
* new State()
* .onState('foo', function (bar) {
* bar; // 'baz'
* this.state; // 'foo'
* })
* .setState('foo', 'baz');
*
* new State()
* .onState('foo', function (bar, baz) {
* bar; // true
* baz; // false
* })
* .setState('foo', [true, false]);
*/
State.prototype.setState = function (state, data) {
var _state = !this.is(state);
var _data = arguments.length > 1 && toArray(data);
if (_data && (_state || _data.length)) {
this.stateData = _data;
if (this._event) {
this._event.data = _data;
}
}
if (_state) {
this.__changeState(state, _data);
}
return this;
};
/**
*
* @param {String|Number} state
* @param {Array} data
* @private
*/
State.prototype.__changeState = function (state, data) {
this.stopEmit(this.state);
var _events = this._events;
this.state = state;
if (_events) {
if (_events[state]) {
emit(this, state, data);
}
if (_events[this.EVENT_CHANGE_STATE] && this.is(state)) {
this.emit(this.EVENT_CHANGE_STATE, state);
}
}
};
/**
* Регистрирует обработчик состояния.
* Если объект уже находится в указанном состоянии, обработчик будет вызван немедленно.
* @param {String|Number} state Отслеживаемое состояние.
* @param {Function|EventEmitter} listener Обработчик состояния.
* @param {Object} [context=this] Контекст обработчика состояния.
* @returns {State}
* @example
* new State()
* .onState('foo', function () {
* this.state; // only 'foo'
* })
* .setState('foo')
* .setState('bar');
*/
State.prototype.onState = function (state, listener, context) {
if (this.is(state)) {
invoke(this, listener, state, context);
}
return this.on(state, listener, context);
};
/**
* Регистрирует одноразовый обработчик состояния.
* @param {String|Number} state Отслеживаемое состояние.
* @param {Function|EventEmitter} [listener] Обрабо1тчик состояния.
* @param {Object} [context=this] Контекст обработчика состояния.
* @returns {State}
* @example
* new State()
* .onceState('foo', function () {
* // Этот обработчик будет выполнен один раз
* })
* .setState('foo')
* .setState('bar')
* .setState('foo');
*/
State.prototype.onceState = function (state, listener, context) {
if (this.is(state)) {
invoke(this, listener, state, context);
} else {
this.once(state, listener, context);
}
return this;
};
/**
* Регистрирует обработчик изменения состояния.
* @param {Function|EventEmitter} listener Обработчик изменения состояния.
* @param {Object} [context=this] Контекст обработчика изменения состояния.
* @returns {State}
* @example
* new State()
* .onChangeState(function (state) {
* console.log(state); // 'foo', 'bar'
* })
* .setState('foo')
* .setState('bar');
*/
State.prototype.onChangeState = function (listener, context) {
return this.on(this.EVENT_CHANGE_STATE, listener, context);
};
/**
* Отменяет обработку изменения состояния.
* @param {Function|EventEmitter} [listener] Обработчик, который необходимо отменить.
* Если обработчик не был передан, будут отменены все обработчики.
* @returns {State}
*/
State.prototype.offChangeState = function (listener) {
if (listener) {
this.removeListener(this.EVENT_CHANGE_STATE, listener);
} else {
this.removeAllListeners(this.EVENT_CHANGE_STATE);
}
return this;
};
/**
*
* @param {Function} [wrapper]
* @constructor
* @requires EventEmitter
* @extends State
* @returns {Response}
*/
function Response(wrapper) {
this.State(this.STATE_PENDING);
this.data = null;
this.context = null;
this.callback = null;
this.keys = null;
if (typeof wrapper === 'function') {
call(wrapper, this);
}
return this;
}
/**
* @type {State}
*/
Response.State = State;
/**
* @type {Queue}
*/
Response.Queue = Queue;
/**
*
* @param {Response|*} [response]
* @static
* @returns {Boolean}
*/
Response.isResponse = function (response) {
return response instanceof Response;
};
/**
*
* @example
* var Response = require('Response');
*
* module.exports = Response.create();
* module.exports instanceof Response; // true
* module.exports.hasOwnProperty('resolve'); // false
*
* @returns {Object}
*/
Response.create = create;
/**
* @param {...*} [results]
* @static
* @returns {Response}
*/
Response.resolve = function (results) {
var response = new Response();
var index = arguments.length;
while (index--) {
response.stateData[index] = arguments[index];
}
response.state = response.STATE_RESOLVED;
return response;
};
/**
*
* @param {*} reason
* @static
* @returns {Response}
*/
Response.reject = function (reason) {
var response = new Response();
response.state = response.STATE_REJECTED;
response.stateData[0] = toError(reason);
return response;
};
/**
* @param {...*} [args]
* @static
* @returns {Queue}
*/
Response.queue = function (args) {
var index = arguments.length;
var stack = new Array(index);
while (index--) {
stack[index] = arguments[index];
}
return new Queue(stack);
};
/**
*
* @param {...*} [args]
* @static
* @returns {Queue}
*/
Response.strictQueue = function (args) {
var index = arguments.length;
var stack = new Array(index);
while (index--) {
stack[index] = arguments[index];
}
return new Queue(stack).strict();
};
Response.prototype = State.create(Response);
Response.prototype.State = State;
/**
* @type {String}
* @default 'pending'
*/
Response.prototype.STATE_PENDING = 'pending';
/**
* @type {String}
* @default 'resolve'
*/
Response.prototype.STATE_RESOLVED = 'resolve';
/**
* @type {String}
* @default 'error'
*/
Response.prototype.STATE_REJECTED = 'error';
/**
* @type {String}
* @default 'progress'
*/
Response.prototype.EVENT_PROGRESS = 'progress';
/**
*
* @type {*}
* @default null
*/
Response.prototype.data = null;
/**
*
* @type {Object}
* @default null
*/
Response.prototype.context = null;
/**
*
* @type {Function|null}
* @default null
*/
Response.prototype.callback = null;
/**
*
* @type {Array}
* @default null
*/
Response.prototype.keys = null;
/**
*
* @param {*} [data=null]
* @returns {Response}
*/
Response.prototype.setData = function (data) {
this.data = arguments.length ? data : null;
return this;
};
/**
*
* @param {String|Number|Array|Arguments} [keys=null]
* @returns {Response}
*/
Response.prototype.setKeys = function (keys) {
this.keys = arguments.length ? keys : null;
return this;
};
/**
*
* @param {Function} callback
* @param {Object} [context=this]
* @returns {Function}
*/
Response.prototype.bind = function (callback, context) {
if (typeof callback !== 'function') {
throw new Error('Callback is not a function');
}
var _context = context == null ? this : context;
return function responseCallback() {
return callback.apply(_context, arguments);
};
};
/**
* @param {String} type Тип события.
* @param {...*} [args] Аргументы, передаваемые в обработчик события.
* @returns {Boolean}
*/
Response.prototype.emit = function (type, args) {
var result = false;
if (this._events && this._events[type]) {
try {
result = nativeEmit.apply(this, arguments);
} catch (error) {
setReason(this, error);
}
}
return result;
};
/**
* @param {String|Number} state
* @param {Function|EventEmitter} listener
* @param {Object} [context=this]
* @returns {Response}
*/
Response.prototype.onState = function (state, listener, context) {
if (this.is(state)) {
try {
invoke(this, listener, state, context);
} catch (error) {
setReason(this, error);
}
}
return this.on(state, listener, context);
};
/**
* @param {String|Number} state
* @param {Function|EventEmitter} listener
* @param {Object} [context=this]
* @returns {Response}
*/
Response.prototype.onceState = function (state, listener, context) {
if (this.is(state)) {
try {
invoke(this, listener, state, context);
} catch (error) {
setReason(this, error);
}
} else {
this.once(state, listener, context);
}
return this;
};
/**
*
* @returns {Response}
*/
Response.prototype.pending = function () {
this.setState(this.STATE_PENDING);
return this;
};
/**
* @param {...*} [results]
* @returns {Response}
*/
Response.prototype.resolve = function (results) {
var index = arguments.length;
var data = new Array(index);
while (index--) {
data[index] = arguments[index];
}
this.setState(this.STATE_RESOLVED, data);
return this;
};
/**
*
* @param {*} reason
* @returns {Response}
*/
Response.prototype.reject = function (reason) {
this.setState(this.STATE_REJECTED, new Array(reason == null ? 0 : toError(reason)));
return this;
};
/**
*
* @param {*} progress
* @returns {Response}
*/
Response.prototype.progress = function (progress) {
if (this.isPending() && this._events && this._events[this.EVENT_PROGRESS]) {
this.emit(this.EVENT_PROGRESS, progress);
}
return this;
};
/**
*
* @returns {Boolean}
*/
Response.prototype.isPending = function () {
return !(this.isResolved() || this.isRejected());
};
/**
*
* @returns {Boolean}
*/
Response.prototype.isResolved = function () {
return this.is(this.STATE_RESOLVED);
};
/**
*
* @returns {Boolean}
*/
Response.prototype.isRejected = function () {
return this.is(this.STATE_REJECTED);
};
/**
*
* @param {Function|EventEmitter} [onResolve]
* @param {Function|EventEmitter} [onReject]
* @param {Function|EventEmitter} [onProgress]
* @param {Object} [context=this]
* @returns {Response}
*/
Response.prototype.then = function (onResolve, onReject, onProgress, context) {
if (onResolve != null) {
this.onceState(this.STATE_RESOLVED, onResolve, context);
}
if (onReject != null) {
this.onceState(this.STATE_REJECTED, onReject, context);
}
if (onProgress != null) {
this.on(this.EVENT_PROGRESS, onProgress, context);
}
return this;
};
/**
*
* @param {Function|EventEmitter} listener
* @param {Object} [context=this]
* @returns {Response}
*/
Response.prototype.always = function (listener, context) {
this
.onceState(this.STATE_RESOLVED, listener, context)
.onceState(this.STATE_REJECTED, listener, context);
return this;
};
/**
*
* @param {Function|EventEmitter} listener
* @param {Object} [context=this]
* @returns {Response}
*/
Response.prototype.onResolve = function (listener, context) {
this.onceState(this.STATE_RESOLVED, listener, context);
return this;
};
/**
*
* @param {Function|EventEmitter} listener
* @param {Object} [context=this]
* @returns {Response}
*/
Response.prototype.onReject = function (listener, context) {
this.onceState(this.STATE_REJECTED, listener, context);
return this;
};
/**
*
* @param {Function|EventEmitter} listener
* @param {Object} [context=this]
* @returns {Response}
*/
Response.prototype.onProgress = function (listener, context) {
this.on(this.EVENT_PROGRESS, listener, context);
return this;
};
/**
*
* @param {Response} parent
* @throws {Error} Бросает исключение, если parent равен this.
* @returns {Response}
* @this {Response}
*/
Response.prototype.notify = function (parent) {
if (parent) {
if (parent === this) {
throw new Error('Can\'t notify itself');
}
this.then(parent.resolve, parent.reject, parent.progress, parent);
}
return this;
};
/**
* @example
* var Response = require('Response');
* var Vow = require('Vow');
*
* new Response()
* .onResolve(function (result) {
* // result is "'success'" here
* })
* .listen(new Vow.Promise(function (resolve, reject, notify) {
* resolve('success');
* }));
*
* @param {Response|Object} response
* @throws {Error} Бросает исключение, если response равен this.
* @returns {Response}
* @this {Response}
*/
Response.prototype.listen = function (response) {
if (response === this) {
throw new Error('Cannot listen on itself');
}
if (!this.isPending()) {
this.pending();
}
response.then(this.resolve, this.reject, this.progress, this);
return this;
};
/**
*
* @returns {Response}
*/
Response.prototype.done = function () {
return this.always(this.destroy);
};
/**
*
* @param {Object|null} [context]
* @returns {Response}
*/
Response.prototype.setContext = function (context) {
if (typeof context === 'object') {
this.context = context;
}
return this;
};
/**
*
* @param {Error|*} [error]
* @param {...*} [results]
*/
Response.prototype.callback = function defaultResponseCallback(error, results) {
var index = arguments.length;
var arg;
if (error == null) {
if (index && --index) {
arg = new Array(index);
while (index--) {
arg[index] = arguments[index + 1];
}
call(this.resolve, this, arg);
} else {
this.resolve();
}
} else {
this.reject(error);
}
};
/**
* @example
* var Response = require('Response');
* var r = new Response()
* .bind(function (data, textStatus, jqXHR) {
* if (data && data.error) {
* this.reject(data.error);
* } else {
* this.resolve(data.result);
* }
* });
*
* $.getJSON('ajax/test.json', r.callback);
*
* @param {Function} [callback=Response.callback]
* @param {Object} [context=this]
* @returns {Response}
*/
Response.prototype.makeCallback = function (callback, context) {
this.callback = this.bind(typeof callback === 'function' ? callback : Response.prototype.callback, context);
return this;
};
/**
* @example
* var r = new Response();
* fs.open('/file.txt', 'r', r.getCallback());
*
* @returns {Function}
*/
Response.prototype.getCallback = function () {
if (typeof this.callback !== 'function') {
this.makeCallback();
}
return this.callback;
};
/**
*
* @example
* var response = new Response();
*
* response
* .makeCallback()
* .setContext(fs)
*
* // Open file.txt;
* .invoke(fs.open, '/file.txt', 'r', response.callback)
*
* // File is opened, read first 10 bytes
* .then(function (fd) {
* this
* .setData(fd) // Save file descriptor
* .invoke('read', fd, new Buffer(), 0, 10, null, this.callback);
* })
*
* // File is read
* .then(function (bytesRead, buffer) {
* this.invoke('close', this.data, this.callback);
* })
*
* // File is closed
* .then(function (fd) {});
*
* @param {Function|String} method
* @param {...*} [args]
* @throws {Error} Бросает исключение, если методом является строка и response не привязан к объекту,
* либо метод не является функцией.
* @returns {*} Результат работы метода method
*/
Response.prototype.invoke = function (method, args) {
var context = this.context == null ? this : this.context;
var arg;
var index;
var _method = method;
if (typeof _method === 'string' || getType(_method) === 'String') {
if (context == null) {
throw new Error('Context object is not defined. Use the Response#setContext method.');
}
_method = context[method];
}
if (typeof _method === 'function') {
index = arguments.length - 1;
arg = new Array(index);
while (index--) {
arg[index] = arguments[index + 1];
}
if (!this.isPending()) {
this.pending();
}
try {
return call(_method, context, arg);
} catch (error) {
return this.reject(error);
}
}
throw new Error('Method is not a function.');
};
/**
*
* @param {Function} callback
* @param {Object} [context=this]
*/
Response.prototype.spread = function (callback, context) {
call(callback, context == null ? this : context, this.stateData);
return this;
};
/**
*
* @example
* var r = new Response()
* .resolve(3) // resolve one result
* .getResult() // 3, returns result
*
* r
* .resolve(1, 2) // resolve more results
* .getResult() // [1, 2], returns a results array
*
* r.getResult(1) // 2, returns result on a index
*
* r.getResult(['foo', 'bar']) // {foo: 1, bar: 2}, returns a hash results
*
* r
* .setKeys(['foo', 'bar']) // sets a default keys
* .getResult('bar') // 2, returns result on a default key
*
*
* @param {String|Number|Array|Arguments} [key=this.keys]
* @returns {*|null}
* @throws {Error}
*/
Response.prototype.getResult = function (key) {
if (!this.isResolved()) {
return null;
}
var keys = arguments.length ? key : this.keys;
var stateData = this.stateData;
var result;
var index;
var length;
var _key;
switch (getType(keys)) {
case 'String':
if (!isArray(this.keys)) {
throw new Error('Default keys must be a array');
}
index = this.keys.length;
while (index--) {
if (this.keys[index] === keys) {
return stateData[index];
}
}
return null;
case 'Number':
return stateData[keys];
case 'Array':
case 'Arguments':
length = keys.length;
index = 0;
result = {};
while (index < length) {
_key = keys[index];
if (_key != null) {
result[_key] = stateData[index++];
}
}
return result;
default:
return stateData.length === 1 ? stateData[0] : stateData;
}
};
/**
*
* @returns {Error|null}
*/
Response.prototype.getReason = function () {
return this.isRejected() ? this.stateData[0] : null;
};
/**
*
* @returns {Object}
*/
Response.prototype.toJSON = function () {
return this.getResult();
};
/**
*
* @param {Array} [stack=[]]
* @param {Boolean} [start=false]
* @constructor
* @extends Response
* @returns {Queue}
*/
function Queue(stack, start) {
this.Response();