Parse, validate and transform data with confidence in nuxt using zod

Related tags

Vue.js nuxt-parse
Overview

nuxt-parse

npm version npm downloads GitHub stars License Follow us on Twitter Join our Discord

A nuxt focused package to make data validation and parsing easy. This package follows the design philosophy of the article parse, don't validate. It uses zod for parsing data from the user, APIs, your own functions, ...

Full tsdoc-documentation is here: https://nuxt-sidebase-parse.sidebase.io

Moved here from original mono-repo

Features

  • ✔️ Validate Data using zod
  • ✔️ Deserialize and Serialize user, backend, api data
  • ✔️ Helpers focused on Nuxt 3 usage and developer experience

Usage

npm i @sidebase/nuxt-parse

Then, e.g., in your code:

  • Make an arbitrary parser, e.g., to deserialize data from an API:
    • Example with valid data:
      import { z, makeParser } from "@sidebase/nuxt-parse"
      
      // Define the expected response schema
      const responseSchema = z.object({
          uuid: z.string().uuid(),
      })
      
      // Perform the request, use `makeParse` to pass a transformer for the data
      const { data, error } = await useFetch('https://httpbin.org/uuid', {
          transform: makeParser(responseSchema),
      })
      
      console.log(`data is ${data.value}`)
      // -> `data is {"uuid":"f8df921c-d7f3-43c1-ac9b-3cf5d4da2f7b"}`
      
      console.log(`error is ${error.value}`)
      // -> `error is false`
    • Example with invalid data:
      import { z, makeParser } from "@sidebase/nuxt-parse"
      
      // Define the expected response schema
      const responseSchema = z.object({
          uuid: z.string().uuid(),
      })
      
      // Perform the request, use `makeParse` to pass a transformer for the data
      const { data, error } = await useFetch('https://httpbin.org/ip', {
          transform: makeParser(responseSchema),
      })
      
      console.log(`data is ${data.value}`)
      // -> `data is null`
      
      console.log(`error is ${error.value}`)
      // -> `error is true`
  • Handle user data in an endpoint:
    import { defineEventHandler } from 'h3'
    import type { CompatibilityEvent } from 'h3'
    import { z, parseParamsAs, parseBodyAs } from "@sidebase/nuxt-parse"
    
    // Define the schema of the parameters you expect the user to provide you with
    const paramsSchema = z.object({
        id: z.string().uuid(),
    })
    
    // Define the schema of the body you expect the user to provide you with
    const bodySchema = z.object({
        name: z.string(),
        age: z.number()
    })
    
    // Get a nice type to use throughout your code and components
    type RequestBody = z.infer<typeof bodySchema>
    
    export default defineEventHandler(async (event: CompatibilityEvent) => {
        // Validate and then get the parameters
        // This automatically throws a nice HTTP 422 error with more information if the data is invalid
        const params = parseParamsAs(event, paramsSchema)
    
        let body: RequestBody;
        try {
            body = parseBodyAs(event, paramsSchema)
        } catch(error) {
            // Fallback, this avoids automatic raising + returning of the HTTP 422 error
            body = {
                name: 'Bernd',
                age: 88
            }
        }
    
        // Return the full entity
        return {
            id: params.id,
            ...body
        }
    })
  • Parse any data:
    import { z, parseDataAs } from "@sidebase/nuxt-parse"
    
    const parsedData = await parseDataAs({ test: "1" }, z.object({ test: z.number() )}))
    // -> throws! `"1"` is not a number, but a string!
    
    const parsedData = await parseDataAs({ test: 1 }, z.object({ test: z.number() )}))
    console.log(parsedData)
    // -> output: `{ test: 1 }`
    
    
    const parsedData = await parseDataAs({ test: "1" }, z.object({ test: z.string().transform(v => parseInt(v)) )}))
    console.log(parsedData)
    // -> output: `{ test: 1 }` (we used `.transform` to ensure that we get a number)
  • Also works with async data, e.g., when fetching from another API or DB:
    import { z, parseDataAs } from "@sidebase/nuxt-parse"
    
    const fakeDatabaseQuery = async () => { id: 1 }
    const parsedData = await parseDataAs(fakeDatabaseQuery, z.object({ id: z.number() )}))
    
    console.log(parsedData)
    // -> output: `1`

