Skip to content

Commit

Permalink
Add Joi.func().class()
Browse files Browse the repository at this point in the history
  • Loading branch information
wswoodruff committed Oct 7, 2017
1 parent 15810d6 commit 60852a2
Show file tree
Hide file tree
Showing 3 changed files with 68 additions and 2 deletions.
3 changes: 2 additions & 1 deletion lib/language.js
Expand Up @@ -73,7 +73,8 @@ exports.errors = {
arity: 'must have an arity of {{n}}',
minArity: 'must have an arity greater or equal to {{n}}',
maxArity: 'must have an arity lesser or equal to {{n}}',
ref: 'must be a Joi reference'
ref: 'must be a Joi reference',
class: 'must be a class'
},
lazy: {
base: '!!schema error: lazy schema must be set',
Expand Down
13 changes: 12 additions & 1 deletion lib/types/func/index.js
Expand Up @@ -62,7 +62,6 @@ internals.Func = class extends ObjectType.constructor {
});
}


ref() {

return this._test('ref', null, function (value, state, options) {
Expand All @@ -74,6 +73,18 @@ internals.Func = class extends ObjectType.constructor {
return this.createError('function.ref', null, state, options);
});
}

class() {

return this._test('class', null, function (value, state, options) {

if ((/^\s*class\s/).test(value.toString())) {
return value;
}

return this.createError('function.class', null, state, options);
});
}
};

module.exports = new internals.Func();
54 changes: 54 additions & 0 deletions test/types/function.js
Expand Up @@ -366,3 +366,57 @@ describe('func', () => {
], done);
});
});

describe('func().class()', () => {

it('should differentiate between classes and functions', (done) => {

const classSchema = Joi.object({
_class: Joi.func().class()
});

const testFunc = function () {};
const testClass = class MyClass {};

Helper.validate(classSchema, [
[{ _class: testClass }, true],
[{ _class: testFunc }, false, null, {
message: 'child "_class" fails because ["_class" must be a class]',
details: [{
message: '"_class" must be a class',
path: ['_class'],
type: 'function.class',
context: { key: '_class', label: '_class' }
}]
}]
], done);
});

it('refuses class look-alikes and bad values', (done) => {

const classSchema = Joi.object({
_class: Joi.func().class()
});

Helper.validate(classSchema, [
[{ _class: ['class '] }, false, null, {
message: 'child "_class" fails because ["_class" must be a Function]',
details: [{
message: '"_class" must be a Function',
path: ['_class'],
type: 'function.base',
context: { key: '_class', label: '_class' }
}]
}],
[{ _class: null }, false, null, {
message: 'child "_class" fails because ["_class" must be a Function]',
details: [{
message: '"_class" must be a Function',
path: ['_class'],
type: 'function.base',
context: { key: '_class', label: '_class' }
}]
}]
], done);
});
});

0 comments on commit 60852a2

Please sign in to comment.