Predefined Types
Predefined types are not shipped with enolib - they are provided as separate packages, for instance enotype.
There are two ways to use them:
Registering types globally
This is the preferred approach when you re-use types a lot - when you register a type it is made available through the native API.
const enolib = require('enolib');
const { boolean, color } = require('enotype');
enolib.register({ boolean, color });
const document = enolib.parse('#b5b5b5: yes');
document.field('#b5b5b5').booleanKey(); // throws "A boolean is required - allowed values are 'true', 'false', 'yes' and 'no'."
document.field('#b5b5b5').colorKey(); // returns '#b5b5b5'
document.field('#b5b5b5').requiredBooleanValue(); // returns true
document.field('#b5b5b5').requiredColorValue(); // throws "A color is required, for instance '#B6D918', '#fff' or '#01b'."
In this approach you take any of the content query methods in enolib and replace string
with a type you have registered.
Supplying types with queries
This is essentially what's happening above as well, only under the hood. We'll see why this approach is sometimes preferable on the next page, when we define our own custom types.
const enolib = require('enolib');
const { boolean, color } = require('enotype');
const document = enolib.parse('#b5b5b5: yes');
document.field('#b5b5b5').key(boolean); // throws "A boolean is required - allowed values are 'true', 'false', 'yes' and 'no'."
document.field('#b5b5b5').key(color); // returns '#b5b5b5'
document.field('#b5b5b5').requiredValue(boolean); // returns true
document.field('#b5b5b5').requiredValue(color); // throws "A color is required, for instance '#B6D918', '#fff' or '#01b'."
In this approach you remove string
from any content query method and pass the type as a parameter instead.
Next page: Custom Types