build-system/compile/json-schema/README.md
A file may import a JSON Schema validation function by importing its schema file:
product.schema.json{
"properties": {
// .schema.json files can have comments
"title": {"type": "string"}
},
"required": ["title"]
}
source.jsImport a function from a JSON Schema file, using assert { type: 'json-schema' }:
import validateProduct from './product.schema.json' assert { type: 'json-schema' };
validateProduct({foo: "bar"}); // invalid, returns errrors
validateProduct can have any name since it's the default exported function. It's generated by babel-plugin-transform-json-import.
This function has the following signature:
function validate(data: any, schemaName? string): string[] {}
data is the value to validate.schemaName is optional, and represents the name of the validated object. This is added to error messages. By default, it's the basename of the imported file.The function returns an array of strings representing validation errors. It is empty when valid:
const errors = validateProduct(myProduct);
if (errors.length) {
for (const error of errors) {
console.warn(error);
}
}
We write all JSON schema exactly like the standard spec. However, some schemas can be annotated so that they can be compiled into a special function.
Validating a currency code in JSON Schema requires a long enum of possible values.
In JavaScript we can instead use Intl.NumberFormat. This prevents us from including this long list, in order to reduce output size.
By including the string ISO 4217 (or any that matches /iso[_- ]?4217/i) in the description field, the enum is replaced with a Intl.NumberFormat call in the validation code.
You should also include the full ISO 4217 list of currency codes as enum to ensure schema portability. If the list is not included, or incomplete, compilation will fail. You may copy this list from iso4217.json
{
"description": "https://en.wikipedia.org/wiki/ISO_4217",
"enum": [
"AED",
"...",
"ZWL"
]
}