@chrstntdd/valita-validator
TypeScript icon, indicating that this package has built-in type declarations

0.0.2 • Public • Published

Valita validator middleware for Hono

Main CI

Validator middleware using Valita for Hono applications. Define your schemas with Valita and validate requests.

Valita is particularly well suited for the Cloudflare Workers platform where resources are limited.

Usage

As plain middleware

import { Hono } from "hono"
import * as v from "@badrap/valita"
import { valitaValidator } from "@chrstntdd/valita-validator"

let app = new Hono()

let schema = v.object({ name: v.string() })

app.post("/hello", valitaValidator("json", { schema }), async (ctx) => {
	let { name } = ctx.req.valid("json")

	return ctx.json({ your: name })
})

Combine middlewares to validate multiple components of the request.

import { Hono } from "hono"
import * as v from "@badrap/valita"
import { valitaValidator } from "@chrstntdd/valita-validator"

let app = new Hono()

let pathSchema = v.string()
let bodySchema = v.object({ details: v.string() })

app.post(
	"/item/:id",
	valitaValidator("param", { schema: pathSchema }),
	valitaValidator("json", { schema: bodySchema }),
	async (ctx) => {
		let { id } = ctx.req.valid("param")
		let { details } = ctx.req.valid("json")

		return ctx.json({ id, details })
	},
)

You can use the hook based API instead to control the failure case.

import { Hono } from "hono"
import * as v from "@badrap/valita"
import { valitaValidator } from "@chrstntdd/valita-validator"

let app = new Hono()

let schema = v.object({ name: v.string() })

app.post(
	"/hooks",
	valitaValidator("json", { schema }, async (r, ctx) => {
		if (!r.success) {
			return ctx.text("Tea", 418)
		}
		let { name } = r.data
		return ctx.json({ your: name })
	}),
)

Package Sidebar

Install

npm i @chrstntdd/valita-validator

Weekly Downloads

0

Version

0.0.2

License

MIT

Unpacked Size

9.15 kB

Total Files

8

Last publish

Collaborators

  • chrstntdd