Skip to content
This repository has been archived by the owner on Feb 16, 2021. It is now read-only.

Type override for enums #32

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ var TcombType = transform({

## registerFormat(format: string, predicateOrType: (x: any) => boolean | Type): void

Registers a new format.
Registers a new format for string types. If you're using any format in the json-schema you need to register it before the transformation.

**Example**

Expand Down
34 changes: 22 additions & 12 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,31 @@ function and(f, g) {

var types = {
string: function(s) {
var predicate, formatPredicate;

if (s.hasOwnProperty('format')) {
t.assert(
formats.hasOwnProperty(s.format),
'[tcomb-json-schema] Missing format ' +
s.format +
', use the (format, predicate) API'
);

if (t.isType(formats[s.format])) {
return formats[s.format];
}

formatPredicate = formats[s.format];
Copy link
Author

Choose a reason for hiding this comment

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

doing this to preserve the order of the "and" conditions.

}

if (s.hasOwnProperty('enum')) {
if (t.Array.is(s['enum'])) {
return t.enums.of(s['enum']);
} else {
return t.enums(s['enum']);
}
}
var predicate;

if (s.hasOwnProperty('minLength')) {
predicate = and(predicate, fcomb.minLength(s.minLength));
}
Expand All @@ -40,18 +57,11 @@ var types = {
);
}
}
if (s.hasOwnProperty('format')) {
t.assert(
formats.hasOwnProperty(s.format),
'[tcomb-json-schema] Missing format ' +
s.format +
', use the (format, predicate) API'
);
if (t.isType(formats[s.format])) {
return formats[s.format];
}
predicate = and(predicate, formats[s.format]);

if (formatPredicate) {
predicate = and(predicate, formatPredicate);
}

return predicate ? t.subtype(t.String, predicate) : t.String;
},

Expand Down
18 changes: 18 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -447,6 +447,24 @@ describe('transform', function() {
ok(Type.is('a@b'));
ko(Type.is(''));
});

it('should favour format types over any other type', function() {
var TestNumType = t.subtype(Num, function(val) {
return Boolean(~[2, 3].indexOf(val));
});

transform.registerFormat('number-type', TestNumType);

var Type = transform({
type: 'string',
format: 'number-type',
enum: [1, 2]
});
eq(getKind(Type), 'subtype');
ok(Type.meta.type === Num);
ok(Type.is(2));
ko(Type.is(1));
});
});

describe('date format', function() {
Expand Down