forked from restify/plugins
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpause.js
More file actions
66 lines (51 loc) · 1.5 KB
/
pause.js
File metadata and controls
66 lines (51 loc) · 1.5 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
// Copyright 2012 Mark Cavage, Inc. All rights reserved.
'use strict';
///--- Helpers
/**
* this pre handler fixes issues with node hanging when an asyncHandler is
* used prior to bodyParser.
* https://github.com/restify/node-restify/issues/287
* https://github.com/restify/node-restify/issues/409
* https://github.com/restify/node-restify/wiki/1.4-to-2.0-Migration-Tips
* @public
* @function pauseStream
* @param {Stream} stream the stream to pause
* @returns {undefined}
*/
function pauseStream(stream) {
function _buffer(chunk) {
stream.__buffered.push(chunk);
}
function _catchEnd(chunk) {
stream.__rstfyEnded = true;
}
stream.__rstfyEnded = false;
stream.__rstfyPaused = true;
stream.__buffered = [];
stream.on('data', _buffer);
stream.once('end', _catchEnd);
stream.pause();
stream._resume = stream.resume;
stream.resume = function _rstfy_resume() {
if (!stream.__rstfyPaused) {
return;
}
stream.removeListener('data', _buffer);
stream.removeListener('end', _catchEnd);
stream.__buffered.forEach(stream.emit.bind(stream, 'data'));
stream.__buffered.length = 0;
stream._resume();
stream.resume = stream._resume;
if (stream.__rstfyEnded) {
stream.emit('end');
}
};
}
///--- Exports
module.exports = function pause() {
function prePause(req, res, next) {
pauseStream(req);
next();
}
return (prePause);
};