keithwhor / nodal

API Services Made Easy With Node.js

Home Page:http://www.nodaljs.com/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Validate the related model / Promise in validators

pptp opened this issue · comments

commented

There is no way to add a validator in order to check wheather the related model exists (or, for example, it has some state).

We can add a validator the following way:

User.validates('post_id', 'must be valid', v => v && (v + '').match(/.+@.+\.\w+/i));

The third parameter is a callback. If this callback returns falsy the saving process interrupts and we catch an error.

For example, I have a model UserGroup.
Before creating the User model I should check if the UserGroup model with the following attribute UserGroup.id = User.usergroup_id exists.
In this case we cannot implement this feature using models validation because we can do this checking only after fetching the UserGroups model, however, the validator should return boolean:

User.validates('usergroup_id', 'usergroup doesnot exists', v => UserGroup.find(v, ug => /* aaaarrrrgh! */));

I think it will be better to allow validators return not only callbacks but Promises as well.
If it is possible to put a Promise in validator, we can write something like this:

User.validates('usergroup_id', 'usergroup doesnot exists', v =>  {
  let resolve;
  let reject;
  const result = new Promise((_resolve, _reject) => {
    resolve = _resolve;
    reject = _reject;
  });

  UserGroup.find(v, ug => {
    if (ug) {
      resolve(ug);
    } else {
      reject();
    }
  })

  return result;
});

So, this problem can be solved on the Database level by checking indexes.
Yet, for example, if we should validate wheather UserGroup.open is true the simpliest way is using Promises.

What do you think about it?

Thanks,
Mike

commented

Anyway, you an error in documentation. You wrote:

User.verifies('Must not have duplicate email', (email, callback) => {
  User.findBy('email', email, (err, user) => {
    callback(!user); // true if user isn't found, false otherwise
  });
});

But method verifies has 3 attributes:

static verifies(field, message, fnAction) {