# SDK de Node.js

`tomba` es el cliente oficial de Node.js para la [API de Tomba](/introduction). Cada área de la API es una clase de servicio, y cada método devuelve una promesa para una solicitud.

## Requisitos

- Node.js. `package.json` no declara ninguna versión mínima; el SDK se compila y se prueba en Node.js 20.
- [`axios`](https://www.npmjs.com/package/axios), instalado como dependencia.

## Instalación

```bash
npm install tomba
```

El paquete es CommonJS con declaraciones de TypeScript. Los ejemplos de esta página son módulos ES: guárdalos como archivos `.mjs` o establece `"type": "module"` en tu `package.json`.

## Autenticación

Crea una clave API y copia tu secreto en la página [API keys](https://app.tomba.io/api), y luego exporta ambos:

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

El SDK no lee variables de entorno. Pasa los valores a `setKey()` y `setSecret()`, y el cliente los envía como los encabezados `X-Tomba-Key` y `X-Tomba-Secret`. La caducidad y la rotación de las claves se explican en [Autenticación](/authentication).

## Primera solicitud

Busca la dirección de email de una persona en una empresa:

```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);
```

Todos los métodos se resuelven en `{ data, rateLimit }`, donde `data` es el cuerpo JSON decodificado. La API envuelve su payload en su propio objeto `data` ([Formato de respuesta](/introduction#response-format)), así que la dirección está en `result.data.data.email`. Las declaraciones de TypeScript tipan `result.data` como el propio payload, así que el código TypeScript necesita una conversión de tipo para leer `result.data.data`.

## Errores

Los métodos se rechazan con `TombaException`, una subclase de `Error`, cuando la API responde con un estado 400 o superior y, antes de enviar una solicitud, cuando falta un argumento obligatorio.

| Propiedad   | Valor                                                                                                                                                 |
| ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
| `message`  | El `errors.message` de la API.                                                                                                                           |
| `code`     | El objeto de respuesta de axios: `code.status` es el estado HTTP y `code.headers` contiene los encabezados de la respuesta. `undefined` cuando no se recibió ninguna respuesta. |
| `response` | El cuerpo del error decodificado, `{ 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()` y `combined()` no se rechazan cuando no se encuentra nada: esos endpoints responden con el estado 200 y un cuerpo `errors`, así que comprueba `result.data.errors`. Cada `errors.type` se describe en [Errores](/error-handling#error-types).

## Límites de solicitudes y reintentos

El SDK no reintenta. `result.rateLimit` contiene los [encabezados de límites de solicitudes](/rate-limits#rate-limit-headers) de la respuesta como `secondLimit`, `minuteLimit`, `dailyLimit`, `minuteRemaining`, `dailyRemaining`, `minuteReset`, `dailyReset`, `retryAfter`, `policy` y `rateLimit`. Los encabezados numéricos se analizan como enteros, y un encabezado ausente o `0` se convierte en `null`.

Un `429` se rechaza con `TombaException`; lee el tiempo de espera de `error.code.headers["retry-after"]` y reintenta como se describe en [Gestionar respuestas 429](/rate-limits#handle-429-responses).

Las solicitudes agotan el tiempo de espera a los 120 segundos. Cambia el tiempo de espera con `client.setTimeout(milliseconds)`.

## Referencia de métodos

Crea cada servicio con el cliente, por ejemplo `new Finder(client)`. Todas las clases son exportaciones con nombre de `tomba`.

| Método                                                                                                   | Endpoint                                                                        |
| -------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- |
| `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` es el segmento `{type}` que se enumera en [Tipos de trabajos masivos](/bulks#bulk-types); el orden de las llamadas se describe en [Ciclo de vida](/bulks#lifecycle). `Bulk.create()` envía un cuerpo JSON, así que no puede crear trabajos que requieren subir un CSV, como los trabajos de [Email Finder](/bulks#email-finder). `Bulk.download()` devuelve el archivo de resultados, un CSV, como string en `result.data`.

## Código fuente

[github.com/tomba-io/node](https://github.com/tomba-io/node) (Apache-2.0). Las notas de la versión están en [CHANGELOG.md](https://github.com/tomba-io/node/blob/master/CHANGELOG.md).
