zippycli
Version:
An unofficial Zippyshare CLI
166 lines (142 loc) • 3.62 kB
JavaScript
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
import { Readable } from 'stream';
import fetch from 'node-fetch';
import { AbortController } from 'abort-controller';
/**
* RequestStream, similar to the deprecated request module stream.
*/
export class RequestStream extends Readable {
/**
* Request options.
*/
/**
* Abort controller.
*/
/**
* Create RequestStream.
*
* @param options Request options.
*/
constructor(options) {
super();
_defineProperty(this, "_abortController_", null);
this._options_ = options;
}
/**
* Abort request.
*/
abort() {
this.destroy();
}
/**
* Read implementation.
*
* @param _size Size to be read.
*/
// eslint-disable-next-line @typescript-eslint/naming-convention
_read(_size) {
// Get options if set, only starts reading once.
const options = this._options_;
if (!options) {
return;
}
this._options_ = null;
fetch(options.url, {
signal: (this._abortController_ = new AbortController()).signal,
method: options.method || 'GET',
headers: {
'User-Agent': '-',
...(options.headers || {})
},
compress: !!options.gzip,
timeout: options.timeout
}).then(res => {
const {
status,
headers,
body
} = res;
const headersRaw = headers.raw();
const headersObject = {};
for (const p of Object.keys(headersRaw)) {
headersObject[p] = headersRaw[p].join(', ');
}
const response = {
statusCode: status,
headers: headersObject
};
body.on('error', err => {
this.emit('error', err);
});
body.on('data', data => {
this.push(data);
});
body.on('end', () => {
this.push(null);
});
this.on('end', () => {
this.emit('complete', response);
});
this.emit('response', response);
}, err => {
this.emit('error', err);
});
}
/**
* Destroy implementation.
*
* @param error Error object.
* @param callback Callback function.
*/
// eslint-disable-next-line @typescript-eslint/naming-convention
_destroy(error, callback) {
const abortController = this._abortController_;
this._abortController_ = null;
if (abortController) {
abortController.abort();
}
super._destroy(error, callback);
}
/**
* Request factory.
*
* @param defaults Default options.
* @returns Request factory.
*/
static factory(defaults = {}) {
const Constructor = this;
return (options, cb) => {
const opts = {
defaults,
...options
};
const request = new Constructor(opts);
if (cb) {
let response = {
statusCode: 0,
headers: {}
};
const datas = [];
request.on('response', resp => {
response = resp;
});
request.on('data', data => {
datas.push(data);
});
request.on('error', err => {
request.abort();
cb(err, response, Buffer.concat(datas));
});
request.on('complete', resp => {
const data = Buffer.concat(datas);
const {
encoding
} = opts;
cb(null, resp, encoding === null ? data : data.toString(encoding));
});
}
return request;
};
}
}
//# sourceMappingURL=request.mjs.map