Parses form and query parameter data based on TypeBox schemas
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.
Install with your preferred dependency manager:
npm install typebox typebox-form-parser
yarn add typebox typebox-form-parser
pnpm add typebox typebox-form-parser
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.
From data and query parameters have limited ability to express data. This library employs the following constraints:
null
value."false"
, "off"
, and empty string are interpreted as false
; all other non-empty string values are interpreted as true
.MIT License. Copyright © 2023 Joseph T. Lapp
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4