json-safeguard
A lib that effectively safeguards data types, and automatic completion of the required words.
Quick Start
$ npm i --save json-safeguard
const safeguard = require('json-safeguard')
const schema = {
name: 'string'
}
const data = {
name: 'Heleth'
}
safeguard(schema, data)
More complicated verification
const schema = {
name: 'string*',
age: 'number',
excellent: (value, data) => {
const subjects = data.subjects || []
const isExcellent = subjects.every(item => item.achievement >= 90)
return isExcellent === value ? true : {
state: false,
messages: [
`${data.name} is ${isExcellent ? '' : 'n\'t'} excellent`
]
}
},
subjects: [
{
name: 'string*',
achievement: 'number*'
}
],
hobby: 'string[]*'
}
const data = {
name: 'Heleth',
age: 23,
excellent: false,
subjects: [
{
name: 'Javascript',
achievement: 95.5
},
{
name: 'Python',
achievement: 90
},
{
name: 'Swift',
achievement: 93
}
]
}
safeguard(schema, data)
Schema
Basic Types
Declare the type of field in the Schema to verify the data.
const schema = {
_string: 'string'
}
Types | Value | Description |
---|
Boolean | boolean | True or false. |
Number | number | Integer or float. |
String | string | |
Array | [] | Array of any. |
Boolean-Array | boolean[] | Array of boolean only. |
Number-Array | number[] | Array of number only. |
String-Array | string[] | Array of string only. |
Required and Automatic Completion
You can specify some required fields with *
, such as number[]*
. When the field is empty, it will automatically completion.
Types | Value | Description |
---|
Required | * | Check if this field exists. |
For example:
const safeguard = require('json-safeguard')
const schema = {
_string_array: 'string[]*'
}
const data = {}
safeguard(schema, data)
Custom Verify
Types | Value | Description |
---|
Custom Verify | (value, data) => any | Use a custom function to check if this field meets the requirements. Return a boolean to tell the result of the check directly. You can also return an object and set the custom message and default value, please read below for details. |
const safeguard = require('json-safeguard')
const schema = {
_number: (value, data) => value < 20
}
const data = {
_number: 15
}
safeguard(schema, data)
Result
Property | Description | Type | Default |
---|
state | Verification state | boolean | - |
message | Error message | string | '' |
completed_data | Safe data containing required arrays and objects | object | {} |
License
MIT