arrest
Version:
OpenAPI v3 compliant REST framework for Node.js, with support for MongoDB and JSON-Schema
97 lines • 3.24 kB
JavaScript
import { Operation } from './operation.js';
import { toCSV } from './util.js';
export class PipelineOperation extends Operation {
async createJob(req, res) {
const out = {
req,
res,
query: {},
opts: {},
feat: {
filter: {
fields: true,
data: true,
},
},
};
if (req.query.format === 'csv' && req.query.csv_fields?.length) {
const opts = {
fields: req.query.csv_fields,
...(req.query.csv_options || {}),
};
if (req.query.csv_names?.length === opts.fields.length) {
opts.fields = opts.fields.reduce((o, i, idx) => {
o[i] = req.query.csv_names[idx];
return o;
}, {});
}
out.feat.format = {
...opts,
type: 'csv',
};
}
return out;
}
async prepareQuery(job) {
return job;
}
async prepareDoc(job) {
return job;
}
async prepareOpts(job) {
return job;
}
async redactResult(job) {
if (job.req.ability && job.data && typeof job.data === 'object' && (job.feat?.filter?.fields || job.feat?.filter?.data)) {
job.data = this.checkAbility(job.req.ability, job.data, job.feat.filter.fields, job.feat.filter.data);
}
return job;
}
async processResult(job) {
if (job.data) {
if (job.feat?.format?.type === 'csv' && Array.isArray(job.data)) {
job.data = toCSV(job.data, job.feat.format);
job.res.setHeader('content-type', 'text/csv');
if (job.feat.format.filename) {
job.res.setHeader('content-disposition', `attachment; filename=\"${job.feat.format.filename}\"`);
}
job.res.send(job.data);
}
else {
job.res.jsonp(job.data);
}
}
else {
job.res.end();
}
return job;
}
async handler(req, res) {
try {
const job = await this.createJob(req, res);
await this.prepareQuery(job);
await this.prepareDoc(job);
await this.prepareOpts(job);
req.logger.debug(this.info.operationId, 'query', JSON.stringify(job.query, null, 2));
req.logger.debug(this.info.operationId, 'doc', JSON.stringify(job.doc, null, 2));
req.logger.debug(this.info.operationId, 'opts', JSON.stringify(job.opts, null, 2));
await this.runOperation(job);
await this.redactResult(job);
await this.processResult(job);
}
catch (err) {
this.api.handleError(err, req, res);
}
}
}
export class SimplePipelineOperation extends PipelineOperation {
customRunner;
constructor(customRunner, resource, path, method, id) {
super(resource, path, method, id);
this.customRunner = customRunner;
}
runOperation(job) {
return this.customRunner(job);
}
}
//# sourceMappingURL=pipeline.js.map