From 38bf7b6714fc28c814c082c3bd4ac33ec8d97906 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D0=BA=D0=BE=D0=B2=D0=BE=D1=80=D0=BE=D0=B4=D0=B0=20?= =?UTF-8?q?=D0=9D=D0=B8=D0=BA=D0=B8=D1=82=D0=B0=20=D0=90=D0=BD=D0=B4=D1=80?= =?UTF-8?q?=D0=B5=D0=B5=D0=B2=D0=B8=D1=87?= Date: Sat, 20 Jun 2020 00:56:41 +0300 Subject: [PATCH] doc: Parser, not validator --- doc/Parser-not-validator.md | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 doc/Parser-not-validator.md diff --git a/doc/Parser-not-validator.md b/doc/Parser-not-validator.md new file mode 100644 index 00000000..55f96378 --- /dev/null +++ b/doc/Parser-not-validator.md @@ -0,0 +1,36 @@ +# Parser, not validator + +While this package provides API for generating both parsers and validators, parser should be +preferred if that fits your use case. + +## Why? + +Using the parser API ensures that the object is never present in your code in parsed but not +validated form, significantly reducing the number of mistakes that can come from using unvalidated +raw objects. + +Apart from that, it allows some checks in the validation to be fast-tracked for clarity and +performance if the input is known to be from `JSON.parse` and can not contain, e.g. `undefined` +variables. +That fast-tracking could be also enabled via the `isJSON` option of the validator, but it should be +used only when the input is _definitely_ coming from a `JSON.parse` without a reviver. + +## Differences between parser and validator + +`validator(schema, options)` creates a `validate(object)` function which accepts input after it has +been parsed from JSON. It will return either `true` or `false` and errors would be reported as a +property of `validate` function: `validate.errors` (if `includeErrors` option is enabled). + +`parser(schema, options)` creates a similar `parse(string)` function, which accepts a raw string +containing JSON-encoded input, with a few differences: + + 1. If validation succeeds, it returns the parsed object itself, like `JSON.parse(string)` does. + + 2. If validation fails, it will throw instead of returning `false`. + + 3. Validation errors (if enabled) are available as the `err.errors` of the thrown `err` object. + + 4. Parser operates in [strong mode](./Strong-mode.md) by default. To override it, use + `mode: 'default'` option. + +Parsers can be likewise exported to js code by using `parser.toModule()`.