@strapi/data-transfer
Version:
Data transfer capabilities for Strapi
97 lines (93 loc) • 2.88 kB
JavaScript
;
var stream = require('stream');
/**
* Create a filter stream that discard chunks which doesn't satisfies the given predicate
*
* @param predicate - A filter predicate, takes a stream data chunk as parameter and returns a boolean value
* @param options - Transform stream options
*/ const filter = (predicate, options = {
objectMode: true
})=>{
return new stream.Transform({
...options,
async transform (chunk, _encoding, callback) {
const keep = await predicate(chunk);
callback(null, keep ? chunk : undefined);
}
});
};
/**
* Create a map stream that transform chunks using the given predicate
*
* @param predicate - A map predicate, takes a stream data chunk as parameter and returns a mapped value
* @param options - Transform stream options
*/ const map = (predicate, options = {
objectMode: true
})=>{
return new stream.Transform({
...options,
async transform (chunk, _encoding, callback) {
const mappedValue = await predicate(chunk);
callback(null, mappedValue);
}
});
};
/**
* Collect every chunks from a Readable stream.
*
* @param stream - The redable stream to collect data from
* @param options.destroy - If set to true, it automatically calls `destroy()` on the given stream upon receiving the 'end' event
*/ const collect = (stream, options = {
destroy: true
})=>{
const chunks = [];
return new Promise((resolve, reject)=>{
let settled = false;
const cleanup = ()=>{
stream.removeListener('data', onData);
stream.removeListener('end', onEnd);
stream.removeListener('close', onClose);
stream.removeListener('error', onError);
};
const finishResolve = ()=>{
if (settled) {
return;
}
settled = true;
cleanup();
resolve(chunks);
};
const finishReject = (err)=>{
if (settled) {
return;
}
settled = true;
cleanup();
reject(err);
};
const onData = (chunk)=>{
chunks.push(chunk);
};
const onEnd = ()=>{
if (options.destroy) {
stream.destroy();
}
finishResolve();
};
const onClose = ()=>{
// Handles streams that emit `close` without `end` (e.g. `destroy()` in `_read`).
finishResolve();
};
const onError = (err)=>{
finishReject(err);
};
stream.on('data', onData);
stream.on('end', onEnd);
stream.on('close', onClose);
stream.on('error', onError);
});
};
exports.collect = collect;
exports.filter = filter;
exports.map = map;
//# sourceMappingURL=stream.js.map