salix/services/loopback/common/methods/item/clone.js

66 lines
2.1 KiB
JavaScript
Raw Normal View History

let UserError = require('../../helpers').UserError;
2018-02-22 12:40:23 +00:00
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 => {
2018-02-22 12:40:23 +00:00
let filter = {
where: {
id: itemId
},
include: [
{relation: 'tags', scope: {order: 'priority ASC', include: {relation: 'tag'}}}
2018-02-22 12:40:23 +00:00
]
};
2018-02-22 12:40:23 +00:00
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]));
2018-05-15 12:02:16 +00:00
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]));
2018-02-22 12:40:23 +00:00
await Promise.all(promises);
return newItem.id;
} catch (err) {
throw new UserError(err);
}
};
};