1.0.22 • Published 21 days ago

shape-tape v1.0.22

Weekly downloads
-
License
MIT
Repository
github
Last release
21 days ago

shape-tape

About

A TypeScript/JavaScript library to help with runtime validation of structured data.

Consumers define Shapes that represent the structure of their data. Consumers call validateDataShape to validate some data matches their Shape.

Installation

npm install shape-tape

Usage

import { s, validateObjectShape } from "shape-tape"

// Define a shape.
const resourceShape = s.object({
	id: s.string({regex: /^[a-zA-Z0-9\-_]{10}$/}),
	state: s.union([s.literal("pending"), s.literal("active"), s.literal("removed")]),
	createdAt: s.integer()
})

// Validate that some object matches your shape.
const goodData = JSON.parse("{\"id\":\"ui_1zoEJ18\",\"state\":\"active\",\"createdAt\":1700354795466}")
const resource = validateDataShape({ data: goodData, shape: resourceShape })

// Safely access the validated and typed data.
if (resource.state === "active") ...

...

// Data that doesn't match your shape causes a ShapeValidationError.
const badData = JSON.parse("{\"id\":\"\",\"state\":\"active\",\"createdAt\":1700354795466}")
const resource = validateDataShape({ data: badData, shape: resourceShape })
// ^ throws ShapeValidationError "Parameter \"id\" is invalid."

If you're using TypeScript you can use the shape's TypeScript type.

import { ShapeToType } from "shape-tape"

type Resource = ShapeToType<typeof resourceShape>

...

const resource: Resource = ...

Please see the unit test demonstrating this example.

Documentation

Please see the low level documentation for more details.

1.0.22

21 days ago

1.0.21

21 days ago

1.0.20

29 days ago

1.0.19

2 months ago

1.0.18

4 months ago

1.0.17

4 months ago

1.0.16

5 months ago

1.0.15

5 months ago

1.0.14

5 months ago

1.0.13

5 months ago

1.0.11

5 months ago

1.0.12

5 months ago

1.0.10

6 months ago

1.0.9

6 months ago

1.0.8

6 months ago

1.0.7

6 months ago

1.0.6

6 months ago

1.0.5

6 months ago

1.0.4

6 months ago

1.0.3

6 months ago

1.0.2

6 months ago

1.0.1

6 months ago

1.0.0

6 months ago