@edgefirst-dev/api-client

中文文档
0.3.0发布于 2025/09/02MITES Module零依赖构建来源已验证近 30 天下载 2216

A basic HTTP client for making API requests

原始使用文档
文档目录9 节
  1. Installation
  2. Usage
  3. Customization
  4. Interceptos
  5. Testing
  6. Error Handling
  7. Timeout
  8. License
  9. Author

@edgefirst-dev/api-client

The APIClient class provides a flexible and extensible HTTP client for making API requests. It supports common HTTP methods (GET, POST, PUT, PATCH, DELETE) and allows customization of the request and response handling through the before and after interceptor hooks.

Installation

bun add @edgefirst-dev/api-client

Usage

Import the APIClient and create a new instance to make API requests.

import { APIClient } from "@edgefirst-dev/api-client";

let client = new APIClient("https://api.example.com");
let response = await client.get("/users/1");

Customization

You can customize the request and response handling by extending the APIClient class and overriding the before and after methods.

class CustomAPIClient extends APIClient {
  async before(request: Request) {
    // Add a custom header to the request
    request.headers.set("X-Custom-Header", "value");

    return request;
  }

  async after(request: Request, response: Response) {
    if (response.status === 401) {
      // Handle unauthorized error
      throw new Error("Unauthorized");
    }

    return response;
  }
}

let client = new CustomAPIClient("https://api.example.com");
let response = await client.get("/users/1");

You can also define custom methods in the subclass to encapsulate common API calls.

import { ObjectParser } from "@edgefirst-dev/data/parser";

class CustomAPIClient extends APIClient {
  async fetchUserData(id: number) {
    let response = await this.get(`/users/${id}`);
    let data = await response.json();
    return new ObjectParser(data);
  }
}

let client = new CustomAPIClient("https://api.example.com");
let user = await client.fetchUserData(1);
let userName = user.string("name");

By overriding the constructor, you can provide a default base URL.

class CustomAPIClient extends APIClient {
  constructor() {
    super("https://api.example.com");
  }
}

let client = new CustomAPIClient();

Interceptos

You can add interceptors to the APIClient instance to customize the request and response handling.

let client = new APIClient("https://api.example.com");

client.interceptors.before.on(async (request) => {
  // Add a custom header to the request
  request.headers.set("X-Custom-Header", "value");

  return request;
});

client.interceptors.after.on(async (request, response) => {
  if (response.status === 401) {
    // Handle unauthorized error
    throw new Error("Unauthorized");
  }

  return response;
});

You can also remove interceptors using the off method.

async function beforeInterceptor(request) {
  // Add a custom header to the request
  request.headers.set("X-Custom-Header", "value");

  return request;
}

let client = new APIClient("https://api.example.com");

client.interceptors.before.on(beforeInterceptor); // Add the interceptor
client.interceptors.before.off(beforeInterceptor); // Remove the interceptor

The sub-class interceptors run before the instance interceptors.

class CustomAPIClient extends APIClient {
  async before(request: Request) {
    // Add a custom header to the request
    request.headers.set("X-Custom-Header", "1");

    return request;
  }
}

let client = new CustomAPIClient("https://api.example.com");

client.interceptors.before.on(async (request) => {
  // Add a custom header to the request
  request.headers.set("X-Custom-Header", "2");

  return request;
});

Here the X-Custom-Header will be set to 2 in the request because the instance interceptor overrides the header set by the sub-class interceptor.

Testing

You can easily test your API calls using the APIClient with msw to mock the API responses.

import { http, HttpResponse } from "msw";
import { setupServer } from "msw/native"; // or "msw/node" or "msw/browser"

let server = setupServer(
  http.get("https://api.example.com/users/1", (req, res, ctx) => {
    return res(ctx.json({ id: 1, name: "John Doe" }));
  })
);

server.listen();

let client = new APIClient("https://api.example.com");
let response = await client.get("/users/1");
let data = await response.json(); // { id: 1, name: "John Doe" }

Error Handling

The APIClient class never throws an error except for network errors. You can handle API errors by checking the response status code.

let client = new APIClient("https://api.example.com");

try {
  let response = await client.get("/users/1");
  if (response.status === 401) {
    // Handle unauthorized error
    throw new Error("Unauthorized");
  }
  // Handle other errors or success
} catch (error) {
  // Handle network error
  console.error(error);
}

Alternatively, you can use the after interceptor to handle common API errors.

class CustomAPIClient extends APIClient {
  async after(request: Request, response: Response) {
    if (response.status === 401) {
      // Handle unauthorized error
      throw new Error("Unauthorized");
    }

    return response;
  }
}

Or you can use the on method to add an interceptor to handle common API errors.

let client = new APIClient("https://api.example.com");

client.interceptors.after.on(async (_, response) => {
  if (response.status === 401) {
    // Handle unauthorized error
    throw new Error("Unauthorized");
  }

  return response;
});

Timeout

You can set a timeout for the API requests using the signal option.

let client = new APIClient("https://api.example.com");
await client.get("/users/1", { signal: AbortSignal.timeout(5000) });

License

See LICENSE

Author

版本与发布记录

@edgefirst-dev/api-client 共发布 4 个版本,首次发布于 2024/10/14;过去 12 个月发布了 0 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.3.0latest2025/09/021.2 年前
0.2.02025/03/251.6 年前
0.1.02025/01/141.8 年前
0.0.12024/10/142 年前

关于 @edgefirst-dev/api-client 的常见问题

@edgefirst-dev/api-client 是什么?

A basic HTTP client for making API requests

如何安装 @edgefirst-dev/api-client?

在项目目录运行 npm install @edgefirst-dev/api-client,或使用 pnpm add / yarn add / bun add。

@edgefirst-dev/api-client 支持 TypeScript 吗?

该包的 package.json 没有声明类型入口。需要类型提示时,可以在 npm 上查找社区维护的 @types/edgefirst-dev__api-client 是否存在。

@edgefirst-dev/api-client 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@edgefirst-dev/api-client 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=20.0.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@edgefirst-dev/api-client 可以商用吗?

@edgefirst-dev/api-client 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@edgefirst-dev/api-client 的下载量有多少?

根据 npm 官方下载统计,@edgefirst-dev/api-client 在 2026/10/13 – 2026/11/11 这 30 天内被下载 2,216 次,日均约 74 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@edgefirst-dev/api-client 还在维护吗?

最新版本 0.3.0 发布于 2025/09/02(1.2 年前);至今共发布 4 个版本,其中过去 12 个月发布了 0 个;首次发布于 2024/10/14。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。