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

Feature/extend joi validation #67

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ Please file issues for other unsupported features.
- `refineType(type, format)` - an (optional) function to call to apply to type based on the type and format of the JSON schema.
- `extensions` - an array of extensions to pass [joi.extend](https://github.com/hapijs/joi/blob/master/API.md#extendextension).
- `strictMode` - make schemas `strict(value)` with a default value of `false`.
- `warnOnEmpty` - outputs a warning message on console if a schema is empty or considered empty - https://json-schema.org/latest/json-schema-core.html#rfc.section.4.3.1
- `extendValidation` - gives the ability to extend the default joi validation schema produced by `enjoi`. Works for the root schema and for references.
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Concerned this sounds a lot like joi extensions.

Copy link
Contributor Author

@maldimirov maldimirov Dec 14, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It sound similar, but the key is in the details. Maybe it can be called extendJoiSchemas with a bit addition to the description:

extendJoiSchemas - gives the ability to extend the default Joi validation schema produced by Enjoi. Works for the root schema and for referenced ones. In contrast to extensions which extends on a per type level, this options extends on a per schema level. Useful when you want the extend the Joi schema produced by Enjoi, without defining a new custom type.


Example:

Expand Down Expand Up @@ -216,3 +218,55 @@ const schema = Enjoi.schema({
]
});
```

### Extend Joi validation

Example with root schema:
```javascript
const schema = Enjoi.schema({
type: 'object',
properties: {
title: {type: 'string'},
},
definitions: {
Name: {
type: 'string'
}
}
}, {
extendValidation: {
'#': Joi.object().keys({title: Joi.string().max(3)}),
}
});
```

Example with root schema and references:
```javascript
const schema = Enjoi.schema({
type: 'object',
properties: {
title: {type: 'string'},
name: {$ref: '#/definitions/Name'},
address: {$ref: 'definitions#/Address'}
},
definitions: {
Name: {
type: 'string'
}
}
}, {
subSchemas: {
'definitions': {
'Address': {
'type': 'string'
}
}
},
extendValidation: {
'#': Joi.object().keys({title: Joi.string().max(3)}),
'#/definitions/Name': Joi.string().max(8),
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hard to use this as an example to illustrate why this is useful. Could use currently supported json-schema to specify.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You are right. What do you think about this example:

const schema = Enjoi.schema({
    type: 'object',
    required: ['min', 'max'],
    properties: {
        lower: {type: 'number', minimum: 5},
        higher: {type: 'number', maximum: 20},
    },
}, {
    extendValidation: {
        '#': Joi.object().keys({
            higher: Joi.number().greater(Joi.ref('lower')),
        }),
    },
});

'definitions#/Address': Joi.string().max(7)
}
});
```

6 changes: 5 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ const optionsSchema = Joi.object({
extensions: Joi.array().items(Joi.object().unknown(true)).allow(null),
refineType: Joi.func().allow(null),
strictMode: Joi.boolean().default(false),
extendValidation: Joi.object().pattern(/^\S*#(\/\S*)*$/, Joi.object().schema()),
warnOnEmpty: Joi.boolean(),
});

const validate = function (schema, options = {}) {
Expand All @@ -34,7 +36,9 @@ exports.defaults = function (defaults = {}) {
types: Object.assign({}, defaults.types, options.types),
extensions: defaults.extensions || [],
refineType: options.refineType || defaults.refineType,
strictMode: options.strictMode || defaults.strictMode
strictMode: options.strictMode || defaults.strictMode,
extendValidation: options.extendValidation || {},
warnOnEmpty: options.warnOnEmpty || true,
};
if (Util.isArray(options.extensions)) {
merged.extensions = merged.extensions.concat(options.extensions);
Expand Down
69 changes: 43 additions & 26 deletions lib/resolver.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,15 @@ const Util = require('util');
const Hoek = require('hoek');

class SchemaResolver {
constructor(root, { subSchemas, types, refineType, strictMode, extensions = [] }) {
constructor(root, { subSchemas, types, refineType, strictMode, extendValidation, warnOnEmpty, extensions = [] }) {
this.root = root;
this.types = types;
this.subSchemas = subSchemas;
this.refineType = refineType;
this.strictMode = strictMode;

this.extendValidation = extendValidation || {};
this.warnOnEmpty = warnOnEmpty || true;

extensions.push({
name: 'allOf',
rules: [{
Expand Down Expand Up @@ -38,46 +40,61 @@ class SchemaResolver {

this.joi = Joi.extend(extensions);
}

extendJoiSchema(joiSchema, ref) {
return this.extendValidation[ref] ?
joiSchema = joiSchema.concat(this.extendValidation[ref]) :
joiSchema;
}

resolve(schema = this.root) {
if (schema.type) {
return this.resolveType(schema);
resolve(schema) {
if (!schema) {
// extend and resolve the root schema
return this.extendJoiSchema(this.resolveSchema(this.root), '#');
}

if (schema.$ref) {
// extend and resolve any referenced schemas
return this.extendJoiSchema(
this.resolveSchema(this.resolveReference(schema.$ref)),
schema.$ref,
);
}

// resolve subschemas
return this.resolveSchema(schema);
}

resolveSchema(schema) {
if (schema.type) {
return this.resolveType(schema);
}
if (schema.anyOf) {
return this.resolveAnyOf(schema);
}

}
if (schema.allOf) {
return this.resolveAllOf(schema.allOf);
}

}
if (schema.oneOf) {
return this.resolveOneOf(schema);
}

}
if (schema.not) {
return this.resolveNot(schema);
}

if (schema.$ref) {
return this.resolve(this.resolveReference(schema.$ref));
}

//if no type is specified, just enum
}
if (schema.enum) {
//if no type is specified, just enum
return this.joi.any().valid(schema.enum);
}

// If schema is itself a string, interpret it as a type
}
if (typeof schema === 'string') {
// If schema is itself a string, interpret it as a type
return this.resolveType({ type: schema });
}
}

//Fall through to whatever.
//eslint-disable-next-line no-console
console.warn('WARNING: schema missing a \'type\' or \'$ref\' or \'enum\': \n%s', JSON.stringify(schema, null, 2));
//TODO: Handle better
// interpret as empty schema and always validate
if (this.warnOnEmpty) {
// eslint-disable-next-line no-console
console.warn('WARNING: schema missing a \'type\' or \'$ref\' or \'enum\': \n%s', JSON.stringify(schema, null, 2));
}
return this.joi.any();
}

Expand Down
54 changes: 54 additions & 0 deletions test/test-options.js
Original file line number Diff line number Diff line change
Expand Up @@ -200,4 +200,58 @@ Test('extensions', function (t) {
Joi.validate('foo', schema, function (error, value) {
t.ok(error, 'error.');
});
});

Test('extending the Joi validation', function (t) {
t.test('extend root, inline and external refs', function(t) {
t.plan(4);

const schema = Enjoi.schema({
type: 'object',
properties: {
title: {type: 'string'},
name: {$ref: '#/definitions/Name'},
address: {$ref: 'definitions#/Address'}
},
definitions: {
Name: {
type: 'string'
}
}
}, {
subSchemas: {
'definitions': {
'Address': {
'type': 'string'
}
}
},
extendValidation: {
'#': Joi.object().keys({title: Joi.string().max(3)}),
'#/definitions/Name': Joi.string().max(8),
'definitions#/Address': Joi.string().max(7)
}
});

const data = {
title: 'mr.',
name: 'John Doe',
address: 'Earth'
};
Joi.validate(data, schema, function (error, value) {
t.ok(!error, 'no error.');
});

Joi.validate({title: 'mister'}, schema, function (error, value) {
t.ok(error, 'error.');
});

Joi.validate({name: 'Jonathan Doe'}, schema, function (error, value) {
t.ok(error, 'error.');
});

Joi.validate({address: 'Earth, Milky Way'}, schema, function (error, value) {
t.ok(error, 'error.');
});
});
});