78 lines
2.4 KiB
JavaScript
78 lines
2.4 KiB
JavaScript
|
const UserError = require('vn-loopback/util/user-error');
|
||
|
const fs = require('fs-extra');
|
||
|
|
||
|
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
|
||
|
},
|
||
|
{
|
||
|
arg: 'collection',
|
||
|
type: 'string',
|
||
|
description: 'The collection name',
|
||
|
required: true
|
||
|
}],
|
||
|
returns: {
|
||
|
type: 'Object',
|
||
|
root: true
|
||
|
},
|
||
|
http: {
|
||
|
path: `/upload`,
|
||
|
verb: 'POST'
|
||
|
}
|
||
|
});
|
||
|
|
||
|
Self.upload = async ctx => {
|
||
|
const models = Self.app.models;
|
||
|
const fileOptions = {};
|
||
|
const args = ctx.args;
|
||
|
|
||
|
const hasWriteRole = await models.ImageCollection.hasWriteRole(ctx, args.collection);
|
||
|
if (!hasWriteRole)
|
||
|
throw new UserError(`You don't have enough privileges`);
|
||
|
|
||
|
if (process.env.NODE_ENV == 'test')
|
||
|
throw new UserError(`You can't upload images on the test instance`);
|
||
|
|
||
|
// Upload file to temporary path
|
||
|
const container = await getContainer(args.collection);
|
||
|
const uploaded = await models.ImageContainer.upload(container.name, ctx.req, ctx.result, fileOptions);
|
||
|
const [uploadedFile] = Object.values(uploaded.files).map(file => {
|
||
|
return file[0];
|
||
|
});
|
||
|
|
||
|
const file = await models.ImageContainer.getFile(container.name, uploadedFile.name);
|
||
|
const srcFile = `${file.client.root}/${file.container}/${file.name}`;
|
||
|
await models.Image.registerImage(container.name, srcFile, args.id);
|
||
|
};
|
||
|
|
||
|
/**
|
||
|
* Returns a container instance
|
||
|
* If doesn't exists creates a new one
|
||
|
*
|
||
|
* @param {String} name Container name
|
||
|
* @return {Object} Container instance
|
||
|
*/
|
||
|
async function getContainer(name) {
|
||
|
const models = Self.app.models;
|
||
|
let container;
|
||
|
try {
|
||
|
container = await models.ImageContainer.getContainer(name);
|
||
|
} catch (err) {
|
||
|
if (err.code === 'ENOENT') {
|
||
|
container = await models.ImageContainer.createContainer({
|
||
|
name: name
|
||
|
});
|
||
|
} else throw err;
|
||
|
}
|
||
|
|
||
|
return container;
|
||
|
}
|
||
|
};
|