forked from maksrom/javascript-nodejs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTaskProxy.js
More file actions
213 lines (168 loc) · 6.41 KB
/
Copy pathTaskProxy.js
File metadata and controls
213 lines (168 loc) · 6.41 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
'use strict';
var crypto = require('crypto'),
objectAssign = require('object-assign'),
objectOmit = require('object.omit'),
Promise = require('bluebird');
var TaskProxy = function (opts) {
objectAssign(this, {
task: opts.task,
file: opts.file,
opts: opts.opts
});
};
function makeHash(key) {
return crypto.createHash('md5').update(key).digest('hex');
}
objectAssign(TaskProxy.prototype, {
processFile: function () {
var self = this;
return this._checkForCachedValue().then(function (cached) {
// If we found a cached value
if (cached.value) {
// Extend the cached value onto the file, but don't overwrite original path info
return objectAssign(
self.file,
objectOmit(cached.value, ['cwd', 'path', 'base', 'stat'])
);
}
// Otherwise, run the proxied task
return self._runProxiedTaskAndCache(cached.key);
});
},
removeCachedResult: function () {
var self = this;
return this._getFileKey().then(function (cachedKey) {
var removeCached = Promise.promisify(self.opts.fileCache.removeCached, self.opts.fileCache);
return removeCached(self.opts.name, cachedKey);
});
},
_getFileKey: function () {
var getKey = this.opts.key;
if (typeof getKey === 'function' && getKey.length === 2) {
getKey = Promise.promisify(getKey, this.opts);
}
return Promise.resolve(getKey(this.file)).then(function (key) {
if (!key) {
return key;
}
return makeHash(key);
});
},
_checkForCachedValue: function () {
var self = this;
return this._getFileKey().then(function (key) {
// If no key returned, bug out early
if (!key) {
return {
key: key,
value: null
};
}
var getCached = Promise.promisify(self.opts.fileCache.getCached, self.opts.fileCache);
return getCached(self.opts.name, key).then(function (cached) {
if (!cached) {
return {
key: key,
value: null
};
}
var parsedContents;
try {
parsedContents = JSON.parse(cached.contents);
} catch (e) {
parsedContents = { cached: cached.contents };
}
if (self.opts.restore) {
parsedContents = self.opts.restore(parsedContents);
}
return {
key: key,
value: parsedContents
};
});
});
},
_runProxiedTaskAndCache: function (cachedKey) {
var self = this;
return self._runProxiedTask().then(function (result) {
// If this wasn't a success, continue to next task
// TODO: Should this also offer an async option?
if (self.opts.success !== true && !self.opts.success(result)) {
return result;
}
return self._storeCachedResult(cachedKey, result).then(function () {
return result;
});
});
},
_runProxiedTask: function () {
var self = this,
def = Promise.defer(),
handleData = function (datum) {
// Wait for data (can be out of order, so check for matching file we wrote)
if (self.file !== datum) {
return;
}
// Be good citizens and remove our listeners
self.task.removeListener('error', handleError);
self.task.removeListener('data', handleData);
// Reduce the maxListeners back down
self.task.setMaxListeners(self.task._maxListeners - 2);
def.resolve(datum);
},
handleError = function (err) {
// TODO: Errors will step on each other here
// Reduce the maxListeners back down
self.task.setMaxListeners(self.task._maxListeners - 1);
def.reject(err);
};
// Bump up max listeners to prevent memory leak warnings
var currMaxListeners = this.task._maxListeners || 0;
this.task.setMaxListeners(currMaxListeners + 2);
this.task.on('data', handleData);
this.task.once('error', handleError);
// Run through the other task and grab output (or error)
// Not sure if a _.defer is necessary here
self.task.write(self.file);
return def.promise;
},
_getValueFromResult: function (result) {
var getValue;
if (typeof this.opts.value !== 'function') {
if (typeof this.opts.value === 'string') {
getValue = {};
getValue[this.opts.value] = result[this.opts.value];
}
return Promise.resolve(getValue);
} else if (this.opts.value.length === 2) {
// Promisify if passed a node style function
getValue = Promise.promisify(this.opts.value, this.opts);
} else {
getValue = this.opts.value;
}
return Promise.resolve(getValue(result));
},
_storeCachedResult: function (key, result) {
var self = this;
// If we didn't have a cachedKey, skip caching result
if (!key) {
return Promise.resolve(result);
}
return this._getValueFromResult(result).then(function (value) {
var val,
addCached = Promise.promisify(self.opts.fileCache.addCached, self.opts.fileCache);
if (typeof value !== 'string') {
if (value && typeof value === 'object' && Buffer.isBuffer(value.contents)) {
// Shallow copy so "contents" can be safely modified
val = objectAssign({}, value);
val.contents = val.contents.toString('utf8');
}
val = JSON.stringify(value, null, 2);
} else {
val = value;
}
return addCached(self.opts.name, key, val);
});
}
});
module.exports = TaskProxy;