Skip to content

TypeScript 项目示例

示例网站GitHub源码

概述

本示例展示了如何在 TypeScript 项目中集成 ApiSorcery。TypeScript 为 JavaScript 应用程序提供静态类型检查和增强的开发体验,非常适合大型 Web 应用程序。

特性

  • 类型安全:完整的 TypeScript 支持,生成接口和类型定义
  • 框架无关:适用于 React、Vue、Angular 和其他 TypeScript 框架
  • Axios 集成:内置支持 Axios HTTP 客户端和拦截器
  • IntelliSense 支持:完整的 IDE 支持,包含自动完成和类型检查
  • Tree shaking:通过 ES 模块支持优化打包体积

快速设置

1. 安装 ApiSorcery

bash
npm install -g autoapi

2. 初始化配置

bash
autoapi init -l ts

这将创建一个 .autoapirc.json 配置文件:

json
{
  "application": {
    "name": "TypeScript API 客户端",
    "language": "ts",
    "outputDir": "./src/api/auto"
  },
  "services": [
    {
      "code": "main",
      "name": "主服务",
      "source": "https://your-api.com/swagger.json",
      "enabled": true
    }
  ]
}

3. 安装依赖

bash
npm install axios
npm install -D @types/node

4. 生成 API 客户端

bash
autoapi generate

5. 在 TypeScript 中使用

typescript
import { ApiMain } from '@/api/auto/main/api';
import type { User } from '@/api/auto/main/model';

class UserService {
  private apiMain = new ApiMain();

  async getUsers(): Promise<User[]> {
    try {
      const response = await this.apiMain.getUsers();
      return response.data || [];
    } catch (error) {
      console.error('获取用户失败:', error);
      throw error;
    }
  }

  async createUser(userData: Partial<User>): Promise<User> {
    const response = await this.apiMain.createUser(userData);
    return response.data;
  }
}

框架集成

Vue 3 + Composition API

typescript
import { ref, onMounted } from 'vue';
import { ApiMain } from '@/api/auto/main/api';

export function useUsers() {
  const users = ref<User[]>([]);
  const loading = ref(false);
  const apiMain = new ApiMain();

  const fetchUsers = async () => {
    loading.value = true;
    try {
      const response = await apiMain.getUsers();
      users.value = response.data || [];
    } finally {
      loading.value = false;
    }
  };

  onMounted(fetchUsers);

  return { users, loading, fetchUsers };
}

React with Hooks

typescript
import { useState, useEffect } from 'react';
import { ApiMain } from '@/api/auto/main/api';

export function useUsers() {
  const [users, setUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState(false);
  const apiMain = new ApiMain();

  useEffect(() => {
    const fetchUsers = async () => {
      setLoading(true);
      try {
        const response = await apiMain.getUsers();
        setUsers(response.data || []);
      } finally {
        setLoading(false);
      }
    };

    fetchUsers();
  }, []);

  return { users, loading };
}

最佳实践

  1. 类型定义:利用生成的 TypeScript 接口获得更好的类型安全性
  2. 错误处理:实现适当的错误边界和错误处理策略
  3. 请求拦截器:使用 Axios 拦截器进行身份验证和请求/响应转换
  4. 环境配置:为开发、测试和生产环境使用不同的 API 端点
  5. 代码分割:实现 API 模块的懒加载以优化打包体积