Allow providing an Ajv instance to Validator
NGTOne opened this issue · comments
AJV has a plugin system, along the lines of the decorator pattern - each plugin exposes a function that modifies an instantiated Ajv
object. However, because the Validator
class only accepts AjvOptions
and then constructs its own, applying plugins requires modifying it at runtime. This is fine (and expected, according to the tests) in straight JavaScript, but in TypeScript violates the provided types, because the Ajv
is not included in the class definition:
// Plugin
import formats from "ajv-formats-draft2019";
const ajv = formats(new Ajv({allErrors: true}));
const validator = new Validator({});
validator.ajv = ajv;
// Yields:
// TS2339: Property 'ajv' does not exist on type 'Validator'.
Either way, this seems a brittle approach, prone to breaking as the library changes. A backwards-compatible solution to this might be something like:
export class Validator {
// Allow passing an Ajv to the constructor
constructor(options: AjvOptions | Ajv);
// Expose the ajv to match the behaviour of the JS implementation
ajv: Ajv;
}
If a non-Ajv
object is provided, the existing behaviour is kept, but otherwise the validator can just use the provided Ajv
wholesale.
Right, I realized that this one's basically a duplicate of #67.