@nickyzj2023/utils
    Preparing search index...

    Function fetcher

    • 基于 Fetch API 的请求实例

      Parameters

      • baseUrl: string = ""

        接口前缀

      • baseOptions: RequestInit = {}

        应用于整个实例的请求体,后续请求都会带上

      Returns {
          delete: <T>(
              url: string,
              options?: Omit<RequestInit, "method" | "body">,
          ) => Promise<T>;
          get: <T>(url: string, options?: Omit<RequestInit, "method">) => Promise<T>;
          post: <T>(
              url: string,
              body: any,
              options?: Omit<RequestInit, "method" | "body">,
          ) => Promise<T>;
          put: <T>(
              url: string,
              body: any,
              options?: Omit<RequestInit, "method" | "body">,
          ) => Promise<T>;
      }

      特性:

      • 支持在创建实例、发出请求时合并相同的请求体(后者覆盖前者)
      • 支持在 GET 的 params 请求体中传递对象
      • 支持在 POST、PUT 的 body 请求体中传递对象
      • 可选 to() 函数转换请求结果为 [Error, Response]
      • 可选 withCache() 函数缓存请求结果
      // 直接发请求
      const res = await fetcher().get<Blog>("https://nickyzj.run:3030/blogs/hello-world", {
      params: {
      page: 2,
      pageSize: 10,
      }
      });

      // 创建实例,发请求
      const api = fetcher("https://nickyzj.run:3030", {
      headers: {
      Authorization: "Bearer token"
      }
      });
      const res = await api.get<Blog>("/blogs/hello-world");

      // 安全返回请求结果,不抛异常
      const [error, data] = await to(api.get<Blog>("/blogs/hello-world"));
      if (error) {
      // ...
      }
      // ...

      // 缓存请求结果
      const getBlogs = withCache(api.get);
      await getBlogs("/blogs");
      await getBlogs("/blogs"); // 不发请求,使用缓存