hminghe / nuxt-unapi

Full-stack API for Nuxt 3.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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
  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.
  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.

License:MIT License


Languages

Language:TypeScript 90.8%Language:Vue 9.2%