66 lines
2.1 KiB
JavaScript
66 lines
2.1 KiB
JavaScript
let 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: 'tags', 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]));
|
|
|
|
let createTax = `REPLACE INTO vn.itemTaxCountry (itemFk, countryFk, taxClassFk)
|
|
SELECT ?, countryFk, taxClassFk
|
|
FROM vn.itemTaxCountry WHERE itemFk = ?`;
|
|
promises.push(Self.rawSql(createTax, [newItem.id, origin.id]));
|
|
|
|
await Promise.all(promises);
|
|
return newItem.id;
|
|
} catch (err) {
|
|
throw new UserError(err);
|
|
}
|
|
};
|
|
};
|