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

68 lines
2.2 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;
delete copy.description;
2018-02-22 12:40:23 +00:00
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]));
2018-06-05 06:24:53 +00:00
let createTags = `INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
SELECT ?, i.tagFk, i.value,i.priority
FROM vn.itemTag i WHERE i.itemFk = ?
ON DUPLICATE KEY UPDATE value = i.value, priority = i.priority`;
2018-02-22 12:40:23 +00:00
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);
}
};
};