# frisker

> > Quick and declarative object validation with TypeScript with simple objects

Latest version **1.7.0** (published 2023-03-24) · MIT license · 0 weekly downloads

## Install

```sh
npm install frisker
pnpm add frisker
yarn add frisker
bun add frisker
```

## Health

**Score 25/100 (F)** — status: abandoned.

Positive: has types; no vulnerabilities; high quality score.

Warnings: low downloads; no esm support.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 1.7.0 |
| Published | 2023-03-24 |
| First published | 2021-04-22 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | CommonJS |
| Dependencies | 1 |
| Unpacked size | 102.9 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 3 |
| Author | Carl Winkler |
| Maintainers | seikho |
| Keywords | body, request, valid, validator, typescript, checker |

## Links

- npm: https://www.npmjs.com/package/frisker
- Repository: https://github.com/seikho/frisker
- Homepage: https://github.com/seikho/frisker#readme
- Issues: https://github.com/seikho/frisker/issues
- npm.io page: https://npm.io/package/frisker

## Dependencies (1)

- [@types/node](https://npm.io/package/@types/node.md) ^15.12.2

## Alternatives

- [vest](https://npm.io/package/vest.md) — 50.1K weekly downloads
- [@regle/core](https://npm.io/package/@regle/core.md) — 47.0K weekly downloads
- [typeof-arguments](https://npm.io/package/typeof-arguments.md) — 12.5K weekly downloads
- [@lokalise/projects-engine-contracts](https://npm.io/package/@lokalise/projects-engine-contracts.md) — 978 weekly downloads
- [@osjwnpm/nam-laboriosam-quibusdam](https://npm.io/package/@osjwnpm/nam-laboriosam-quibusdam.md) — 70 weekly downloads

## Recent versions

- 1.7.0 (latest) — 2023-03-24
- 1.6.2 — 2023-03-21
- 1.6.1 — 2023-03-21
- 1.6.0 — 2023-02-19
- 1.5.0 — 2022-02-25
- 1.4.4 — 2021-06-17
- 1.4.3 — 2021-06-17
- 1.4.2 — 2021-06-09
- 1.4.1 — 2021-06-09
- 1.4.0 — 2021-06-08
- 1.2.0 — 2021-06-03
- 1.1.0 — 2021-04-27
- 1.0.1 — 2021-04-22
- 1.0.0 — 2021-04-22

## README

# 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

```sh
> 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"

```ts
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

```ts
function isValid(type: Validator, input: any)
```

Frisker can be used as a **Type Guard**:

```ts
// 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

```ts
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:

```ts
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

```ts
function isValidPartial(type: Validator, input: any)
```

```ts
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

```ts
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

---
_Source: https://npm.io/package/frisker · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
