Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Custom types with custom coercions and validations #15

Open
talyssonoc opened this issue Dec 28, 2016 · 0 comments
Open

Custom types with custom coercions and validations #15

talyssonoc opened this issue Dec 28, 2016 · 0 comments

Comments

@talyssonoc
Copy link
Owner

talyssonoc commented Dec 28, 2016

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant