用Axios和原生fetch写访问语雀API接口

1. Axios 方式


import axios, { AxiosInstance, AxiosResponse } from 'axios';

// 定义 API 请求类
export class YuqueAPI {
  private readonly http: AxiosInstance;

  // 构造函数接受一个 access_token 参数
  constructor(private readonly accessToken: string) {
    // 创建 Axios 实例,并设置默认请求头
    this.http = axios.create({
      baseURL: 'https://www.yuque.com/api/v2',
      headers: {
        'User-Agent': 'lyzhong-yuque-blog',
        'X-Auth-Token': accessToken, // 在请求头中携带访问令牌
      },
    });
  }

  // 获取用户信息
  // 获取用户信息
  async getUser(login?: string): Promise<AxiosResponse<any>> {
    return this.http.get(`/user${login ? `s/${login}` : ''}`);
  }

  // 获取指定用户的文档仓库列表
  async getRepos(login: string, offset?: number): Promise<AxiosResponse<any>> {
    return this.http.get(`/users/${login}/repos`);
  }

  // 获取指定用户的文档列表
  async getDocs(login: string, blogNames: string): Promise<AxiosResponse<any>> {
    return this.http.get(`/repos/${login}/${blogNames}/docs`);
  }

  async getDoc(
    login: string,
    blogNames: string,
    slug: string,
  ): Promise<AxiosResponse<any>> {
    return this.http.get(`/repos/${login}/${blogNames}/docs/${slug}`);
  }

  // 其他 API 请求方法
  // ...
}


2. 原生Fetch 方式

// 定义 API 请求类
export class YuqueAPI {
  private readonly baseUrl = 'https://www.yuque.com/api/v2';
  private readonly headers = {
    'User-Agent': 'lyzhong-yuque-blog',
  };

  // 构造函数接受一个 access_token 参数
  constructor(private readonly accessToken: string) {
    // 在请求头中携带访问令牌
    this.headers['X-Auth-Token'] = accessToken;
  }

  // 获取用户信息
  async getUser(login?: string): Promise<Response> {
    const url = `${this.baseUrl}/user${login ? `s/${login}` : ''}`;
    const response = await fetch(url, { headers: this.headers });
    return response.json();
  }

  // 获取指定用户的文档仓库列表
  async getRepos(login: string, offset?: number): Promise<Response> {
    const url = `${this.baseUrl}/users/${login}/repos`;
    const response = await fetch(url, { headers: this.headers });
    return response.json();
  }

  // 获取指定用户的文档列表
  async getDocs(login: string, blogNames: string): Promise<Response> {
    const url = `${this.baseUrl}/repos/${login}/${blogNames}/docs`;
    const response = await fetch(url, { headers: this.headers });
    return response.json();
  }

  async getDoc(
    login: string,
    blogNames: string,
    slug: string,
  ): Promise<Response> {
    const url = `${this.baseUrl}/repos/${login}/${blogNames}/docs/${slug}`;
    const response = await fetch(url, { headers: this.headers });
    return response.json();
  }

  // 其他 API 请求方法
  // ...
}


3. 添加类型定义个 getResult 方法

const API_ROOT = 'https://www.yuque.com/api/v2';

export interface YuquePayload<T> {
  data: T;
}

export interface HelloMessage {
  message: string;
}

export interface User {
  id: number;
  type: string;
  login: string;
  name: string;
  description: string | null;
  avatar_url: string;
  created_at: string;
  updated_at: string;
}

export interface Repo {
  id: number;
  type: string;
  slug: string;
  name: string;
  namespace: string;
  user_id: string;
  user: User;
  description: string;
  creator_id: string;
  public: number;
  likes_count: number;
  watches_count: number;
  created_at: string;
  updated_at: string;
}

export interface Doc {
  cover: string;
  description: string;
  id: number;
  slug: string;
  title: string;
  book_id: number;
  book: Repo;
  user_id: number;
  user: User;
  format: string;
  body: string;
  body_draft: string;
  body_html: string;
  body_lake: string;
  creator_id: number;
  public: number;
  status: number;
  likes_count: number;
  comments_count: number;
  content_updated_at: string;
  deleted_at: string;
  created_at: string;
  updated_at: string;
}

export class YuqueApi {
  private token: string;
  private headers: { [key: string]: string };

  constructor(token: string) {
    this.token = token;
    this.headers = {
      'Content-Type': 'application/json',
      'User-Agent': 'lyzhong-yuque-blog',
      'X-Auth-Token': this.token,
    };
  }

  public async hello(): Promise<YuquePayload<HelloMessage>> {
    const { data } = await this.getResult<HelloMessage>('/hello');
    return {
      data,
    };
  }

  public async getUser(login?: string): Promise<YuquePayload<User>> {
    const { data } = await this.getResult<User>(
      `/user${login ? `s/${login}` : ''}`,
    );
    return {
      data,
    };
  }

  public async getRepos(
    login: string,
    offset?: number,
  ): Promise<YuquePayload<Repo[]>> {
    const { data } = await this.getResult<Repo[]>(`/users/${login}/repos`);
    return {
      data,
    };
  }

  public async getDocs(
    namespace: string,
    offset?: number,
  ): Promise<YuquePayload<Doc[]>> {
    const { data } = await this.getResult<Doc[]>(`/repos/${namespace}/docs`);
    return {
      data,
    };
  }

  public async getDoc(
    namespace: string,
    slug: string,
  ): Promise<YuquePayload<Doc>> {
    const { data } = await this.getResult<Doc>(
      `/repos/${namespace}/docs/${slug}`,
    );
    return {
      data,
    };
  }

  private async getResult<T>(
    path: string,
    options: RequestInit = {},
  ): Promise<YuquePayload<T>> {
    const response = await fetch(`${API_ROOT}${path}`, {
      method: 'GET',
      headers: this.headers,
      ...options,
    });

    if (!response.ok) {
      throw new Error(
        `Failed to fetch ${path}, status code: ${response.status}`,
      );
    }

    const json = await response.json();

    return {
      data: json,
    };
  }
}


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值