EmailVerify LogoEmailVerify

TypeScript SDK

TypeScript email checker SDK with full type definitions. Type-safe email verification for Node.js.

El SDK de TypeScript de EmailVerify proporciona definiciones de tipos completas para verificación de correo electrónico con tipos seguros en proyectos TypeScript.

El SDK de TypeScript comparte el mismo paquete que el SDK de Node.js pero con soporte completo de TypeScript.

Instalación

npm install @emailverify/node
# o
yarn add @emailverify/node
# o
pnpm add @emailverify/node

Inicio rápido

import { EmailVerify, VerificationResult } from '@emailverify/node';

const client = new EmailVerify({
  apiKey: process.env.EMAILVERIFY_API_KEY!,
});

const result: VerificationResult = await client.verify('user@example.com');
console.log(result.status); // Tipo: 'valid' | 'invalid' | 'unknown' | 'accept_all'

Definiciones de tipos

Opciones del cliente

interface ClientOptions {
  apiKey: string;
  timeout?: number;           // Predeterminado: 30000ms
  retries?: number;           // Predeterminado: 3
  retryDelay?: number;        // Predeterminado: 1000ms
  retryMaxDelay?: number;     // Predeterminado: 30000ms
  baseUrl?: string;           // Predeterminado: 'https://api.emailverify.ai'
}

Resultado de verificación

interface VerificationResult {
  email: string;
  status: VerificationStatus;
  result: ResultDetails;
  score: number;
  reason: string | null;
}

type VerificationStatus = 'valid' | 'invalid' | 'unknown' | 'accept_all';

interface ResultDetails {
  deliverable: boolean | null;
  valid_format: boolean;
  valid_domain: boolean;
  valid_mx: boolean;
  disposable: boolean;
  role: boolean;
  catchall: boolean;
  free: boolean;
  smtp_valid: boolean | null;
}

Tipos de trabajos masivos

interface BulkJob {
  id: string;
  status: BulkJobStatus;
  total: number;
  processed: number;
  valid: number;
  invalid: number;
  unknown: number;
  created_at: string;
  completed_at: string | null;
}

type BulkJobStatus = 'pending' | 'processing' | 'completed' | 'failed';

interface BulkJobResults {
  job_id: string;
  results: VerificationResult[];
}

Tipos de errores

class EmailVerifyError extends Error {
  code: string;
  statusCode?: number;
}

class AuthenticationError extends EmailVerifyError {
  code: 'authentication_error';
}

class RateLimitError extends EmailVerifyError {
  code: 'rate_limit_error';
  retryAfter: number;
}

class ValidationError extends EmailVerifyError {
  code: 'validation_error';
  field?: string;
}

Configuración

const client = new EmailVerify({
  apiKey: process.env.EMAILVERIFY_API_KEY!,
  timeout: 30000,
  retries: 3,
});

Verificación individual

Uso básico

const result = await client.verify('user@example.com');

// TypeScript conoce todas las propiedades y sus tipos
if (result.status === 'valid') {
  console.log(`Puntuación: ${result.score}`);
  console.log(`Entregable: ${result.result.deliverable}`);
}

Con opciones

interface VerifyOptions {
  smtpCheck?: boolean;
  timeout?: number;
}

const result = await client.verify('user@example.com', {
  smtpCheck: true,
  timeout: 5000,
});

Guardias de tipos

function isValidEmail(result: VerificationResult): boolean {
  return result.status === 'valid' && result.score >= 0.8;
}

function isSafeForMarketing(result: VerificationResult): boolean {
  return (
    result.status === 'valid' &&
    !result.result.disposable &&
    !result.result.role
  );
}

Verificación masiva

Enviar trabajo

const emails: string[] = [
  'user1@example.com',
  'user2@example.com',
];

const job: BulkJob = await client.verifyBulk(emails);

Obtener estado

const status: BulkJob = await client.getBulkJobStatus(job.id);

// Verificación de estado con tipos seguros
switch (status.status) {
  case 'pending':
    console.log('El trabajo está en cola');
    break;
  case 'processing':
    console.log(`Progreso: ${status.processed}/${status.total}`);
    break;
  case 'completed':
    console.log(`¡Completado! Válidos: ${status.valid}, Inválidos: ${status.invalid}`);
    break;
  case 'failed':
    console.log('El trabajo falló');
    break;
}

Obtener resultados

const results: BulkJobResults = await client.getBulkJobResults(job.id);

results.results.forEach((result) => {
  console.log(`${result.email}: ${result.status}`);
});

Manejo de errores

import {
  EmailVerify,
  EmailVerifyError,
  AuthenticationError,
  RateLimitError,
  ValidationError,
} from '@emailverify/node';

async function verifyEmail(email: string): Promise<VerificationResult | null> {
  try {
    return await client.verify(email);
  } catch (error) {
    if (error instanceof AuthenticationError) {
      console.error('Clave API inválida');
    } else if (error instanceof RateLimitError) {
      console.error(`Límite de tasa alcanzado. Reintentar después de ${error.retryAfter}s`);
    } else if (error instanceof ValidationError) {
      console.error(`Entrada inválida: ${error.message}`);
    } else if (error instanceof EmailVerifyError) {
      console.error(`Error de API: ${error.message}`);
    }
    return null;
  }
}

