Type-safe API layer with Axios, Aspida, and composition api.
- Create a directory for each endpoint in /api directory
- Create an endpoint type definition file
- run
yarn run build:api
- Access to the whole auto generated endpoints by
useApi()
composition
// api/types.ts
export type Post = {
UserId: number
title: string
body: string
}
export type PostsListItem = {
UserId: number
id: number
title: string
body: string
}
// /api/posts/index.ts
import { DefineMethods } from 'aspida'
import { Post, PostsListItem } from '~/api/types'
export type Methods = DefineMethods<{
get: {
resBody: PostsListItem[]
}
post: {
reqBody: Post
resBody: Post
}
}>
// app.vue
<template>
<div>
<h1>Hello World!</h1>
<button @click="getPosts">Get Posts</button>
</div>
</template>
<script lang="ts" setup>
const getPosts = async () => {
const response = await useApi().posts.get()
}
</script>