# 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 キーを作成してシークレットをコピーし、両方をエクスポートします：

```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 以上で応答した場合、および必須の引数が欠けている場合（リクエストの送信前）、メソッドは `Error` のサブクラスである `TombaException` で reject します。

| プロパティ   | 値                                                                                                                                                 |
| ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
| `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()` は、何も見つからなかった場合でも reject しません。これらのエンドポイントはステータス 200 と `errors` ボディで応答するため、`result.data.errors` を確認します。各 `errors.type` については[エラー](/error-handling#error-types)で説明しています。

## レート制限と再試行

SDK は再試行しません。`result.rateLimit` は、レスポンスの[レート制限ヘッダー](/rate-limits#rate-limit-headers)を `secondLimit`、`minuteLimit`、`dailyLimit`、`minuteRemaining`、`dailyRemaining`、`minuteReset`、`dailyReset`、`retryAfter`、`policy`、`rateLimit` として保持します。数値のヘッダーは整数として解析され、存在しないヘッダーや `0` のヘッダーは `null` になります。

`429` の場合は `TombaException` で reject します。`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 ボディを送信するため、[メール検索](/bulks#email-finder)のジョブなど、CSV のアップロードが必要なジョブは作成できません。`Bulk.download()` は、結果ファイル（CSV）を文字列として `result.data` に返します。

## ソースコード

[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) にあります。
