1

I have a "post"-model in strongloop loopback with some properties:

  • title
  • text
  • tags
  • category
  • published (true or false)

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?

Ernie
  • 972
  • 1
  • 10
  • 23

1 Answers1

2

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'}
    }
  );


};
notbrain
  • 3,366
  • 2
  • 32
  • 42
  • Thx! When I use the upsert (PUT) instead of POST to create a new Post in combination with `validateUpsert:false`, validation doesn't get executed, that's what I want, then I call it manually in my remote publish method – Ernie Jul 13 '15 at 09:32