Skip to content

olton/guardian

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

38 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Guardian

Data guard and validation library. Validate user input with Guardian.

Install

npm i @olton/guardian

Using

import {parse, string, required, email, object} from "@olton/guardian"

const schema = string()
let value = parse(schema, "123")

console.log(value); // -> 123

let value = parse(schema, 123) // -> throw error


let value = safeParse(schema, 123) // -> return obj with error
if (!value.ok) {
    console.log(value.error)
}

let value = safeParse(schema, "123") // -> return obj with data
if (value.ok) {
    console.log(value.output)
}

let schema = object({
    name: pipe(required("Name Required"), string()),
    email: pipe(string(), email("Please enter a valid email address"))
})

const res0 = parse(schema, {
    name: "Vasya Pupkin",
    email: "vasya@pupkin.com"
}) // -> Ok

const res1 = parse(schema, {
    name: "",
    email: "vasya@pupkin.com"
}) // -> Error "Name Required"

const res2 = parse(schema, {
    name: "Serhii Pimenov",
    email: "vasya_pupkin.com"
}) // -> Error "Please enter a valid email address"

Parsing

  • parse - Throw error when invalid data
  • safeParse - Return special object with .output when all ok, and .error when invalid data

Pipes

  • pipe - run guarders left to right
  • compose - run guarders right to left
import {pipe, string, email} from "@olton/guardian"

const scheme1 = pipe(string(), email()) // left to right
const scheme2 = compose(email(), string()) // right to left

Create a simple schema

import {parse, object, visa, mastercard, string, email} from "@olton/guardian"

const schema1 = string()
const data1 = parse(schema1, "123")

const schema2 = pipe(required(), email())
const data2 = parse(schema2, "vasya@pupkin.com")

Create complex schema

import {parse, object, visa, mastercard, string, email} from "@olton/guardian"

const schema = object({
    name: string(),
    email: email(),
    cards: object({
        visa: visa(),
        mastercard: mastercard()
    })
})

const data = parse(schema, {...})

Guardians

  • array
  • base64
  • between
  • bigint
  • boolean
  • bytes
  • creditCard (visa, mastercard, discover, jbc, diners, unionPay, americanExpress)
  • date
  • digits
  • domain
  • email
  • empty
  • endsWith
  • finite
  • float
  • func
  • hexColor
  • imei
  • instance
  • integer
  • ip (ipv4, ipv6)
  • length
  • maxValue
  • minValue
  • notNull
  • notNumber
  • number
  • pattern
  • promise
  • required
  • safeInteger
  • startsWith
  • string
  • symbol
  • unknown
  • url

About

Data guard and validation library

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published