2020-11-27 12:10:39 +00:00
|
|
|
const UserError = require('vn-loopback/util/user-error');
|
2023-04-14 11:04:40 +00:00
|
|
|
const fs = require('fs/promises');
|
2020-12-18 16:23:04 +00:00
|
|
|
const path = require('path');
|
2020-11-27 12:10:39 +00:00
|
|
|
|
|
|
|
module.exports = Self => {
|
|
|
|
Self.remoteMethodCtx('upload', {
|
|
|
|
description: 'Uploads a file and inserts into dms model',
|
|
|
|
accessType: 'WRITE',
|
|
|
|
accepts: [
|
|
|
|
{
|
|
|
|
arg: 'id',
|
|
|
|
type: 'Number',
|
|
|
|
description: 'The entity id',
|
|
|
|
required: true
|
2023-04-17 12:33:07 +00:00
|
|
|
}, {
|
2020-11-27 12:10:39 +00:00
|
|
|
arg: 'collection',
|
|
|
|
type: 'string',
|
|
|
|
description: 'The collection name',
|
|
|
|
required: true
|
2023-04-17 12:33:07 +00:00
|
|
|
}
|
|
|
|
],
|
2020-11-27 12:10:39 +00:00
|
|
|
returns: {
|
|
|
|
type: 'Object',
|
|
|
|
root: true
|
|
|
|
},
|
|
|
|
http: {
|
|
|
|
path: `/upload`,
|
|
|
|
verb: 'POST'
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
Self.upload = async ctx => {
|
|
|
|
const models = Self.app.models;
|
2020-12-18 16:23:04 +00:00
|
|
|
const TempContainer = models.TempContainer;
|
2020-11-27 12:10:39 +00:00
|
|
|
const fileOptions = {};
|
|
|
|
const args = ctx.args;
|
|
|
|
|
2023-04-14 11:04:40 +00:00
|
|
|
let tempFilePath;
|
2020-12-18 16:23:04 +00:00
|
|
|
try {
|
|
|
|
const hasWriteRole = await models.ImageCollection.hasWriteRole(ctx, args.collection);
|
|
|
|
if (!hasWriteRole)
|
|
|
|
throw new UserError(`You don't have enough privileges`);
|
2020-11-27 12:10:39 +00:00
|
|
|
|
2020-12-18 16:23:04 +00:00
|
|
|
if (process.env.NODE_ENV == 'test')
|
2021-03-15 12:43:22 +00:00
|
|
|
throw new UserError(`Action not allowed on the test environment`);
|
2020-11-27 12:10:39 +00:00
|
|
|
|
2020-12-18 16:23:04 +00:00
|
|
|
// Upload file to temporary path
|
|
|
|
const tempContainer = await TempContainer.container(args.collection);
|
|
|
|
const uploaded = await TempContainer.upload(tempContainer.name, ctx.req, ctx.result, fileOptions);
|
|
|
|
const [uploadedFile] = Object.values(uploaded.files).map(file => {
|
|
|
|
return file[0];
|
|
|
|
});
|
2023-02-20 11:40:13 +00:00
|
|
|
|
2020-12-18 16:23:04 +00:00
|
|
|
const file = await TempContainer.getFile(tempContainer.name, uploadedFile.name);
|
2023-04-14 11:04:40 +00:00
|
|
|
tempFilePath = path.join(file.client.root, file.container, file.name);
|
2020-11-27 12:10:39 +00:00
|
|
|
|
2023-04-14 11:04:40 +00:00
|
|
|
const fileName = `${args.id}.png`;
|
2020-11-27 12:10:39 +00:00
|
|
|
|
2023-04-14 11:04:40 +00:00
|
|
|
await models.Image.resize({
|
|
|
|
collectionName: args.collection,
|
|
|
|
srcFile: tempFilePath,
|
|
|
|
fileName: fileName,
|
|
|
|
entityId: args.id
|
|
|
|
});
|
|
|
|
} finally {
|
|
|
|
try {
|
|
|
|
await fs.unlink(tempFilePath);
|
|
|
|
} catch (error) { }
|
2020-12-18 16:23:04 +00:00
|
|
|
}
|
|
|
|
};
|
2020-11-27 12:10:39 +00:00
|
|
|
};
|