talyssonoc / structure

A simple schema/attributes library built on top of modern JavaScript

Home Page:https://structure.js.org/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Custom types with custom coercions and validations

talyssonoc opened this issue · 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.