I have a loopback-js API.
In it I have a products-model, which is rather complex, with many related models. (metadata, technical requirements, tags, domains, targetAudience, ...)
I'm writing a CMS, and I want the users to be able to copy the products easily, and then just alter some small things, because many of the data is the same for all those products.
Is there an easy way to do this in Loopback JS? E.g product.saveAs();
The only way I see it is to get the data from a product, then delete the id's and insert the data as a new product in the database, and then do the same for all the related models...
Since I couldn't find an easy answer on the web, I've come up with a mixin that can be implemented with a Model. The mixin defines a duplicate method, which duplicates the model by inspecting the model definition, so it's traversing the relation-tree, to duplicate or link related items as well:
mixin file in common/mixins/duplicate.js
var async = require('async');
Update your model-config:
Define in model where needed, that you want to use the mixin:
Use at own risk
It's far from perfect but for now, it's good enough for what I need. Maybe someone else can use this as well.
Currently it copy's the model data itself, (which includes foreign keys of belongsTo relations, and embedded models), hasMany (recursively) and hasToAndBelongsToMany (not-recursively). If you want hasManyThrough functionality, better add an extra hasmany-relation to the 'through-table', that will be duplicated instead.
Things I might add in the future: