Validate and Clean data made easy!
easy-vac is a JavaScript library which helps you validate and clean data.
All you need is:
easy-vac can be installed via:
npm install --save easy-vac
EasyVAC
Schema can’t contains functions or undefined
! Valid types in easy-vac schema:
Let’s start with a simple example:
import { VObject, VArray, VEnum, VTuple, VACError } from "easy-vac"
const OrderItem = VObject({
product: { type: "string", required: true },
count: { type: "int", default: 1, minimum: 1 },
})
const Order = VObject.required({
guest: { type: String }, // <- type can also be "string"
items: { type: VArray({ items: { type: OrderItem },
minItems: 1,
maxItems: 3 })
}
})
The javascript code defined 2 object schemas: OrderItem
and Order
.
In TypeScript, the corresponding types can be written as:
interface OrderItem {
product: string
count: number // integer, value >= 1, default is 1
}
interface Order {
guest: string,
items: OrderItem[], // array of OrderItem. 1 <= array length <= 3
}
You don’t need to write that! Types are automatically inferred from your code by TypeScript and easy-vac.
Put the JavaScript code into playground, hover your cursor on the Schema names and see the magic.
You may also define other types with VTuple, VEnum and makeVType. See Define new Types.
Now we’ve defined the schemas. Time to VAC some data!
var incoming = {
_id: "xxxxx",
guest: 12345,
items: [
{ product: "Ice Cream" },
{ product: "Toast", count: 3 },
]
}
var order = Order.vac(incoming)
console.log(order)
There is a _id
which is unexpected. guest
is a number rather than string, and items[0]
lacks count
.
However, in your schemas, _id
is not defined, guest
of Order is defined as a string, count
of OrderItem has a default value.
easy-vac will validate and clean the data. Print data
and you will find that those minor issues are fixed:
{
"guest": "12345",
"items": [
{ "product": "Ice Cream", "count": 1 },
{ "product": "Toast", "count": 3 }
]
}
If there are major problems, Order.vac(...)
will throw a [VACError][].
var incoming = {
items: [
{ product: "Ice Cream" },
{ product: "Toast", count: 3 },
{ product: "Beer", count: -1 },
{ product: "Pizza", count: 0 },
]
}
try {
var data = Order.vac(incoming) // <- this throws a VACError
console.log(data) // <- will not reach this line
} catch (err) {
if (err instanceof VACError) {
console.error("easy-vac found Error!")
err.errors.forEach(it => {
console.error(`- ${it.label}: ${it.error.message}`)
})
}
}
Console will print this in red:
easy-vac found Error!
- root.guest: required property is missing
- root.items[2].count: value too small
- root.items[3].count: value too small
- root.items: array length is too long
Don't miss the playground and 7 examples