0.5.3 • Published 4 months ago

h3-zod v0.5.3

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

h3-zod

npm (tag) npm bundle size NPM

Validate h3 and Nuxt requests with zod.

!IMPORTANT
H3 1.8.0 now has built-in runtime + type-safe request utilities, eliminating the need for this module.

Install

npm install zod h3-zod

Usage

Import it like:

import { zh } from 'h3-zod';

// Or

import { useSafeValidatedQuery, useSafeValidatedBody } from 'h3-zod';

Helpers that don't throw when parsing fails:

export default defineEventHandler(async (event) => {
  const query = zh.useSafeValidatedQuery(event, z.object({
    required: z.string()
  }))

  const body = await zh.useSafeValidatedBody(event, z.object({
    optional: z.string().optional(),
    required: z.boolean()
  }))

  const params = zh.useSafeValidatedParams(event, {
    id: z.number()
  })

  if (!params.success) {
    // params.error
  }
})

Helpers that throw error 400 when parsing fails:

export default defineEventHandler(async (event) => {
  const query = zh.useValidatedQuery(event, z.object({
    required: z.string()
  }))

  const body = await zh.useValidatedBody(event, z.object({
    optional: z.string().optional(),
    required: z.boolean()
  }))

  const params = await zh.useValidatedParams(event, {
    id: z.number()
  })
})

You can also pass an object schema:

export default defineEventHandler(async (event) => {
  const body = await zh.useValidatedBody(event, {
    optional: z.string().optional(),
    required: z.boolean()
  })
})

Helper Zod Schemas

zh.boolAsString

  • "true"true
  • "false"false
  • "notboolean" → throws ZodError

zh.checkboxAsString

  • "on"true
  • undefinedfalse
  • "anythingbuton" → throws ZodError

zh.intAsString

  • "3"3
  • "3.14" → throws ZodError
  • "notanumber" → throws ZodError

zh.numAsString

  • "3"3
  • "3.14"3.14
  • "notanumber" → throws ZodError

Usage

const Schema = z.object({
  isAdmin: zh.boolAsString,
  agreedToTerms: zh.checkboxAsString,
  age: zh.intAsString,
  cost: zh.numAsString,
});

const parsed = Schema.parse({
  isAdmin: 'true',
  agreedToTerms: 'on',
  age: '38',
  cost: '10.99'
});

console.log(parsed)
// {
//   isAdmin: true,
//   agreedToTerms: true,
//   age: 38,
//   cost: 10.99
// }

Related

License

MIT

0.5.3

4 months ago

0.5.2

7 months ago

0.5.0

1 year ago

0.5.1

1 year ago

0.4.1

1 year ago

0.4.0

1 year ago

0.4.2

1 year ago

0.3.9

1 year ago

0.3.10

1 year ago

0.3.0

2 years ago

0.2.1

2 years ago

0.3.6

1 year ago

0.3.5

2 years ago

0.2.6

2 years ago

0.3.8

1 year ago

0.3.7

1 year ago

0.3.2

2 years ago

0.3.4

2 years ago

0.2.5

2 years ago

0.3.3

2 years ago

0.2.0

2 years ago

0.1.2

2 years ago

0.1.1

2 years ago

0.1.0

2 years ago

0.0.1

2 years ago