Vue3项目中优雅封装API基础接口:getBaseApi设计解析

837 阅读2分钟

在Vue3前端项目中,高效管理API接口是提升开发效率的关键。本文将介绍一种优雅的API基础封装方案——getBaseApi方法,它可以通过​​单次配置​​生成完整的CRUD接口模板,显著减少重复代码并强化类型安全。

设计目标

  1. 标准化接口规范:统一接口路径与方法命名
  2. 类型安全:通过TypeScript泛型支持自定义数据类型
  3. 灵活扩展:允许不同模块覆盖默认参数类型
  4. 开箱即用:5秒生成完整CRUD接口集合

apis目录结构

apis
  --user
    --index.ts
    --type.ts
  --dept
    --index.ts
    --type.ts
// @/apis/user/index.ts
import type * as T from './type'
import { getBaseApi } from '@/apis/base'
import http from '@/utils/http'

export type * from './type'

/** 用户模块 */
export const baseAPI = getBaseApi<T.ListItem>({ baseUrl: '/user' })

// 其他接口
export const getUserRoleList = (params: { id: string }) => {
  return http.get<PageRes<T.UserRoleListItem[]>>('/user/getUserRoleList', params)
}
// @/apis/user/type.ts

export interface ListItem {
  id: string
  name: string
  account: string
  avatar: string
  gender: Gender
  phone: string
  email: string
  createTime: string
  address: string
  proportion: number
  status: Status
  hobbys: string[]
}

export interface UserRoleListItem { ... }

上面代码没有使用export default,是因为对Tree Shaking不友好

使用

import { baseAPI, getUserRoleList } from '@/apis/user'
import type * as T from '@/apis/user' // 获取类型

const userList = ref<T.ListItem[]>([])

// 获取列表
baseAPI.getList({ page: 1, size: 10 })
// 获取详情
baseAPI.getDetail({ id: 'xxx' })
// 新增
baseAPI.add(formData)
// 编辑
baseAPI.update(formData)
// 删除
baseAPI.delete({ ids: ['xx1', 'xx2'] })

使用baseAPI都会有类型提示

image.png

image.png

类型覆盖

image.png

核心代码解析

interface DefaultP {
  GetListParams?: Record<string, any>   // 分页查询参数
  GetDetailParams?: { id: string }      // 详情查询参数
  AddParams?: Record<string, any>       // 新增参数
  UpdateParams?: Record<string, any>    // 更新参数
  DeleteParams?: { ids: string[] }      // 删除参数
}

export function getBaseApi<T, P extends DefaultP = DefaultP>(
  params: { baseUrl: string }
) {
  const { baseUrl } = params;

  return {
    // 获取分页列表
    getList(params?: P['GetListParams'] & { page: number, size: number }) {
      return http.get<PageRes<T[]>>(`${baseUrl}/getList`, params)
    },
    
    // 获取详情
    getDetail(params: P['GetDetailParams']) {
      return http.get<T>(`${baseUrl}/getDetail`, params)
    },
    
    // 新增数据
    add(params: P['AddParams']) {
      return http.post<T>(`${baseUrl}/add`, params)
    },
    
    // 修改数据
    update(params: P['UpdateParams']) {
      return http.post<T>(`${baseUrl}/update`, params)
    },
    
    // 批量删除
    delete(params: P['DeleteParams']) {
      return http.post<boolean>(`${baseUrl}/delete`, params)
    }
  }
}

T:定义核心数据类型

P:继承默认参数类型DefaultP,允许模块自定义参数结构