-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathresponse.js
More file actions
109 lines (87 loc) · 2.43 KB
/
Copy pathresponse.js
File metadata and controls
109 lines (87 loc) · 2.43 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
const NOT_ITERABLE_ERROR = new Error('Response is not iterable');
class Response {
constructor(promise) {
this.promise = promise;
[
'map',
'filter',
'reduce',
'some',
'every',
'reverse',
].forEach(method => {
this[method] = function (...args) {
return new Response(this.promise.then(data => {
if (Array.isArray(data)) {
return data[method](...args);
}
throw NOT_ITERABLE_ERROR;
}))
}
})
}
valueOf() {
return this.data;
}
toString() {
return `[object Response<${this.data.length}>`;
}
orderBy(fn) {
return this.sort(fn);
}
take(limit) {
return _takeWrap(this.promise, limit);
}
takeLast(limit) {
return _takeLastWrap(this.promise, limit);
}
sort(fn, asc = true) {
return _sortWrap(this.promise, fn, asc);
}
asc(str) {
return this.sort(str, true);
}
desc(str) {
return this.sort(str, false);
}
count() {
return _countWrap(this.promise)
}
paginate(page, limit) {
if (page <= 0 || limit <= 0) {
throw new Error('Page and Limit should be more than 30')
}
return _paginateWrap(this.promise, page, limit);
}
then(fn) {
return this.promise.then(fn);
}
catch(fn) {
return this.promise.catch(fn);
}
json() {
return this.promise.then(data => JSON.parse(data));
}
or(defaultValue) {
return this.promise.then(data => data === null ? defaultValue : data);
}
}
const wrap = fn => (el, ...rest) => {
return new Response(el.then(data => {
if (!Array.isArray(data)) {
throw new Error('Response is not iterable');
}
return fn(data, ...rest);
}))
}
const _countWrap = wrap(data => data.length);
const _takeWrap = wrap((data, limit) => data.slice(0, limit));
const _takeLastWrap = wrap((data, limit) => data.slice(-limit));
const _sortWrap = wrap((data, fn, asc = true) => {
return data.sort(typeof fn === 'string' ? (a, b) => (asc ? a[fn] - b[fn] : b[fn] - a[fn]) : fn);
});
const _paginateWrap = wrap((data, page, limit) => {
const start = (page - 1) * limit;
return data.slice(start, start + limit);
});
module.exports = Response