Skip to content

Commit

Permalink
Fix redesign api (#4)
Browse files Browse the repository at this point in the history
feat: redesign api and rebench
  • Loading branch information
ahungrynoob authored Oct 28, 2021
1 parent 1557579 commit f73fec6
Show file tree
Hide file tree
Showing 7 changed files with 87 additions and 277 deletions.
4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ version = "0.1.0"
crate-type = ["cdylib"]

[dependencies]
jsonschema = {version = "0.12.2", default-features = false }
napi = {version = "1", features = ["serde-json"] }
jsonschema = { version = "0.13.1", default-features = false, features = [ "draft201909" ] }
napi = {version = "1", features = ["serde-json", "napi5"] }
napi-derive = "1"
serde_json = "1"

Expand Down
109 changes: 43 additions & 66 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,37 @@

> A node package based on jsonschema-rs for performing JSON schema validation.
## Bench
**[ajv](https://github.com/ajv-validator/ajv) is much faster than this lib.**
### Hardware
```
Model Name: MacBook Pro
Model Identifier: MacBookPro16,1
Processor Name: 6-Core Intel Core i7
Processor Speed: 2.6 GHz
Number of Processors: 1
Total Number of Cores: 6
L2 Cache (per Core): 256 KB
L3 Cache: 12 MB
Hyper-Threading Technology: Enabled
Memory: 32 GB
```
### Result
```
Running "Validate Sync" suite...
Progress: 100%
@node-rs/jsonschema::validate:
2 642 863 ops/s, ±1.42% | slowest, 92.86% slower
ajv::validate:
36 997 776 ops/s, ±0.46% | fastest
Finished 2 cases!
Fastest: ajv::validate
Slowest: @node-rs/jsonschema::validate
```

## Install

```
Expand All @@ -30,17 +61,17 @@ yarn add @node-rs/jsonschema

## Usage
```javascript
const { isValidSync, validateSync, isValid, validate } = require("@node-rs/jsonschema");
const { compile } = require("@node-rs/jsonschema");

const schema = JSON.stringify({
const schema = {
type: 'object',
properties: {
foo: { type: 'integer' },
bar: { type: 'string' },
},
required: ['foo'],
additionalProperties: false,
})
};

const input = JSON.stringify({
foo: 1,
Expand All @@ -52,75 +83,21 @@ const exceptionInput = JSON.stringify({
bar: 1,
})

const validator = compile(schema);

// check whether the input meet schema
const result = isValidSync(input, schema);
const result = validator(input);
console.log(result); // true

try {
validateSync(exceptionInput, schema);
}catch(e){
// it will throw error if input doesn't meet schema
console.log(e.message); // Validation error: 1 is not of type "string"; Instance path: /bar; \nValidation error: "abc" is not of type "integer"; Instance path: /foo; \n
}

// promise version of isValidSync
isValid(input, schema).then((result) => {
console.log(result); // true
})

// promise version of validateSync
validate(input, schema).then(() => {
console.log("feel good and input meet schema");
}).catch((e) => {
// it will reject if input doesn't meet schema
console.log(e.message); // Validation error: 1 is not of type "string"; Instance path: /bar; \nValidation error: "abc" is not of type "integer"; Instance path: /foo; \n
})
const result = validator(exceptionInput);
console.log(result); // false
```

## API
```typescript
export const isValidSync: (input: string, schema: string) => boolean

export const validateSync: (input: string, schema: string) => void

export const isValid: (
input: Buffer | string | ArrayBuffer | Uint8Array,
schema: Buffer | string | ArrayBuffer | Uint8Array,
) => Promise<boolean>

export const validate: (
input: Buffer | string | ArrayBuffer | Uint8Array,
schema: Buffer | string | ArrayBuffer | Uint8Array,
) => Promise<null>
```
## Bench
### Hardware
```
Model Name: MacBook Pro
Model Identifier: MacBookPro16,1
Processor Name: 6-Core Intel Core i7
Processor Speed: 2.6 GHz
Number of Processors: 1
Total Number of Cores: 6
L2 Cache (per Core): 256 KB
L3 Cache: 12 MB
Hyper-Threading Technology: Enabled
Memory: 32 GB
```
### Result
```
Running "Validate Sync" suite...
Progress: 100%
@node-rs/jsonschema::validateSync:
105 138 ops/s, ±2.04% | fastest
ajv::validateSync:
178 ops/s, ±2.46% | slowest, 99.83% slower
export declare class JSONSchema {
isValid(input: any): boolean
}

Finished 2 cases!
Fastest: @node-rs/jsonschema::validateSync
Slowest: ajv::validateSync
export const compile: (schema: any) => (input: string) => boolean
```
34 changes: 7 additions & 27 deletions __test__/index.spec.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
import test from 'ava'

import { isValidSync, validateSync, isValid, validate } from '../index'
import { compile } from '../index'

const schema = JSON.stringify({
const schema = {
type: 'object',
properties: {
foo: { type: 'integer' },
bar: { type: 'string' },
},
required: ['foo'],
additionalProperties: false,
})
}

const correctData = JSON.stringify({
foo: 1,
Expand All @@ -22,28 +22,8 @@ const exceptionData = JSON.stringify({
bar: 1,
})

test('isValidSync function from native code', (t) => {
t.assert(isValidSync(correctData, schema))
t.assert(!isValidSync(exceptionData, schema))
})

test('validateSync function from native code', (t) => {
t.notThrows(() => validateSync(correctData, schema))
t.throws(() => validateSync(exceptionData, schema))
})

test('isValid async function from native code', async (t) => {
const trueValue = await isValid(correctData, schema)
t.assert(trueValue)
const falseValue = await isValid(exceptionData, schema)
t.assert(!falseValue)
})

test('validate async function from native code', async (t) => {
await t.notThrowsAsync(validate(correctData, schema))
const error = await t.throwsAsync(validate(exceptionData, schema))
t.is(
error.message,
`Validation error: 1 is not of type "string"; Instance path: /bar; \nValidation error: "abc" is not of type "integer"; Instance path: /foo; \n`,
)
test('isValid function from native code', (t) => {
const compiled = compile(schema)
t.assert(compiled(correctData))
t.assert(!compiled(exceptionData))
})
23 changes: 12 additions & 11 deletions benchmark/bench.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
import Ajv from 'ajv'
import b from 'benny'

import { validateSync } from '../index'
import { compile } from '../index'

const fooObject = {
const input = {
foo: 1,
bar: 'abc',
}
const foo = JSON.stringify(fooObject)

const fooSchemaObject = {
const schema = {
type: 'object',
properties: {
foo: { type: 'integer' },
Expand All @@ -18,20 +17,22 @@ const fooSchemaObject = {
required: ['foo'],
additionalProperties: false,
}
const fooSchema = JSON.stringify(fooSchemaObject)

const ajv = new Ajv()
const ajvValidator = ajv.compile(schema)
const nativeValidator = compile(schema)
const inputStr = JSON.stringify(input)

async function run() {
await b.suite(
'Validate Sync',

b.add('@node-rs/jsonschema::validateSync', () => {
validateSync(foo, fooSchema)
b.add('@node-rs/jsonschema::validate', () => {
nativeValidator(inputStr)
}),

b.add('ajv::validateSync', () => {
const ajv = new Ajv()
const validate = ajv.compile(fooSchemaObject)
validate(fooObject)
b.add('ajv::validate', () => {
ajvValidator(input)
}),

b.cycle(),
Expand Down
16 changes: 4 additions & 12 deletions index.d.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,5 @@
export const isValidSync: (input: string, schema: string) => boolean
export declare class JSONSchema {
isValid(input: any): boolean
}

export const validateSync: (input: string, schema: string) => void

export const isValid: (
input: Buffer | string | ArrayBuffer | Uint8Array,
schema: Buffer | string | ArrayBuffer | Uint8Array,
) => Promise<boolean>

export const validate: (
input: Buffer | string | ArrayBuffer | Uint8Array,
schema: Buffer | string | ArrayBuffer | Uint8Array,
) => Promise<null>
export const compile: (schema: any) => (input: string) => boolean
23 changes: 3 additions & 20 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,7 @@
const { loadBinding } = require('@node-rs/helper')

const {
isValid: _isValid,
validate: _validate,
isValidSync: _isValidSync,
validateSync: _validateSync,
} = loadBinding(__dirname, 'jsonschema', '@node-rs/jsonschema')
const { compile: _compile } = loadBinding(__dirname, 'jsonschema', '@node-rs/jsonschema')

module.exports.isValid = function isValid(input, schema) {
return _isValid(Buffer.from(input), Buffer.from(schema))
}

module.exports.isValidSync = function isValidSync(input, schema) {
return _isValidSync(input, schema)
}

module.exports.validate = function validate(input, schema) {
return _validate(Buffer.from(input), Buffer.from(schema))
}

module.exports.validateSync = function uncompress(input, schema) {
return _validateSync(input, schema)
module.exports.compile = function (schema) {
return _compile(JSON.stringify(schema))
}
Loading

0 comments on commit f73fec6

Please sign in to comment.