Reputation: 1000
I have a "post"-model in strongloop loopback with some properties:
Is it possible to use the model validations in strongloop loopback, but only when I want to publish the post, not when I save it?
Upvotes: 1
Views: 798
Reputation: 3396
Set up a custom post.saveOrPublish()
remote method that only calls post.isValid()
when post.publish === true
. Or use the built-in persistedModel.save()
for everything without validation and use a custom post.publish()
remote method for when you actually click the publish button, which would trigger your validation code before calling save()
.
saveOrPublish
example: (not tested, just a rough idea):
module.exports = function(Post) {
Post.saveOrPublish = function(post, cb) {
if(post.publish) {
post.isValid(function(valid){
if(valid) {
Post.upsert(post, function(err, post) {
if(err) {cb(err, null);}
cb(null, post);
});
} else {
cb(new Error('Publishing requires a valid post.'), post)
}
});
} else {
Post.upsert(post, function(err, post) {
if(err) {cb(err, null);}
cb(null, post);
});
}
};
// don't forget the remote method def
Post.remoteMethod('saveOrPublish',
{
accepts: [{
arg: 'post',
type: 'object'
}],
returns: {
arg: 'result',
type: 'object'
},
http: {verb: 'post'}
}
);
};
Upvotes: 2