salix/modules/client/back/methods/client/uploadFile.js

93 lines
2.4 KiB
JavaScript

module.exports = Self => {
Self.remoteMethodCtx('uploadFile', {
description: 'Upload and attach a file to a client',
accessType: 'WRITE',
accepts: [
{
arg: 'id',
type: 'number',
description: 'The client id',
http: {source: 'path'}
},
{
arg: 'warehouseId',
type: 'number',
description: 'The warehouse id',
required: true
},
{
arg: 'companyId',
type: 'number',
description: 'The company id',
required: true
},
{
arg: 'dmsTypeId',
type: 'number',
description: 'The dms type id',
required: true
},
{
arg: 'reference',
type: 'string',
required: true
},
{
arg: 'description',
type: 'string',
required: true
},
{
arg: 'hasFile',
type: 'boolean',
description: 'True if has an attached file',
required: true
}
],
returns: {
type: 'object',
root: true
},
http: {
path: `/:id/uploadFile`,
verb: 'POST'
}
});
Self.uploadFile = async(ctx, id, options) => {
const models = Self.app.models;
let tx;
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
if (!myOptions.transaction) {
tx = await Self.beginTransaction({});
myOptions.transaction = tx;
}
const promises = [];
try {
const uploadedFiles = await models.Dms.uploadFile(ctx, myOptions);
uploadedFiles.forEach(dms => {
const newClientDms = models.ClientDms.create({
clientFk: id,
dmsFk: dms.id
}, myOptions);
promises.push(newClientDms);
});
const resolvedPromises = await Promise.all(promises);
if (tx) await tx.commit();
return resolvedPromises;
} catch (e) {
if (tx) await tx.rollback();
throw e;
}
};
};