salix/back/methods/dms/uploadFile.js

118 lines
3.8 KiB
JavaScript
Raw Normal View History

const fs = require('fs-extra');
const UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
Self.remoteMethodCtx('uploadFile', {
description: 'Uploads a file and inserts into dms model',
accessType: 'WRITE',
2019-06-13 07:21:36 +00:00
accepts: [
{
arg: 'options',
type: 'object'
}, {
arg: 'warehouseId',
type: 'Number',
description: ''
}, {
arg: 'companyId',
type: 'Number',
description: ''
}, {
arg: 'dmsTypeId',
type: 'Number',
description: ''
}, {
arg: 'reference',
type: 'String',
description: ''
}, {
arg: 'description',
type: 'String',
description: ''
}, {
arg: 'hasFile',
type: 'Boolean',
description: ''
}
],
returns: {
type: 'Object',
root: true
},
http: {
path: `/uploadFile`,
verb: 'POST'
}
});
2019-06-13 07:21:36 +00:00
Self.uploadFile = async(ctx, options) => {
const models = Self.app.models;
const storageConnector = Self.app.dataSources.storage.connector;
const myUserId = ctx.req.accessToken.userId;
const myWorker = await models.Worker.findOne({where: {userFk: myUserId}});
const args = ctx.args;
const fileOptions = {};
2019-06-13 07:21:36 +00:00
let tx;
let myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
if (!myOptions.transaction) {
tx = await Self.beginTransaction({});
myOptions.transaction = tx;
}
try {
const hasWriteRole = await models.DmsType.hasWriteRole(ctx, args.dmsTypeId);
if (!hasWriteRole)
throw new UserError(`You don't have enough privileges`);
const uploaded = await models.Container.upload('temp', ctx.req, ctx.result, fileOptions);
const files = Object.values(uploaded.files).map(file => {
return file[0];
});
const dmsType = await models.DmsType.findById(args.dmsTypeId);
const promises = [];
files.forEach(file => {
const newDms = Self.create({
workerFk: myWorker.id,
dmsTypeFk: args.dmsTypeId,
companyFk: args.companyId,
warehouseFk: args.warehouseId,
reference: args.reference,
description: args.description,
hasFile: args.hasFile
2019-06-13 07:21:36 +00:00
}, myOptions).then(newDms => {
const extension = storageConnector.getFileExtension(file.name);
const fileName = `${newDms.id}.${extension}`;
2019-06-13 07:21:36 +00:00
return newDms.updateAttribute('file', fileName, myOptions);
}).then(dms => {
return models.Container.getContainer('temp').then(container => {
const originPath = `${container.client.root}/${container.name}/${file.name}`;
const destinationPath = `${container.client.root}/${dmsType.path}/${dms.file}`;
return fs.rename(originPath, destinationPath).then(() => {
return dms;
});
});
});
promises.push(newDms);
});
const resolvedPromise = await Promise.all(promises);
2019-06-13 07:21:36 +00:00
if (tx) await tx.commit();
return resolvedPromise;
} catch (e) {
2019-06-13 07:21:36 +00:00
if (tx) await tx.rollback();
throw e;
}
};
};