1.0.23 • Published 10 months ago

shape-tape v1.0.23

Weekly downloads
-
License
MIT
Repository
github
Last release
10 months 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.23

10 months ago

1.0.22

1 year ago

1.0.21

1 year ago

1.0.20

1 year ago

1.0.19

1 year ago

1.0.18

1 year ago

1.0.17

1 year ago

1.0.16

1 year ago

1.0.15

1 year ago

1.0.14

1 year ago

1.0.13

1 year ago

1.0.11

2 years ago

1.0.12

2 years ago

1.0.10

2 years ago

1.0.9

2 years ago

1.0.8

2 years ago

1.0.7

2 years ago

1.0.6

2 years ago

1.0.5

2 years ago

1.0.4

2 years ago

1.0.3

2 years ago

1.0.2

2 years ago

1.0.1

2 years ago

1.0.0

2 years ago