npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@sidebase/nuxt-parse

v0.3.0

Published

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

Downloads

555

Readme

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