Documentation

Full tsdoc-documentation is here: https://nuxt-sidebase-parse.sidebase.io

This module exports:

  • parseBodyAs: Parse body of h3 event
  • parseParamsAs: Parse params of h3 event
  • parseQueryAs: Parse query of h3 event
  • parseCookieAs: Parse cookies of h3 event
  • parseHeaderAs: Parse header of h3 event
  • parseDataAs: Parse sync or async data
  • makeParser: Make your own parser (see example above)
  • z: zod, the library used for parsing

Development

  • Run npm run test to generate type stubs
  • Run npm run lint to run eslint
  • Run npm run type to run typescheck via tsc
  • Run npm publish to run build and publish the package
You might also like...

Batteries-included, zero-config Ionic integration for Nuxt

Nuxt Ionic Ionic integration for Nuxt ✨ Changelog 📖 Read the documentation ▶️ Online playground Features ⚠️ nuxt-ionic is currently a work in progres

Dec 28, 2022

Http-proxy middleware for Nuxt 3.

nuxt-proxy Http-proxy middleware for Nuxt 3. Installation npm install nuxt-proxy Usage export default defineNuxtConfig({ modules: ['nuxt-proxy'],

Dec 30, 2022

Nuxt 3 module for Web3.js

nuxt-web3.js Nuxt 3 module for Web3.js. Installation npm install nuxt-web3.js Usage export default defineNuxtConfig({ modules: ['nuxt-web3.js'], })

Dec 16, 2022

OpenID-Connect(OIDC) integration module for nuxt 3.0.

Nuxt OpenID-Connect OpenID-Connect(OIDC) integration module for nuxt 3.0. Features An Nuxt 3 module. OIDC integration ( implemetation base openid-clie

Dec 24, 2022

🔎 Meilisearch module for Nuxt 3

🔎 Meilisearch module for Nuxt 3

nuxt-meilisearch Meilisearch module for Nuxt Features Nuxt 3 Easy integration with MeilisearchJS lib Support for Vue Algolia Vue 3 InstantSearch compo

Dec 26, 2022

A modern, zero-dependency uptime monitoring tool & status page based on GitHub Actions & Nuxt Content v2.

A modern, zero-dependency uptime monitoring tool & status page based on GitHub Actions & Nuxt Content v2.

StatusBase Uptime monitoring tool & beautiful status pages Powered by Nuxt Content v2! Free • Open Source • Notification View Demo · Report Bug · Requ

Jul 5, 2022

Nuxt eureka client

Nuxt eureka client

May 30, 2022

✉️ Nuxt module for first class integration with popular newsletter providers

✉️ Nuxt module for first class integration with popular newsletter providers

nuxt-newsletter Newsletter module for Nuxt 3 ✨ Release Notes 📖 Read the documentation Features Nuxt 3 ready Easy integration with Mailchimp, Revue, B

Jan 5, 2023

🔎 Algolia module for Nuxt

🔎 Algolia module for Nuxt

@nuxtjs/algolia Algolia module for Nuxt ✨ Release Notes 📖 Read the documentation Features Nuxt 3 ready Easy integration with Algolia Handy composable

Jul 28, 2022
Comments
  • Removed index page of docs from mobile sidebar

    Removed index page of docs from mobile sidebar

    Closes # .

    Checklist:

    • [ ] issue number linked above after pound (#)
      • replace "Closes " with "Contributes to" or other if this PR does not close the issue
    • [ ] manually checked my feature / checking not applicable
    • [ ] wrote tests / testing not applicable
    • [ ] attached screenshots / screenshot not applicable
    opened by zoey-kaiser 0
  • docs: switch to docus, rewrite ReadMe

    docs: switch to docus, rewrite ReadMe

    Closes N/A.

    I also wanted to ask what the current state of the tsdoc page is? Will we remove it? Also TODO: Link new nuxt-parse documentation as the repo website! 😄

    Checklist:

    • [X] issue number linked above after pound (#)
      • replace "Closes " with "Contributes to" or other if this PR does not close the issue
    • [X] manually checked my feature / checking not applicable
    • [X] wrote tests / testing not applicable
    • [X] attached screenshots / screenshot not applicable
    opened by zoey-kaiser 0
Releases(0.3.0)
  • 0.3.0(Nov 14, 2022)

    What's Changed

    • Updated to RC13 by @zoey-kaiser in https://github.com/sidebase/nuxt-parse/pull/1
    • Removed Nuxt, updated h3, bumped version to 0.3.0 by @zoey-kaiser in https://github.com/sidebase/nuxt-parse/pull/2

    New Contributors

    • @zoey-kaiser made their first contribution in https://github.com/sidebase/nuxt-parse/pull/1

    Full Changelog: https://github.com/sidebase/nuxt-parse/compare/0.2.7...0.3.0

    Source code(tar.gz)
    Source code(zip)
  • 0.2.7(Oct 20, 2022)

Owner
sidebase
High quality open-source software to kick-start your development
sidebase
This repo contains a fully configured nuxt 3 instance supporting TypeScript and several considered as useful libraries, fully configured and ready to use in real world projects!

Nuxt 3 Starter This repo contains a fully configured nuxt 3 instance supporting TypeScript and several considered as useful libraries, fully configure

Ali Soueidan 26 Dec 27, 2022
Nuxt 3 starter with Algolia, Storyblok, and Indexer

Nuxt 3 with Storyblok CMS and Algolia Search (incl. automatic indexing) This is a demo repository for an article in Dev.to. We recommend to look at th

Jakub Andrzejewski 5 May 24, 2022
⚡️ Minimal GraphQL Client + Code Generation for Nuxt

nuxt-graphql-client ⚡️ Minimal GraphQL Client + Code Generation for Nuxt ⚡️ Minimal GraphQL Client + Code Generation for Nuxt Features Zero Configurat

Dizzy 245 Dec 27, 2022
Nuxt.js module to use Unleash toggle feature services

nuxt-unleash Nuxt.js module to use Unleash toggle feature services ?? Release Notes Features Use $unleash to access and handle your Unleash feature fl

Juanjo Conejero 15 Dec 3, 2022
Easy generation of OpenGraph & Twitter meta-tags in Nuxt 3 📋

nuxt-social-tags Easy generation of OpenGraph & Twitter meta-tags in Nuxt 3 ✨ Release Notes ?? Read the documentation Features Nuxt3 ready Composables

Conner 19 Dec 17, 2022
Easily connect your Nuxt 3 application with LogSnag 📰

Nuxt LogSnag ?? LogSnag integration for Nuxt 3 ✨ Release Notes Features Nuxt 3 ready Easy integration Handy composables TypeScript support Setup Insta

Conner 13 Apr 28, 2022
End-to-end typesafe APIs with tRPC.io in Nuxt applications.

tRPC-Nuxt End-to-end typesafe APIs with tRPC.io in Nuxt applications. The client above is not importing any code from the server, only its type declar

Robert Soriano 231 Dec 30, 2022
A modern, zero-dependency uptime monitoring tool & status page based on GitHub Actions & Nuxt Content v2.

StatusBase Uptime monitoring tool & beautiful status pages Powered by Nuxt Content v2! Free • Open Source • Notification View Demo · Report Bug · Requ

zernonia 208 Dec 27, 2022
🔎 Algolia module for Nuxt

@nuxtjs/algolia Algolia module for Nuxt ✨ Release Notes ?? Read the documentation Features Nuxt 3 ready Easy integration with Algolia Handy composable

Nuxt Community 128 Jan 7, 2023
Nuxt 3 module for Kirby's Query Language API

nuxt-kql Kirby KQL module for Nuxt 3. This module provides a useKql composable, which under the hood uses useFetch. Thus, KQL query fetching in your N

Johann Schopplich 25 Dec 15, 2022