Skip to content

hminghe/nuxt-unapi

Repository files navigation

nuxt-unapi

npm version npm downloads License Nuxt

Full-stack API for Nuxt 3.

Install

  1. Add nuxt-unapi dependency to your project
# Using pnpm
pnpm add -D nuxt-unapi

# Using yarn
yarn add --dev nuxt-unapi

# Using npm
npm install --save-dev nuxt-unapi
  1. Add nuxt-unapi to the modules section of nuxt.config.ts
export default defineNuxtConfig({
  modules: [
    'nuxt-unapi'
  ],

  // Required enable asyncContext
  experimental: {
    asyncContext: true,
  },
})

✨✨✨

Usage

Expose server functions under api/**.ts

// api/user.ts
import { z } from 'zod'

export const getUser = defineApi({
  props: z.number(),
  // id type is number
  async handler (id) {
    return db.user.get(id)
  },
})

export const updateUser = defineApi({
  props: z.object({
    id: z.number(),
    name: z.string(),
    age: z.number().optional()
  }),
  
  // props are secure data validated by Zod.
  async handler (props) {
    return db.user.update(props)  
  }
})

On the client side:

import { getUser, updateUser } from '~/api/user.ts'

const user = await getUser(1)

user.name = 'nuxt-unapi'

const result = await updateUser(user)

Client validate. Zod Docs

updateUser.props.parse(user)

About

Full-stack API for Nuxt 3.

Resources

License

Stars

Watchers

Forks

Packages

No packages published