# Node.js SDK

`tomba` 是 [Tomba API](/introduction) 的官方 Node.js 客户端。每个 API 功能区对应一个服务类，每个方法针对 1 个请求返回一个 promise。

## 要求

- Node.js。`package.json` 未声明最低版本；SDK 在 Node.js 20 上构建和测试。
- [`axios`](https://www.npmjs.com/package/axios)，作为依赖项安装。

## 安装

```bash
npm install tomba
```

该包是附带 TypeScript 类型声明的 CommonJS 包。本页中的示例是 ES 模块：将它们保存为 `.mjs` 文件，或在您的 `package.json` 中设置 `"type": "module"`。

## 认证

在 [API keys](https://app.tomba.io/api) 页面创建 API 密钥并复制您的 Secret，然后将它们都导出：

```bash
export TOMBA_API_KEY="ta_xxxx"
export TOMBA_SECRET_KEY="ts_xxxx"
```

SDK 不会读取环境变量。将这些值传给 `setKey()` 和 `setSecret()`，客户端会将它们作为 `X-Tomba-Key` 和 `X-Tomba-Secret` 请求头发送。有关密钥过期和轮换，请参阅[认证](/authentication)。

## 首个请求

查找某家公司中某个人的邮箱地址：

```javascript
import { TombaClient, Finder } from "tomba";

const client = new TombaClient()
    .setKey(process.env.TOMBA_API_KEY)
    .setSecret(process.env.TOMBA_SECRET_KEY);

const result = await new Finder(client).emailFinder({
    domain: "stripe.com",
    firstName: "Jane",
    lastName: "Doe",
});
console.log(result.data.data.email);
```

每个方法都解析为 `{ data, rateLimit }`，其中 `data` 是解码后的 JSON 响应体。API 会将有效负载包装在它自己的 `data` 对象中（[响应格式](/introduction#response-format)），因此邮箱地址位于 `result.data.data.email`。TypeScript 类型声明将 `result.data` 的类型定义为有效负载本身，因此 TypeScript 代码需要进行类型转换才能读取 `result.data.data`。

## 错误

当 API 返回 400 或更高的状态码时，以及在发送请求之前发现缺少必填参数时，方法会以 `TombaException`（`Error` 的子类）拒绝。

| 属性   | 值                                                                                                                                                 |
| ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
| `message`  | API 的 `errors.message`。                                                                                                                           |
| `code`     | axios 响应对象：`code.status` 是 HTTP 状态码，`code.headers` 包含响应头。未收到响应时为 `undefined`。 |
| `response` | 解码后的错误响应体 `{ errors: { type, message, code } }`。                                                                                        |

```javascript
import { TombaClient, Finder, TombaException } from "tomba";

const client = new TombaClient()
    .setKey(process.env.TOMBA_API_KEY)
    .setSecret(process.env.TOMBA_SECRET_KEY);

try {
    const result = await new Finder(client).emailFinder({
        domain: "stripe.com",
        firstName: "Jane",
        lastName: "Doe",
    });
    console.log(result.data.data.email);
} catch (error) {
    if (!(error instanceof TombaException)) throw error;
    console.log(
        error.code?.status,
        error.message,
        error.response?.errors?.type,
    );
}
```

`Enrichment.person()`、`company()` 和 `combined()` 在未找到结果时不会拒绝：这些端点会返回状态码 200 和一个 `errors` 响应体，因此需检查 `result.data.errors`。每个 `errors.type` 的说明请参阅[错误](/error-handling#error-types)。

## 速率限制和重试

SDK 不会重试。`result.rateLimit` 以 `secondLimit`、`minuteLimit`、`dailyLimit`、`minuteRemaining`、`dailyRemaining`、`minuteReset`、`dailyReset`、`retryAfter`、`policy` 和 `rateLimit` 保存响应的[速率限制响应头](/rate-limits#rate-limit-headers)。数值型响应头会被解析为整数，缺失或为 `0` 的响应头会变为 `null`。

收到 `429` 时会以 `TombaException` 拒绝；从 `error.code.headers["retry-after"]` 读取等待时间，然后按照[处理 429 响应](/rate-limits#handle-429-responses)中的说明重试。

请求在 120 秒后超时。使用 `client.setTimeout(milliseconds)` 更改超时时间。

## 方法参考

使用客户端创建各个服务，例如 `new Finder(client)`。每个类都是 `tomba` 的命名导出。

| 方法                                                                                                   | 端点                                                                        |
| -------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- |
| `Account.getAccount()`                                                                                   | [`GET /me`](/api/account#get-account)                                           |
| `Usage.getUsage()`                                                                                       | [`GET /usage`](/api/account#retrieve-api-usage)                                 |
| `Logs.getLogs({ page, limit })`                                                                          | [`GET /logs`](/api/account#retrieve-api-logs)                                   |
| `Domain.domainSearch({ domain, company, page, limit, country, department, enrich_mobile, webhook_url })` | [`GET /domain-search`](/api/finder#domain-search)                               |
| `Finder.emailFinder({ domain, company, firstName, lastName, fullName, enrichMobile, webhook_url })`      | [`GET /email-finder`](/api/finder#email-finder)                                 |
| `Finder.authorFinder(url, webhook_url)`                                                                  | [`GET /author-finder`](/api/finder#author-finder)                               |
| `Finder.linkedinFinder(url, enrich_mobile, full, webhook_url)`                                           | [`GET /linkedin`](/api/finder#linkedin-finder)                                  |
| `Finder.emailEnrichment(email, enrich_mobile, webhook_url)`                                              | [`GET /enrich`](/api/finder#email-enrichment)                                   |
| `Format.emailFormat(domain)`                                                                             | [`GET /email-format`](/api/finder#email-format)                                 |
| `Location.getLocation(domain)`                                                                           | [`GET /location`](/api/finder#location)                                         |
| `Count.emailCount(domain)`                                                                               | [`GET /email-count`](/api/finder#email-count)                                   |
| `Verifier.emailVerifier(email, enrich_mobile, webhook_url)`                                              | [`GET /email-verifier`](/api/verifier#email-verifier)                           |
| `Sources.emailSources(email)`                                                                            | [`GET /email-sources`](/api/email#email-sources)                                |
| `Enrichment.person(email)`                                                                               | [`GET /people/find`](/api/enrichment#person-api)                                |
| `Enrichment.company(domain)`                                                                             | [`GET /companies/find`](/api/enrichment#company-api)                            |
| `Enrichment.combined(email)`                                                                             | [`GET /combined/find`](/api/enrichment#combined-api)                            |
| `Phone.finder({ email, domain, linkedin, full, webhook_url })`                                           | [`GET /phone-finder`](/api/phone#phone-finder)                                  |
| `Phone.validator(phone, country_code)`                                                                   | [`GET /phone-validator`](/api/phone#phone-validator)                            |
| `Status.domainStatus(domain)`                                                                            | [`GET /domain-status`](/api/domain#domain-status)                               |
| `Status.autoComplete(query)`                                                                             | [`GET /domain-suggestions`](/api/domain-suggestions#get-domain-suggestions)     |
| `Similar.websites(domain)`                                                                               | [`GET /similar`](/api/domain#similar)                                           |
| `Technology.list(domain)`                                                                                | [`GET /technology`](/api/domain#technology)                                     |
| `Reveal.companiesSearch({ query, filters, page })`                                                       | [`POST /reveal/search`](/api/reveal#search-companies)                           |
| `Flag.listFlags({ page, limit })`                                                                        | [`GET /flag`](/api/flag#list-my-flags)                                          |
| `Flag.createFlag({ flag_type, value, reason, comment })`                                                 | [`POST /flag`](/api/flag#flag-incorrect-data)                                   |
| `Keys.getKeys()`                                                                                         | [`GET /keys`](/api/keys#retrieve-api-keys)                                      |
| `Keys.getKey(id)`                                                                                        | [`GET /keys/{id}`](/api/keys#retrieve-a-single-api-key)                         |
| `Keys.createKey()`                                                                                       | [`POST /keys`](/api/keys#create-an-api-key)                                     |
| `Keys.resetKey(id)`                                                                                      | [`PUT /keys/{id}`](/api/keys#reset-an-api-key)                                  |
| `Keys.deleteKey(id)`                                                                                     | [`DELETE /keys/{id}`](/api/keys#delete-an-api-key)                              |
| `Leads.listLeads({ page, limit, domain })`                                                               | [`GET /leads`](/api/leads#retrieve-leads)                                       |
| `Leads.getLead(id)`                                                                                      | [`GET /leads/{id}`](/api/leads#retrieve-a-single-lead)                          |
| `Leads.createLead(data)`                                                                                 | [`POST /leads`](/api/leads#create-a-lead)                                       |
| `Leads.updateLead(id, data)`                                                                             | [`PUT /leads/{id}`](/api/leads#update-a-lead)                                   |
| `Leads.deleteLead(id)`                                                                                   | [`DELETE /leads/{id}`](/api/leads#delete-a-lead)                                |
| `LeadsLists.getLists()`                                                                                  | [`GET /leads_lists`](/api/lead-lists#retrieve-leads-lists)                      |
| `LeadsLists.getList(id)`                                                                                 | [`GET /leads_lists/{id}`](/api/lead-lists#retrieve-a-single-leads-list)         |
| `LeadsLists.createList({ name })`                                                                        | [`POST /leads_lists`](/api/lead-lists#create-leads-list)                        |
| `LeadsLists.updateList(id, { name })`                                                                    | [`PUT /leads_lists/{id}`](/api/lead-lists#update-leads-list)                    |
| `LeadsLists.deleteList(id)`                                                                              | [`DELETE /leads_lists/{id}`](/api/lead-lists#delete-leads-list)                 |
| `LeadsAttributes.getLeadAttributes()`                                                                    | [`GET /attributes`](/api/lead-attributes#retrieve-lead-attributes)              |
| `LeadsAttributes.getLeadAttribute(id)`                                                                   | [`GET /attributes/{id}`](/api/lead-attributes#retrieve-a-single-lead-attribute) |
| `LeadsAttributes.createLeadAttribute({ name, type })`                                                    | [`POST /attributes`](/api/lead-attributes#create-a-lead-attribute)              |
| `LeadsAttributes.updateLeadAttribute(id, { name, type })`                                                | [`PUT /attributes/{id}`](/api/lead-attributes#update-a-lead-attribute)          |
| `LeadsAttributes.deleteLeadAttribute(id)`                                                                | [`DELETE /attributes/{id}`](/api/lead-attributes#delete-a-lead-attribute)       |
| `Bulk.list(type, { page, limit })`                                                                       | [`GET /bulk/{type}`](/api/bulks)                                                |
| `Bulk.create(type, data)`                                                                                | [`POST /bulk/{type}`](/api/bulks)                                               |
| `Bulk.get(type, id)`                                                                                     | [`GET /bulk/{type}/{id}`](/api/bulks)                                           |
| `Bulk.launch(type, id)`                                                                                  | [`PUT /bulk/{type}/{id}`](/api/bulks)                                           |
| `Bulk.progress(type, id)`                                                                                | [`GET /bulk/{type}/{id}/progress`](/api/bulks)                                  |
| `Bulk.download(type, id)`                                                                                | [`GET /bulk/{type}/{id}/download`](/api/bulks)                                  |
| `Bulk.rename(type, id, name)`                                                                            | [`PUT /bulk/{type}/{id}/rename`](/api/bulks)                                    |
| `Bulk.archive(type, id)`                                                                                 | [`DELETE /bulk/{type}/{id}/archive`](/api/bulks)                                |
| `Bulk.delete(type, id)`                                                                                  | [`DELETE /bulk/{type}/{id}/delete`](/api/bulks)                                 |

`type` 是[批量类型](/bulks#bulk-types)中列出的 `{type}` 路径段；调用顺序请参阅[生命周期](/bulks#lifecycle)。`Bulk.create()` 发送 JSON 请求体，因此无法创建需要上传 CSV 的任务，例如[邮箱查找器](/bulks#email-finder)任务。`Bulk.download()` 以字符串形式在 `result.data` 中返回结果文件（一个 CSV）。

## 源代码

[github.com/tomba-io/node](https://github.com/tomba-io/node)（Apache-2.0）。版本说明见 [CHANGELOG.md](https://github.com/tomba-io/node/blob/master/CHANGELOG.md)。
