salix/modules/entry/back/methods/entry/getBuysCsv.js

45 lines
1.3 KiB
JavaScript

const {toCSV} = require('vn-loopback/util/csv');
const {flatten} = require('vn-loopback/util/flatten');
const UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
Self.remoteMethodCtx('getBuysCsv', {
description: 'Returns buys for one entry in CSV file format',
accessType: 'READ',
accepts: [{
arg: 'id',
type: 'number',
required: true,
description: 'The entry id',
http: {source: 'path'}
}
],
returns: [
{
arg: 'body',
type: 'file',
root: true
}, {
arg: 'Content-Type',
type: 'String',
http: {target: 'header'}
}, {
arg: 'Content-Disposition',
type: 'String',
http: {target: 'header'}
}
],
http: {
path: `/:id/getBuysCsv`,
verb: 'GET'
}
});
Self.getBuysCsv = async(ctx, id, options) => {
const data = await Self.getBuys(ctx, id, null, options);
if (!data.length) throw new UserError('The entry has no lines or does not exist');
const dataFlatted = flatten(data);
return [toCSV(dataFlatted), 'text/csv', `inline; filename="buys-${id}.csv"`];
};
};