EmailVerify LogoEmailVerify

TypeScript SDK

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

O SDK TypeScript do EmailVerify fornece definições de tipo completas para verificação de e-mail type-safe em projetos TypeScript.

O SDK TypeScript compartilha o mesmo pacote do SDK Node.js, mas com suporte completo a TypeScript.

Instalação

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

Início 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); // Type: 'valid' | 'invalid' | 'unknown' | 'accept_all'

Definições de Tipo

Opções do Cliente

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

Resultado da Verificação

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;
}

Bulk Job Types

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 Erro

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;
}

Configuração

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

Verificação Individual

Basic Usage

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

// TypeScript knows all properties and their types
if (result.status === 'valid') {
  console.log(`Score: ${result.score}`);
  console.log(`Deliverable: ${result.result.deliverable}`);
}

Com Opções

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

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

Type Guards

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

Verificação em Lote

Enviar Trabalho

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

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

Get Status

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

// Type-safe status checking
switch (status.status) {
  case 'pending':
    console.log('Job is queued');
    break;
  case 'processing':
    console.log(`Progress: ${status.processed}/${status.total}`);
    break;
  case 'completed':
    console.log(`Done! Valid: ${status.valid}, Invalid: ${status.invalid}`);
    break;
  case 'failed':
    console.log('Job failed');
    break;
}

Obter Resultados

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

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

Tratamento de Erros

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('Invalid API key');
    } else if (error instanceof RateLimitError) {
      console.error(`Rate limited. Retry after ${error.retryAfter}s`);
    } else if (error instanceof ValidationError) {
      console.error(`Invalid input: ${error.message}`);
    } else if (error instanceof EmailVerifyError) {
      console.error(`API error: ${error.message}`);
    }
    return null;
  }
}

Generic Utilities

Função de Validação Type-Safe

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: 'This email address is invalid',
    };
  }

  if (result.result.disposable) {
    return {
      valid: false,
      reason: 'disposable',
      message: 'Disposable emails are not allowed',
    };
  }

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

Processamento Personalizado de Resultado

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,
  };
}

Integração com 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: 'Invalid email address' },
        { status: 400 }
      );
    }

    return NextResponse.json({
      valid: true,
      score: result.score,
    });
  } catch (error) {
    return NextResponse.json(
      { valid: false, message: 'Verification failed' },
      { status: 500 }
    );
  }
}

Serviço 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 com 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 : 'Unknown error',
    });
  }
});

Integração com Schema 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: 'Email address is not valid or deliverable' }
);

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

Melhores Práticas

1. Use Strict Null Checks

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

// Code with proper null handling
const result = await client.verify(email);
if (result.result.deliverable !== null) {
  console.log(`Deliverable: ${result.result.deliverable}`);
}

2. Crie Wrappers Type-Safe

// 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 Passos

On this page