0.0.2 • Published 12 months ago

@chrstntdd/valita-validator v0.0.2

Weekly downloads
-
License
MIT
Repository
github
Last release
12 months ago

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 })
	}),
)
0.0.2

12 months ago

0.0.1

12 months ago

0.0.1-alpha1

12 months ago

0.0.1-alpha0

12 months ago