You are viewing the docs for the newest version. You can view the docs for 0.5 here

User data

This is an example on how to 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 withconst paramsSchema = z.object({    id: z.string().uuid(),})// Define the schema of the body you expect the user to provide you withconst bodySchema = z.object({    name: z.string(),    age: z.number()})// Get a nice type to use throughout your code and componentstype 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    }})