Custom types with custom coercions and validations
talyssonoc opened this issue · comments
Talysson de Oliveira Cassiano commented
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.