Helpers for document validation in sync function


#1

Hello,

as far as I understood, the sync function is the right place for validating incoming documents. I find myself writing a lot of helpers like these:

  function allowFields(fields) {
    fields.push('_id');
    fields.push('_rev');
    fields.push('type');
    fields.push('_revisions');

    for (var key in doc) {
      if (fields.indexOf(key) == -1) {
        forbidden('field ' + key + ' not allowed');
      }
    }
  }

  function checkTypes(dict, soft) {
    function ass(cond) {
      if (!cond) {
        forbidden('Wrong type for ' + key);
      }
    }

    for (var key in dict) {
      var parts = key.split('.');
      var val = doc;
      for (var idx in parts) {
        var part = parts[idx];
        if (!(part in val)) {
          if (!soft) {
            forbidden('missing field', key);
          }
        }
        val = val[part];
      }
      var type = dict[key];
      //var val = doc[key];

      switch(type) {
        case 'string':
            ass(typeof val === 'string');
            break;
        case 'date':
            ass(typeof val === 'number');
            //ass(!isNaN(Date.parse(val)));
            break;
      }
    }
  }

Therefore, I have two questions:

  1. Does a large sync function impact write performance (i.e. is it parsed every time a write occurs)? If not, could I paste a javascript library for validation into my sync function? Do you know a library that is well suited for doing this?
  2. Are there plans to integrate some validation functionality into couchbase sync gateway (typescript or json syntax could be used, for example)?

#2

does nobody know whether a large sync function impacts performance, i.e. whether it is parsed on every write request?


#3

@foobar123

Currently the sync function is parsed on every document update.

There is a community PR that parses the sync function just once, the PR is slated for review after the release of Sync Gateway 1.3.