Home

Awesome

TypeBox Form Parser

Parses form and query parameter data based on TypeBox schemas

API Reference

Introduction

This library interprets HTTP form data and query parameters as objects defined by TypeBox schemas. Given a TypeBox schema and either an instance of FormData or URLSearchParams, the library parses the data as an instance of the schema to the degree that it is able, without also validating the data. To validate the resulting parsed data, pass it to TypeBox's check function or errors function, or use a TypeBox validator.

Installation

Install with your preferred dependency manager:

npm install typebox typebox-form-parser

yarn add typebox typebox-form-parser

pnpm add typebox typebox-form-parser

Usage

The library is documented in the API reference. Here is an example of usage:

import { Type, type TObject } from "@sinclair/typebox";
import { getSchemaInfo, parseFormFields } from "typebox-form-parser";

const schema = Type.Object({
  name: Type.String({ minLength: 2 }),
  nickname: Type.Optional(Type.String({ minLength: 2 })),
  age: Type.Number({ minimum: 13 }),
  siblings: Type.Optional(Type.Integer({ minimum: 0, default: 0 })),
  email: Type.Union([
    Type.String({
      pattern: "^[a-z]+@[a-z]+[.][a-z]+$",
      minLength: 10,
      default: "you@example.com",
    }),
    Type.Null(),
  ]),
  agree: Type.Boolean(),
});

function handleGet(url: URL) {
  const schemaInfo = getSchemaInfo(schema);
  const parsedParams = parseFormFields(url.searchParams, schemaInfo);
  // validate parsedParams against the schema
  // ...
}

function handlePost(request: Request) {
  const schemaInfo = getSchemaInfo(schema);
  const parsedFormData = parseFormFields(request.formData(), schemaInfo);
  // validate parsedFormData against the schema
  // ...
}

You can also attach application-specific information to the cached schema information:

const appSchemaInfo = getSchemaInfo(schema, (schemaInfo) => {
  // derive `extra` from schemaInfo.schema
  return {
    ...schemaInfo,
    extra,
  };
});

Add any number of properties to the schema, with names of your choosing.

Constraints

From data and query parameters have limited ability to express data. This library employs the following constraints:

Behavior

License

MIT License. Copyright © 2023 Joseph T. Lapp