Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any alternative ajv(json-schema validator) for deno?

Tags:

deno

I'm looking for a ajv-like json schema validator for deno. Wondering is there any alternative?

like image 921
Eric Miao Avatar asked May 21 '20 05:05

Eric Miao


2 Answers

You don't need an alternative, you can use ajv.

Ajv provides a bundle for browsers: https://cdnjs.cloudflare.com/ajax/libs/ajv/6.12.2/ajv.min.js

All you need to do is download it, save it to your project and add: export default Ajv at the bottom of the file.

ajv.js

/* ajv 6.12.2: Another JSON Schema Validator */
!function(e){if("object"==typeof exports&&"undefined"!=typeof module) /*....... */
//# sourceMappingURL=ajv.min.js.map

export default Ajv;

index.js

import Ajv from './ajv.js'

const ajv = new Ajv({allErrors: true});

const schema = {
  "properties": {
    "foo": { "type": "string" },
    "bar": { "type": "number", "maximum": 3 }
  }
};

function test(data) {
  const valid = validate(data);
  if (valid) console.log('Valid!');
  else console.log('Invalid: ' + ajv.errorsText(validate.errors));
}


const validate = ajv.compile(schema);

test({"foo": "abc", "bar": 2});
test({"foo": 2, "bar": 4});

Remember that Deno is a JavaScript runtime, so any code which uses plain JavaScript, you'll be able to use it with very little modification, in this case just export default Ajv

like image 116
Marcos Casagrande Avatar answered Sep 30 '22 09:09

Marcos Casagrande


You have some options to use none-deno modules.

The easiest way is to use a service like esm.sh and import it like:

import Ajv from 'https://esm.sh/[email protected]';
import addFormats from 'https://esm.sh/[email protected]';
const ajv = new Ajv({allErrors: true});
addFormats(ajv);

esm.sh even provides .d.ts definitions if available, so you can import types as well.

import Ajv, {ValidateFunction} from 'https://esm.sh/[email protected]';
const validate: ValidateFunction = new Ajv().compile(schema);

In some cases, you can even import the raw typescript file directly from git. But Ajv imports json files directly, which deno does not support atm.

like image 39
Nemo64 Avatar answered Sep 30 '22 09:09

Nemo64