61 lines
1.8 KiB
JavaScript
61 lines
1.8 KiB
JavaScript
var UserError = require('../../helpers').UserError;
|
|
|
|
module.exports = Self => {
|
|
Self.remoteMethod('clone', {
|
|
description: 'clone item',
|
|
accessType: 'WRITE',
|
|
accepts: [{
|
|
arg: 'id',
|
|
type: 'number',
|
|
required: true,
|
|
description: 'origin itemId',
|
|
http: {source: 'path'}
|
|
}],
|
|
returns: {
|
|
arg: 'id',
|
|
description: 'new cloned itemId'
|
|
},
|
|
http: {
|
|
path: `/:id/clone`,
|
|
verb: 'post'
|
|
}
|
|
});
|
|
|
|
Self.clone = async itemId => {
|
|
let filter = {
|
|
where: {
|
|
id: itemId
|
|
},
|
|
include: [
|
|
{relation: 'itemTag', scope: {order: 'priority ASC', include: {relation: 'tag'}}}
|
|
]
|
|
};
|
|
|
|
try {
|
|
let origin = await Self.findOne(filter);
|
|
let copy = JSON.parse(JSON.stringify(origin));
|
|
|
|
delete copy.id;
|
|
delete copy.itemTag;
|
|
|
|
let newItem = await Self.create(copy);
|
|
let promises = [];
|
|
|
|
let createBotanical = `INSERT INTO vn.itemBotanical (itemFk, botanical, genusFk, specieFk)
|
|
SELECT ?, botanical, genusFk, specieFk
|
|
FROM vn.itemBotanical ib WHERE itemFk = ?`;
|
|
promises.push(Self.rawSql(createBotanical, [newItem.id, origin.id]));
|
|
|
|
let createTags = `INSERT INTO vn.itemTag (itemFk, tagFk, value, priority)
|
|
SELECT ?, tagFk, value, priority
|
|
FROM vn.itemTag WHERE itemFk = ?`;
|
|
promises.push(Self.rawSql(createTags, [newItem.id, origin.id]));
|
|
|
|
await Promise.all(promises);
|
|
return newItem.id;
|
|
} catch (err) {
|
|
throw new UserError(err);
|
|
}
|
|
};
|
|
};
|