艾比·节点js, Bun & Deno SDK
官方Node.js、Bun和Deno图书馆 艾比・APIAbby是自由职业者和微型企业的全能企业管理平台.
目录
安装
使用您的首选软件包管理器安装软件包 :
npm install @abby-inc/node
# or
yarn add @abby-inc/node
# or
pnpm add @abby-inc/node
# or
bun add @abby-inc/node
对于 Deno, 您可以直接从 npm 导入 :
import Abby from 'npm:@abby-inc/node';
所需资源
- 节点js 22.13.0或以上(CI:22,24,26),Bun 1.0.0或以上,或Deno 2.0.0或以上
- 一个有API密钥的 Abby 账户
使用量
初始化
从中获取您的 API 密钥 艾比设置。 。 。 .
import Abby from '@abby-inc/node';
const abby = new Abby('your_api_key');
服务
SDK提供多项服务与Abby API的不同部分互动:
abby.company:当前公司信息与偏好.abby.invoice: 创建和管理发票.abby.estimate: 创建和管理估计数(引文).abby.contact: 管理您的联系人( 客户) .abby.organization: 管理组织.abby.billing: 共享计费公用事业 (PDF,电子邮件).abby.opportunity:客户关系管理和机会管理.abby.asset: 管理业务资产.abby.advance: 管理预付款.abby.customerPortal:客户门户支付和计费主题.
基本示例
import Abby from '@abby-inc/node';
const abby = new Abby('your_api_key');
async function main() {
// Get current company information
const { data: me } = await abby.company.getMe();
console.log(`Welcome back, ${me.user.firstname}!`);
// List all contacts
const { data: contacts } = await abby.contact.retrieveContacts({
query: { limit: 10 },
});
console.log(`Found ${contacts.docs.length} contacts.`);
}
main().catch(console.error);
配置
您可以在初始化 SDK 时通过可选配置设置 :
import Abby from '@abby-inc/node';
const abby = new Abby('your_api_key', {
baseUrl: 'https://api.app-abby.com',
timeout: 30000,
headers: {
'X-Custom-Header': 'value',
},
});
| 选项 | 默认 | 说明 |
|---|---|---|
baseUrl | 'https://api.app-abby.com' | Abby API的基础 URL. |
timeout | 30000 | 请求超时, 以毫秒计 . |
headers | undefined | 在每个请求中包含额外的标题 . |
fetch | globalThis.fetch | 自定义获取代理、记录或测试的执行 。 见 自定义获取代理支持( P)。 。 。 . |
自定义获取代理支持( P)
SDK 允许您提供自定义 fetch 用于高级使用,如代理、自定义记录或测试.
使用代理服务器
与 未编辑 (建议Node.js):
import Abby from '@abby-inc/node';
import { fetch as undiciFetch, ProxyAgent } from 'undici';
const proxyAgent = new ProxyAgent('http://proxy.example.com:8080');
const abby = new Abby('your_api_key', {
fetch: (url, init) =>
undiciFetch(url, {
...init,
dispatcher: proxyAgent,
}),
});
与 节点比对 财务报告和审定财务报表 https- 代理剂数字 :
import Abby from '@abby-inc/node';
import fetch from 'node-fetch';
import { HttpsProxyAgent } from 'https-proxy-agent';
const proxyAgent = new HttpsProxyAgent('http://proxy.example.com:8080');
const abby = new Abby('your_api_key', {
fetch: (url, init) =>
fetch(url, {
...init,
agent: proxyAgent,
}) as Promise<Response>,
});
自定义日志
const abby = new Abby('your_api_key', {
fetch: async (url, init) => {
console.log(`[Abby SDK] ${init?.method ?? 'GET'} ${url}`);
const start = Date.now();
const response = await globalThis.fetch(url, init);
console.log(`[Abby SDK] ${response.status} in ${Date.now() - start}ms`);
return response;
},
});
使用 Moc 获取测试
import { vi } from 'vitest';
const mockFetch = vi.fn(
async () =>
new Response(JSON.stringify({ success: true }), {
status: 200,
headers: { 'Content-Type': 'application/json' },
})
);
const abby = new Abby('your_api_key', {
fetch: mockFetch,
});
处理错误
SDK 当请求失败时会抛出描述错误 。 您可以抓住这些错误来处理不同的失败情况 :
try {
const { data } = await abby.invoice.getInvoice({
path: { invoiceId: 'inv_invalid' },
});
} catch (error) {
if (error.status === 404) {
console.error('Invoice not found');
} else if (error.status === 401) {
console.error('Invalid API key');
} else {
console.error('An unexpected error occurred:', error.message);
}
}
活动听众
SDK为全局错误处理和记录提供了事件发报器模式. 这对于与哨兵等出错跟踪服务相融合或集中记录很有用.
正在收听错误
订阅应用程序中的所有 API 错误 :
import Abby from '@abby-inc/node';
const abby = new Abby('your_api_key');
// Global error handler - fires on any 4xx/5xx response
abby.on('error', (error) => {
console.error(`API Error: ${error.status} ${error.statusText}`);
console.error(`URL: ${error.method} ${error.url}`);
console.error(`Message: ${error.message}`);
console.error(`Duration: ${error.duration}ms`);
// Send to error tracking service
Sentry.captureException(new Error(error.message), {
extra: {
status: error.status,
url: error.url,
requestId: error.requestId,
body: error.body,
},
});
});
倾听所有回复
订阅所有 API 响应( 无论是成功还是失败) :
// Log all API calls for debugging/monitoring
abby.on('response', (response) => {
console.log(`${response.method} ${response.url} - ${response.status} (${response.duration}ms)`);
});
删除收听器
使用 off() 删除一个听众 :
const errorHandler = (error) => console.error(error);
// Add listener
abby.on('error', errorHandler);
// Remove listener later
abby.off('error', errorHandler);
事件类型
| 活动 | 说明 | 有效载荷类型 |
|---|---|---|
error | 4xx/5xxx回应起火 | AbbyErrorEvent |
response | 所有反应均起火 | AbbyResponseEvent |
AbbyErrorEvent 属性 :
| 财产 | 类型 | 说明 |
|---|---|---|
status | number | HTTP 状态代码( 4xx 或 5xx) |
statusText | string | HTTP 状态文本 |
url | string | 请求 URL |
method | string | HTTP 方法( GET, POST等) |
duration | number | 请求持续时间以毫秒为单位 |
message | string? | 来自响应机构的错误消息, 如果有的话 |
body | unknown? | 反应机构(如有) |
requestId | string? | X- 请求- Id 页眉, 如果有的话 |
AbbyResponseEvent 属性 :
| 财产 | 类型 | 说明 |
|---|---|---|
status | number | HTTP 状态代码 |
url | string | 请求 URL |
method | string | HTTP 方法( GET, POST等) |
duration | number | 请求持续时间以毫秒为单位 |
ok | boolean | 答复是否成功( 2xx) |
截取器
拦截器允许您连接到请求/响应生命周期:
const client = abby.getClient();
// Request Interceptor: Add a custom header to every request
client.interceptors.request.use((request) => {
request.headers.set('X-Request-ID', crypto.randomUUID());
return request;
});
// Response Interceptor: Log every response status
client.interceptors.response.use((response) => {
console.log(`API Response: ${response.status}`);
return response;
});
原始请求
如果您需要调用SDK未覆盖的端点,或者更愿意直接指定请求细节,您可以使用基本的HTTP客户端:
import Abby from '@abby-inc/node';
const abby = new Abby('your_api_key');
const client = abby.getClient();
// GET request
const { data } = await client.get({
url: '/v2/some/endpoint',
});
// POST request with body
const { data: result } = await client.post({
url: '/v2/some/endpoint',
body: {
field: 'value',
},
});
// Other methods available: put, patch, delete, head, options
客户端在所有请求中自动包含您的 API 密钥和 SDK 信头 .
验证
SDK包括内置 佐德语Name 对 API 请求进行验证,在不正确有效载荷离开您的进程前将其抓取.
自动验证
所有 SDK 方法自动验证 请求数据:在发送前检查参数、查询字符串和请求机构.
答复未经证实. 反应计划生成并导出(见下文),但SDK并不运行这些计划——如果Spec/API不匹配,否则一个成功的调用会变成一个抛出的错误. 回复类型仅保留编译时间;分析导出内容 z*Dto 如果你需要运行时的保证,请自作主张.
如果请求验证失败, a ZodError 以详细信息显示什么是错的:
import Abby from '@abby-inc/node';
import { ZodError } from 'zod';
const abby = new Abby('your_api_key');
try {
// This will fail validation if the request body is invalid
await abby.contact.createContact({
body: {
// Missing required fields will trigger a ZodError
},
});
} catch (error) {
if (error instanceof ZodError) {
console.error('Validation failed:', error.errors);
}
}
使用 Zod Schemas 直接
所有 Zod schemas 均导出并可用于您自己的验证需要 :
import Abby, { zCreateContactDto, zReadContactDto } from '@abby-inc/node';
// Validate user input before sending to the API
const userInput = {
firstname: 'John',
lastname: 'Doe',
email: '[email protected]',
};
// Parse and validate (throws ZodError if invalid)
const validatedContact = zCreateContactDto.parse(userInput);
// Or use safeParse for non-throwing validation
const result = zCreateContactDto.safeParse(userInput);
if (result.success) {
console.log('Valid:', result.data);
} else {
console.error('Invalid:', result.error.errors);
}
// Infer TypeScript types from schemas
import { z } from 'zod';
type CreateContactInput = z.infer<typeof zCreateContactDto>;
可用的方案模式 :
z{DtoName}- DTO(例如,zCreateContactDto, (中文(简体) ),zReadInvoiceDto(中文(简体) )z{ControllerMethod}Data- 要求数据计划(例如,zContactControllerCreateContactData(中文(简体) )
类型脚本支持
SDK被写入TypeScript,为所有API资源和响应提供了完整的类型定义.
import Abby, { ReadMeDto } from '@abby-inc/node';
const abby = new Abby('your_api_key');
async function getCompanyData() {
const { data }: { data: ReadMeDto } = await abby.company.getMe();
return data;
}
也可以直接从Zod schemas推断类型:
import { z } from 'zod';
import { zReadContactDto } from '@abby-inc/node';
// Infer the type from the Zod schema
type Contact = z.infer<typeof zReadContactDto>;
版本
这个 SDK 使用 独立版本 从艾比API:
- SDK 版本 (单位:千美元)
version内package.json: 随行 铸造 sDK 更改( 错误修正、 新特性、 断开更改) - API 版本 (单位:千美元)
apiVersion内package.json: Abby API 版本用于生成 SDK 的音轨
{
"version": "1.2.0", // SDK version
"apiVersion": "1.5.0" // API spec version used to generate
}
这使得SDK能够独立于API更改而接受错误修正和改进.
SDK更新由 API 光谱变化自动打开的PRs,一旦CI通过就会被自动并发. 生成SDK工作流程的人工运行需要人机合并.
发展
欢迎捐款! 请看我们的 贡献准则 更多信息.
支助
如果遇到问题或有问题,请检查以下资源:
许可证
麻省理工学院执照 - 看 自由主义 详细情况.