Skip to content

Commit

Permalink
feat: use stream class to replace EventEmitter.
Browse files Browse the repository at this point in the history
  • Loading branch information
iyuq authored and fengmk2 committed Sep 7, 2017
1 parent 0aacd61 commit 72e5478
Showing 1 changed file with 31 additions and 30 deletions.
61 changes: 31 additions & 30 deletions lib/mm.js
Expand Up @@ -7,6 +7,8 @@ const https = require('https');
const cp = require('child_process');
const semver = require('semver');
const thenify = require('thenify').withCallback;
const Readable = require('stream').Readable;
const Duplex = require('stream').Duplex;

const mock = module.exports = function mock() {
return muk.apply(null, arguments);
Expand Down Expand Up @@ -213,9 +215,10 @@ function matchURL(options, params) {
}

function mockRequest() {
const req = new EventEmitter();
req.write = function() {};
req.end = function() {};
const req = new Duplex({
write() {},
read() {},
});
req.abort = function() {
req._aborted = true;
process.nextTick(function() {
Expand Down Expand Up @@ -312,7 +315,27 @@ function _request(mod, url, data, headers, delay) {
if (stream) {
res = stream;
} else {
res = new EventEmitter();
res = new Readable({
read() {
let chunk = datas.shift();
if (!chunk) {
if (!req._aborted) {
this.push(null);
}
return;
}

if (!req._aborted) {
if (typeof chunk === 'string') {
chunk = new Buffer(chunk);
}
if (this.charset) {
chunk = chunk.toString(this.charset);
}
this.push(chunk);
}
},
});
res.setEncoding = function(charset) {
res.charset = charset;
};
Expand All @@ -321,34 +344,9 @@ function _request(mod, url, data, headers, delay) {
res.statusCode = headers.statusCode || 200;
res.headers = omit(headers, 'statusCode');

const ondata = function() {
let chunk = datas.shift();
if (!chunk) {
if (!req._aborted) {
res.emit('end');
}
return;
}

if (!req._aborted) {
if (typeof chunk === 'string') {
chunk = new Buffer(chunk);
}
if (res.charset) {
chunk = chunk.toString(res.charset);
}
res.emit('data', chunk);
}
process.nextTick(ondata);
};

setTimeout(function() {
if (!req._aborted) {
req.emit('response', res);
if (stream) {
return;
}
process.nextTick(ondata);
}
}, delay);

Expand Down Expand Up @@ -421,7 +419,10 @@ function _requestError(mod, url, reqError, resError, delay) {
return req.emit('error', reqError);
}

const res = new EventEmitter();
const res = new Duplex({
read() {},
write() {},
});
res.statusCode = 200;
res.headers = {
server: 'MockMateServer',
Expand Down

0 comments on commit 72e5478

Please sign in to comment.