Git Product home page Git Product logo

frisker's Introduction

frisker

Quick and declarative object validation with TypeScript with simple objects

Why?

When building APIs I will need to validate the request.body or request.query object to ensure it conforms to a type.
I have done this in the past with varying amount of rigor, robustness, and verbosity.

I wanted a clear, yet terse way to solve this problem that was still robust and not overly repetitive.

Requirements

TypeScript 4+

Installation

> yarn add frisker

Usage

Frisker can check for a complete or partial match of an object to a validator object.
Validator objects are real objects declared using the as const syntax that closely resembles a TypeScript type or interface.
The objects can be deeply nested and composed together using the object spread syntax.

Objects are comprised the values:

  • Primitives
    • 'string'
    • 'number'
    • 'boolean'
    • 'any'
    • 'unknown'
  • Optional Primitives
    • 'string?'
    • 'number?'
    • 'boolean?'
    • 'any?'
    • 'unknown?'
  • A single element tuple with a primitive or an object which represents an array
    • [Primitive] | [Object]
  • An optional array of primitives
    • [OptionalPrimitive]
    • I.e. ['string?'] | ['number?'] | ['boolean?']
  • Objects containing all of the previous types of values
  • { [key: string]: Primtive | [Primitive] | [Object] | Object }
  • A tuple of string literals represents a string literal
    • [...string[]]
    • E.g. ['user', 'guest', 'admin']

This is a fairly shallow example using all of the available "types"

export const user = {
  id: 'string',
  name: { first: 'string', last: 'string', alias: 'string' },
  union: ['admin', 'user', 'guest'],
  age: 'number',
  isAdmin: 'boolean',
  permissions: ['string'],
  groups: [{ id: 'string', name: 'string' }],
  alias: 'string?', // Optional string
  previousAliases: ['string?'], // Optional array
} as const

export type User = UnwrapBody<typeof user>

Type Guard

function isValid(type: Validator, input: any)

Frisker can be used as a Type Guard:

// Example using an express handler:
import { Request, Response } from 'express'
import { isValid } from 'frisker'
import { user } from './types'

export function ({ body }: Request, res: Response) {
  if (!isValid(user, body)) {
    return res.status(400).json({ message: 'Bad request' })
  }

  // body is now a User type which is inferred from the first parameter is isValid()
  if (!body.permissions.includes('users')) {
    return res.status(403).json({ message: 'Not allowed' })
  }

  return res.json({ message: 'ok' })
}

Type Assertion

function assertValid(type: Validator, input: any, partial?: boolean)

The assertValid function will throw if the input does not conform to the validator.
When combined with an error handling middleware, the assertion helper can reduce boilerplate as seen in earlier examples:

import { RequestHandler } from 'express'
import { assertValid } from 'frisker'

/**
 * A helper for passing errors to the error middleware
 */
function wrap(handler: RequestHandler) {
  const wrapped: RequestHandler = async (req, res, next) => {
    try { await handler(req, res, next) }
    catch (ex) { next(ex) }
  }

  return wrapped
}

const body = { username: 'string', password: 'string' } as const

export const register = wrap((req, res) => {
  assertValid(body, req.body)

  // The req.body object will now be the type you expect and be safe to use
  await createAccount(req.body.username, req.body.password)
  res.json({ true })
})

Partial Type Guard

function isValidPartial(type: Validator, input: any)
import { isValidPartial } from 'frisker'
import { user } from './types' // From the previous example

export function handler({ body, params }: Request, res: Response) {
  if (!isValidPartial(user.name, body)) {
    return res.status(400).json({ message: 'Bad request' })
  }

  await updateName(params.id, body)
  res.json({ message: 'ok' })
}

Configurable Validation

function validateBody(type: Validator, input: any, options: Options)

Using the validateBody() function you can get more detail information about the validation

Options

  • notThrow: boolean: Defaults to false
    • the validateBody function throws by default with a message containing all of the errors
    • Provide true if you want an array of the errors
  • partial: boolean
    • Will only validate properties provided in the object provided for comparison

frisker's People

Contributors

seikho avatar

Stargazers

Jeffi avatar Tom avatar John Clema avatar

Watchers

James Cloos avatar  avatar  avatar

Forkers

luke-john

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.