structure icon indicating copy to clipboard operation
structure copied to clipboard

Custom types with custom coercions and validations

Open talyssonoc opened this issue 8 years ago • 0 comments

There should be a way to introduce new custom types along with custom coercion and validations for the given type. It could be kind of like:

const { createType, attributes } = require('structure');
const { isPlainObject, isString } = require('lodash');
const GJV = require('geojson-validation');

const GeoJSON = createType({
  test(value) {
    return isPlainObject(value);
  },

  coerce(value) {
    if(isString(value)) {
      return JSON.parse(value);
    }

    throw new TypeError("Value can't be coerced to GEOJson");
  },

  validations: {
    // `required` would be included by default
    feature(validationArgument, value) {
      var valid;
      var details;

      GJV.isFeature(value, (isFeature, errors) => {
        if(isFeature) {
          valid = true;
          return;
        }

        details = errors;
      });

      if(valid) {
        return { valid };
      }

      return {
        errors: { details }
      };
    }
  }
});

const House = attributes({
  location: {
    type: GeoJSON,
    required: true,
    feature: true
  }
})(class House { });

The validation errors could somehow use joi extension feature.

talyssonoc avatar Dec 28 '16 02:12 talyssonoc