# Deno SDK

`@tomba/sdk` 是 [Tomba API](/introduction) 的官方 Deno 客户端，发布在 JSR 上。每个 API 功能区对应一个服务类，每个方法针对 1 个请求返回一个 promise。本页介绍 1.0.4 版本，即 JSR 上的当前版本。

## 要求

Deno 2。`deno.json` 未声明最低版本；SDK 在 Deno 2.x 上进行代码检查和测试。使用 `--allow-net` 运行您的程序；如果程序从环境中读取您的密钥，还需加上 `--allow-env`。

## 安装

```bash
deno add jsr:@tomba/sdk
```

这会将 `@tomba/sdk` 添加到您的 `deno.json` 的导入项中。

## 认证

在 [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)。

## 首个请求

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

```typescript
import { Client, Finder } from "@tomba/sdk";

const client = new Client()
    .setKey(Deno.env.get("TOMBA_API_KEY")!)
    .setSecret(Deno.env.get("TOMBA_SECRET_KEY")!);

const result = await new Finder(client).emailFinder(
    "stripe.com",
    "Jane",
    "Doe",
);
const body = result.data as { data: { email: string | null } };
console.log(body.data.email);
```

每个方法都解析为 `{ data, rateLimit }`，其中 `data` 是解码后的 JSON 响应体，类型为 `unknown`。API 会将有效负载包装在它自己的 `data` 对象中（[响应格式](/introduction#response-format)），因此邮箱地址位于 `data.data.email`。

## 错误

当 API 返回 400 或更高的状态码时、请求失败时，以及在发送请求之前发现缺少必填参数时，SDK 都会抛出 `TombaException`。`TombaException` 并不继承 `Error`；对于 API 错误，其 `message` 为 `undefined`，`code` 为 `0`：详细信息需从解码后的错误响应体 `response` 中读取。

```typescript
import { Client, Finder, TombaException } from "@tomba/sdk";

type ErrorBody = { errors: { type: string; message: string; code: number } };

const client = new Client()
    .setKey(Deno.env.get("TOMBA_API_KEY")!)
    .setSecret(Deno.env.get("TOMBA_SECRET_KEY")!);

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

`errors.code` 是 HTTP 状态码。每个 `errors.type` 的说明请参阅[错误](/error-handling#error-types)。对于请求失败或缺少参数的情况，`response` 为空，`message` 包含原因。

## 速率限制和重试

SDK 不会重试。`result.rateLimit` 以 `string | null` 字段的形式保存响应的[速率限制响应头](/rate-limits#rate-limit-headers)：`xSecondRateLimit`、`xMinuteRateLimit`、`xDailyRateLimit`、`xMinuteRequestLeft`、`xDailyRequestLeft`、`xMinuteResetSeconds`、`xDailyResetSeconds`、`retryAfter`、`rateLimitPolicy` 和 `rateLimit`。

收到 `429` 时会抛出 `TombaException`，但不包含响应头。按照[处理 429 响应](/rate-limits#handle-429-responses)中的说明，等待一段时间后再重试。

请求在 120 秒后超时；超时时间不可配置。

## 方法参考

使用客户端创建各个服务，例如 `new Finder(client)`。

| 方法                                                                                | 端点                                                                    |
| ------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- |
| `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, page?, limit?, department?, enrichMobile?, webhookUrl?)` | [`GET /domain-search`](/api/finder#domain-search)                           |
| `Finder.emailFinder(domain, firstName, lastName, webhookUrl?)`                        | [`GET /email-finder`](/api/finder#email-finder)                             |
| `Finder.authorFinder(url, webhookUrl?)`                                               | [`GET /author-finder`](/api/finder#author-finder)                           |
| `Finder.linkedinFinder(url, webhookUrl?)`                                             | [`GET /linkedin`](/api/finder#linkedin-finder)                              |
| `Count.emailCount(domain)`                                                            | [`GET /email-count`](/api/finder#email-count)                               |
| `Verifier.emailVerifier(email, webhookUrl?)`                                          | [`GET /email-verifier`](/api/verifier#email-verifier)                       |
| `Sources.emailSources(email)`                                                         | [`GET /email-sources`](/api/email#email-sources)                            |
| `Finder.phoneFinder(email, webhookUrl?)`                                              | [`GET /phone-finder`](/api/phone#phone-finder)                              |
| `PhoneFinder.finder(email, webhookUrl?)`                                              | [`GET /phone-finder`](/api/phone#phone-finder)                              |
| `PhoneFinder.validator(phone)`                                                        | [`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)                                 |
| `Keys.getKeys()`                                                                      | [`GET /keys`](/api/keys#retrieve-api-keys)                                  |
| `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?, listId?, 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.createList(name)`                                                         | [`POST /leads_lists`](/api/lead-lists#create-leads-list)                    |
| `LeadsLists.updateListId(id, name)`                                                   | [`PUT /leads_lists/{id}`](/api/lead-lists#update-leads-list)                |
| `LeadsLists.deleteListId(id)`                                                         | [`DELETE /leads_lists/{id}`](/api/lead-lists#delete-leads-list)             |

## 源代码

[github.com/tomba-io/deno](https://github.com/tomba-io/deno)（Apache-2.0），在 JSR 上以 [@tomba/sdk](https://jsr.io/@tomba/sdk) 发布。版本说明见 [CHANGELOG.md](https://github.com/tomba-io/deno/blob/master/CHANGELOG.md)。
