fefe
![codecov](https://codecov.io/gh/paperhive/fefe/branch/master/graph/badge.svg)
Validate, sanitize and transform values with proper types.
🔎 Validation: checks a value (example: check if value is string)
⚙ Sanitization: if a value is not valid, try to transform it (example: transform value to Date
)
🛠️ Transformation: transforms a value (example: parse JSON)
🔌 Schemas are functions: easily extendable
🔎 Validation example
Validation only checks the provided value and returns it with proper types.
import { validate } from 'fefe'
const validatePerson = validate.object({ name: validate.string() })
const person = validatePerson({ name: 'Leia' })
validatePerson({ foo: 'bar' })
You can also use fefe
to define your types easily:
type Person = ReturnType<typeof validatePerson>
⚙️ Sanitization example
import { sanitize, validate } from 'fefe'
const sanitizeMovie = validate.object({
title: validate.string(),
releasedAt: sanitize.date()
})
type Movie = ReturnType<typeof sanitizeMovie>
const book: Book = sanitizeMovie({
title: 'Star Wars',
releasedAt: '1977-05-25T12:00:00.000Z'
})
Then book
equals { title: 'Star Wars', releasedAt: Date(1977-05-25T12:00:00.000Z) }
(releasedAt
now is a date).
🛠️ Transformation example
This is an example that can be applied to parsing environment variables or query string parameters. Note how easy it is to apply a chain of functions to transform and validate a value (here we use ramda
).
import { validate } from 'fefe'
import { pipe } from 'ramda'
const parseConfig = validate.object({
gcloudCredentials: pipe(
validate.string(),
JSON.parse,
validate.object({ key: validate.string() })
),
whitelist: pipe(validate.string(), str => str.split(','))
})
type Config = ReturnType<typeof parseConfig>
const config: Config = parseConfig({
gcloudCredentials: '{"key":"secret"}',
whitelist: 'alice,bob'
})
Then config
will equal { gcloudCredentials: { key: 'secret'}, whitelist: ['alice', 'bob'] }
.
Note: you can use validations in transformations.