Simple data validation and utility library.
npm install @knowark/validarkjsimport {
Abstract,
Interactor,
Query,
cache,
Cacher,
check,
fallible,
format,
dedent,
outdent,
grab,
has,
merge,
need,
stringify,
structure,
validate
} from '@knowark/validarkjs'Use validate(schema, instance, options?) to validate and transform data.
import { validate } from '@knowark/validarkjs'
const schema = {
'*name': String,
age: parseInt
}
const result = validate(schema, { name: 'Ada', age: '37' })
// { name: 'Ada', age: 37 }- Schema values can be:
- validation functions (for scalars)
- nested schema objects
- arrays with one validator/schema for item validation
- Prefix a key with
*to make it required. - Use
:=to define aliases. The output key is the left-most alias. - Alias matching is evaluated right-to-left when multiple aliases are present.
const schema = {
'*first_name:=firstname:=firstName': String,
'*score:=totalScore:=points': parseInt,
contact: {
'*email': String
},
tags: [String],
addresses: [{ '*street': String, city: String }]
}validate(..., options) supports:
strict(boolean, defaultfalse):false: unknown properties are ignoredtrue: unknown properties are reported as errors
eager(boolean, defaultfalse):false: collect all issues and throw one aggregate errortrue: throw on the first issue found
dialect(string):'jsonschema': use the JSON Schema validator instead of default function-schema validation
When dialect: 'jsonschema' is used, validate() validates against a JSON Schema
and returns the original instance (without value transformation).
const schema = {
type: 'object',
properties: { age: { type: 'number' } }
}
validate(schema, { age: 33 }, { dialect: 'jsonschema' })
// { age: 33 }Default mode is non-eager (eager: false), so all issues are collected.
const schema = { '*name': String, '*age': parseInt }
try {
validate(schema, [{ age: 'young' }])
} catch (error) {
// error is AggregateError
// error.name === 'ValidationError'
// error.issues is an array of issue objects
console.log(error.message)
}Use eager mode to fail fast:
validate(schema, [{ age: 'young' }], { eager: true })
// throws first validation errorValidation functions can:
- return transformed values
- return an
Errorobject - throw an
Error
In non-eager mode, returned/thrown errors are included in the collected issues.
const schema = {
levels: [parseInt],
contact: {
'*phone': String
}
}
const records = [{ levels: ['1', '2'], contact: { phone: 123456 } }]
const [result] = validate(schema, records)
// { levels: [1, 2], contact: { phone: '123456' } }- Returns
valueif valid. - Throws
CheckErrorif value is falsy. - If
options.typeis provided, validates that type.
import { check } from '@knowark/validarkjs'
check('ok')
check(42, { type: Number })Retrieves a value from an object.
keycan be a stringkeycan be a class constructor (triescamelCaseNamethenClassName)keycan be[name, Class]
import { grab } from '@knowark/validarkjs'
const value = grab({ element: 'content' }, 'element')
const fallback = grab({}, 'missing', 777)Ensures the instance has the requested truthy properties.
import { has } from '@knowark/validarkjs'
has({ name: 'Ada', age: 37 }, ['name', 'age'])Returns fallback if it matches the expected type, otherwise throws NeedError.
import { need } from '@knowark/validarkjs'
const value = need(String, 'default')Wraps a promise and returns [error, result].
import { fallible } from '@knowark/validarkjs'
const [error, result] = await fallible(Promise.resolve(123))Deep-merges plain object branches recursively.
import { merge } from '@knowark/validarkjs'
const merged = merge({ a: 1, b: { c: 2 } }, { b: { d: 3 } })
// { a: 1, b: { c: 2, d: 3 } }import { format, dedent, outdent } from '@knowark/validarkjs'
format('${name} is ${age}', { name: 'Ada', age: 37 })
dedent(' a\n b')
outdent(' a\n b')- default:
String(structure) 'json':JSON.stringify'graphql'/'gql': GraphQL-like serialization
import { stringify } from '@knowark/validarkjs'
stringify({ hello: 'world' }, 'json')- Clones JS objects/arrays into plain data
- Parses GraphQL source strings into structure objects when format is
'graphql'/'gql', or when source starts withquery,mutation, orsubscription
import { structure } from '@knowark/validarkjs'
const data = structure({ a: 1 })Caches async function/object method results.
- Works for async functions and async object methods
- Supports
size,lifetime,methods, and customcacher - Exposes
Cacherabstract interface
import { cache } from '@knowark/validarkjs'
const cachedFetch = cache(async (id) => ({ id }))
await cachedFetch(1)Base class for abstract hierarchies. Prevents direct instantiation and provides abstract(...) helper.
Use for input/output validated workflows.
import { Interactor } from '@knowark/validarkjs'
class CreateUser extends Interactor {
schema = {
input: { '*name': String },
output: { '*id': String, '*name': String }
}
async perform (input) {
return { id: 'u1', name: input.name }
}
}Specialized Interactor with a properties attribute defaulting to null.
MIT