Utilidades genéricas

Función de validación con tipos seguros

type ValidationResult =
  | { valid: true; score: number }
  | { valid: false; reason: string; message: string };

async function validateEmail(email: string): Promise<ValidationResult> {
  const result = await client.verify(email);

  if (result.status === 'invalid') {
    return {
      valid: false,
      reason: 'invalid_email',
      message: 'Esta dirección de correo electrónico es inválida',
    };
  }

  if (result.result.disposable) {
    return {
      valid: false,
      reason: 'disposable',
      message: 'No se permiten correos electrónicos desechables',
    };
  }

  return {
    valid: true,
    score: result.score,
  };
}

Procesamiento de resultados personalizado

interface ProcessedResult {
  email: string;
  isValid: boolean;
  riskLevel: 'low' | 'medium' | 'high';
  flags: string[];
}

function processResult(result: VerificationResult): ProcessedResult {
  const flags: string[] = [];

  if (result.result.disposable) flags.push('disposable');
  if (result.result.role) flags.push('role');
  if (result.result.catchall) flags.push('catchall');
  if (result.result.free) flags.push('free');

  let riskLevel: 'low' | 'medium' | 'high';
  if (result.score >= 0.8) {
    riskLevel = 'low';
  } else if (result.score >= 0.5) {
    riskLevel = 'medium';
  } else {
    riskLevel = 'high';
  }

  return {
    email: result.email,
    isValid: result.status === 'valid',
    riskLevel,
    flags,
  };
}

Integración con frameworks

Next.js App Router

// app/api/verify/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { EmailVerify, VerificationResult } from '@emailverify/node';

const client = new EmailVerify({
  apiKey: process.env.EMAILVERIFY_API_KEY!,
});

interface RequestBody {
  email: string;
}

interface ResponseBody {
  valid: boolean;
  score?: number;
  message?: string;
}

export async function POST(request: NextRequest): Promise<NextResponse<ResponseBody>> {
  const body: RequestBody = await request.json();

  try {
    const result: VerificationResult = await client.verify(body.email);

    if (result.status === 'invalid') {
      return NextResponse.json(
        { valid: false, message: 'Dirección de correo electrónico inválida' },
        { status: 400 }
      );
    }

    return NextResponse.json({
      valid: true,
      score: result.score,
    });
  } catch (error) {
    return NextResponse.json(
      { valid: false, message: 'Verificación fallida' },
      { status: 500 }
    );
  }
}

Servicio de NestJS

// email-verification.service.ts
import { Injectable } from '@nestjs/common';
import { EmailVerify, VerificationResult } from '@emailverify/node';

@Injectable()
export class EmailVerificationService {
  private client: EmailVerify;

  constructor() {
    this.client = new EmailVerify({
      apiKey: process.env.EMAILVERIFY_API_KEY!,
    });
  }

  async verify(email: string): Promise<VerificationResult> {
    return this.client.verify(email);
  }

  async isValidForRegistration(email: string): Promise<boolean> {
    const result = await this.verify(email);
    return (
      result.status === 'valid' &&
      !result.result.disposable &&
      result.score >= 0.7
    );
  }
}

Express con TypeScript

import express, { Request, Response } from 'express';
import { EmailVerify, VerificationResult } from '@emailverify/node';

const app = express();
app.use(express.json());

const client = new EmailVerify({
  apiKey: process.env.EMAILVERIFY_API_KEY!,
});

interface VerifyRequest {
  email: string;
}

interface VerifyResponse {
  success: boolean;
  data?: VerificationResult;
  error?: string;
}

app.post('/verify', async (
  req: Request<{}, VerifyResponse, VerifyRequest>,
  res: Response<VerifyResponse>
) => {
  try {
    const result = await client.verify(req.body.email);
    res.json({ success: true, data: result });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error instanceof Error ? error.message : 'Error desconocido',
    });
  }
});

Integración con esquema Zod

import { z } from 'zod';
import { EmailVerify } from '@emailverify/node';

const client = new EmailVerify({
  apiKey: process.env.EMAILVERIFY_API_KEY!,
});

const emailSchema = z.string().email().refine(
  async (email) => {
    try {
      const result = await client.verify(email);
      return result.status === 'valid';
    } catch {
      return false;
    }
  },
  { message: 'La dirección de correo electrónico no es válida o entregable' }
);

// Uso
async function validateEmail(email: string) {
  return emailSchema.parseAsync(email);
}

Mejores prácticas

1. Usar verificaciones estrictas de nulos

// tsconfig.json
{
  "compilerOptions": {
    "strict": true,
    "strictNullChecks": true
  }
}

// Código con manejo adecuado de nulos
const result = await client.verify(email);
if (result.result.deliverable !== null) {
  console.log(`Entregable: ${result.result.deliverable}`);
}

2. Crear envoltorios con tipos seguros

// verification.ts
export async function verifyAndCategorize(email: string) {
  const result = await client.verify(email);

  return {
    email: result.email,
    category: categorize(result),
    score: result.score,
    details: result.result,
  } as const;
}

function categorize(result: VerificationResult) {
  if (result.status !== 'valid') return 'invalid';
  if (result.result.disposable) return 'disposable';
  if (result.result.role) return 'role';
  return 'valid';
}

Próximos pasos

On this page