69 lines
1.9 KiB
JavaScript
69 lines
1.9 KiB
JavaScript
/**
|
|
* @fileoverview Mock Express Request object with a body that can be read.
|
|
*/
|
|
const _ = require('lodash');
|
|
const {Readable} = require('stream');
|
|
|
|
/**
|
|
* Mock req for getting the request body from.
|
|
* This is required because an Express request is a Readable stream, that we
|
|
* use in order to get the raw body for hmac calculations.
|
|
*/
|
|
class MockRequest extends Readable {
|
|
/**
|
|
* Constructor for MockRequest
|
|
*
|
|
* @param {Object?} opt - Options object
|
|
* @param {string?} opt.mockBody - Mock body for the request
|
|
*/
|
|
constructor(opt) {
|
|
super(opt);
|
|
|
|
this._mockReqLengthRead = 0;
|
|
this._mockReqTotalLength = 0;
|
|
const body = _.get(opt, 'mockBody');
|
|
|
|
if (!_.isUndefined(body)) {
|
|
this._mockReqBody = body;
|
|
this._mockReqTotalLength = this._mockReqBody.length;
|
|
}
|
|
|
|
//
|
|
// Set appropriate headers
|
|
//
|
|
this.headers = {};
|
|
if (this._mockReqTotalLength > 0) {
|
|
this.headers = {
|
|
'content-length': this._mockReqTotalLength,
|
|
'content-type': 'application/json; charset=utf-8'
|
|
};
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Called whenver the readable string needs more bytes.
|
|
* We use it to return the next section of our mockBody.
|
|
*
|
|
* @param {number} size - the number of bytes to read.
|
|
*/
|
|
_read(size) {
|
|
if (this._mockReqLengthRead >= this._mockReqTotalLength) {
|
|
this.push(null);
|
|
} else {
|
|
const remaining = this._mockReqTotalLength - this._mockReqLengthRead;
|
|
const toRead = Math.min(remaining, size);
|
|
const str = this._mockReqBody.substr(this._mockReqLengthRead, toRead);
|
|
const buf = Buffer.from(str, 'utf-8');
|
|
this.push(buf);
|
|
this._mockReqLengthRead += toRead;
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Export the MockRequest
|
|
*/
|
|
module.exports = {
|
|
MockRequest
|
|
};
|