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', 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' } }); 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 = {}; 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 }, myOptions).then(newDms => { const extension = storageConnector.getFileExtension(file.name); const fileName = `${newDms.id}.${extension}`; 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); if (tx) await tx.commit(); return resolvedPromise; } catch (e) { if (tx) await tx.rollback(); throw e; } }; };