为 Fable API 构建 SDK 客户端
安装
npm install @faable/sdk-base
构建 API 客户端
扩展 FaableApi 呼叫静态 create 工厂:
import { FaableApi } from "@faable/sdk-base";
import type { ApiParams } from "@faable/sdk-base";
export class MyApi extends FaableApi {
constructor(params?: ApiParams) {
super({ baseURL: "https://api.example.com", ...params });
}
getThing(id: string) {
return this.fetcher.get(`/thing/${id}`);
}
}
认证( 可插件, Octokit 风格)
认证是 明确 ——战略从不读取环境变量. 你选一个
authStrategy 并传递其配置 auth;选定的策略驱动
类型 auth因此编辑器自动完成正确的字段并拒绝
错的.
import { authClientCredentials, authApikey } from "@faable/sdk-base";
// client_credentials — the DEFAULT strategy. `auth` requires
// { client_id, client_secret }.
const api = MyApi.create({
baseURL: "https://my-account.auth.faable.link",
authStrategy: authClientCredentials,
auth: { client_id: "...", client_secret: "..." },
});
// api key — `auth` requires { apikey }.
const api2 = MyApi.create({
baseURL: "https://api.example.com",
authStrategy: authApikey,
auth: { apikey: "fak_xxx" },
});
authClientCredentials 请求其代号来自 <baseURL>/oauth/token 以
默认。 当 API 主机是 没有 认证服务器,指向符号请求
在右侧主机 auth.domain数字 :
auth: { client_id: "...", client_secret: "...", domain: "https://auth.example.com" }
写入自定义策略
战略就是建设者 (config, context) => { headers() }数字 :
import type { AuthStrategyBuilder } from "@faable/sdk-base";
type BearerConfig = { token: string };
export const authBearer: AuthStrategyBuilder<BearerConfig> = (config) => {
if (!config?.token) throw new Error("authBearer: `auth.token` is required");
return {
headers: async () => ({ authorization: `Bearer ${config.token}` }),
};
};
context 携带活人鱼 domain (数量) baseURL和 debug 旗帜,所以
符号最小化策略可以在不附加配置的情况下到达认证服务器 .