shapetype
v6.0.0
Published
Define shapes and types and use them for data/structure validation
Downloads
7
Maintainers
Readme
ShapeType
Define shapes and types and use them for data/structure validation.
API
Type
Types allow you to define what type of data you expect a value to be.
Type Definitions:
Type.bool()
for a boolean valueType.number()
for a numberType.string()
for a stringType.value(val1[, val2, val3])
for an exact match of one or more values.Type.datetime()
for a Date objectType.null()
for a null valueType.undefined()
for an undefined valueType.object()
for an object literal- Note: You'll often want to use a
Shape
instead ofType.object()
(see below).
- Note: You'll often want to use a
Type.array()
for an array.- Note: You'll often want to use
arrayOf()
instead ofType.array()
(see below).
- Note: You'll often want to use
Type.custom(isType[, name])
allows you to define a custom Type.isType
should be a method that accepts a value and returns a boolean.name
is an optional value that will be stored asType.value
internally.- Example:
const EmailType = Type.custom(val => isEmail(val), 'EMAIL');
Type Methods
.compare(val)
: returnstrue
/false
whetherval
matches the Type.- Example:
EmailType.compare('[email protected]') ~ true
EmailType.compare('test=test') ~ false
- Example:
.validate(val)
: returns an validation object assessing whetherval
matches the Type.- Example:
EmailType.validate('[email protected]') ~ { invalidTypeFields: [] }
EmailType.validate('test=test') ~ { invalidTypeFields: [ 'test=test' ] }
- Example:
.or()
: allows you to chain a list of Types together- Example:
const assignedTo = Type.number().or(Type.null())
- Example:
arrayOf(Type|Shape)
Indicates that there is an array of the provided value.
When validate
is called on a value defined by arrayOf()
, an empty array will be returned if all values pass their tests. An array of validation objects with an additional index
key will be returned if any of the array's values do not pass their test.
optional()
Wraps a Type, Shape, or ArrayContainer to indicate that a given field isn't required in a shape definition. Tests will still pass if the value is omitted.
const Event = defineShape({
id: Type.number(),
name: Type.string(),
createdBy: optional(User),
scheduledAt: optional(Type.datetime()),
guests: arrayOf(User),
defineShape({})
Returns a Shape
when provided with an object of key/Type
pairs.
const User = defineShape({
id: Type.number(),
name: Type.string(),
assignedTo: Type.number().or(Type.null()),
})
You can also nest Shapes within other Shapes.
const Event = defineShape({
id: Type.number(),
name: Type.string(),
createdBy: User,
guests: arrayOf(User),
})
Shape Methods
.compare(obj)
returnstrue
/false
whetherobj
matches the pattern defined by theShape
.- Example:
User.compare({ id: 2, name: 'Test', assignedTo: 12 }) ~ true
User.compare({ id: 2, name: 'Test', assignedTo: 'Joe' }) ~ false
- Example:
.partialCompare(obj)
same as.compare(obj)
, but only tests for the keys present inobj
.- Example:
User.partialCompare({ id: 2 }) ~ true
User.partialCompare({ id: 'Toby' }) ~ false
- Example:
.validate(obj)
returns a validation object reflecting the test results of the individual values defined by the shape.- The validation object consists of three arrays:
missingFields
: fields that are defined in the Shape but missing from the objectextraFields
: fields that are not defined in the Shape but are included in the object- invalidTypeFields: fields that don't match the Type defined by the Shape
- Example:
User.validate({ id: 2, name: 'Test', assignedTo: 12 }) ~ { missingFields: [], extraFields: [], invalidTypeFields: [] }
User.validate({ id: 2, name: 'Test', assignedTo: 'Joe' }) ~ { missingFields: [], extraFields: [], invalidTypeFields: [ 'assignedTo' ] }
User.validate({ name: 'Test', assignedTo: 12 }) ~ { missingFields: [ 'id ], extraFields: [], invalidTypeFields: [] }
User.validate({ id: 2, name: 'Test', assignedTo: 12, isDog: true }) ~ { missingFields: [], extraFields: [ 'isDog' ], invalidTypeFields: [] }
- The validation object consists of three arrays:
.partialValidate(obj)
same as.validate(obj)
, but only tests for the keys present inobj
.- Example:
User.partialValidate({ id: 2 }) ~ { missingFields: [], extraFields: [], invalidTypeFields: [] }
User.partialCompare({ id: 'Toby' }) ~ { missingFields: [], extraFields: [], invalidTypeFields: [ 'id' ] }
- Example:
extendShape(existingShape, obj)
Allows you to build off of an existing shape. A new Shape
instance will be returned.
const Rectangle = defineShape({
length: Type.number(),
width: Type.number(),
});
const Box = extendShape(Rectangle, { height: Type.number() });
Additional Examples
Usage in testing
You can use Shapes with a testing library such as Jest for type assertions.
it ('should return the user', () => {
expect(UserShape.compare(user)).toEqual(true);
});
Usage in field validation
const missingFields = UserShape.validate(user));
if (missingFields.length > 0){
onError(missingFields);
} else {
onSave(user);
}