Skip to content

Padrão de Projeto: Construindo um Cliente de API Reutilizável ​

NOTE

Nota de Esclarecimento: Este documento ensina como criar uma camada de cliente HTTP reutilizável no seu próprio projeto. Este código é um exemplo conceitual de engenharia e não constitui um SDK oficial publicado pelo SusConecta.


🎯 Objetivo ​

Criar uma classe ou módulo cliente limpo, fortemente tipado e com tratamento automático de:

  1. Base URL e injeção do header de autorização;
  2. Timeouts de rede configuráveis;
  3. Tratamento padronizado de respostas de erro e sucesso;
  4. Captura de metadados canônicos da API (X-Analytics-Release-Id, X-Report-Fingerprint, Retry-After).

💻 Implementação de Referência em TypeScript ​

typescript
// src/integrations/susconecta/client.ts

export interface SusConectaConfig {
  baseUrl?: string;
  apiKey: string;
  timeoutMs?: number;
}

export interface AnalyticsQueryPayload {
  metrics: string[];
  group_by?: string[];
  filters?: Array<{
    dimension: string;
    operator: "EQ" | "IN" | "BETWEEN" | "LIKE";
    value: string | number | (string | number)[];
  }>;
  reference_period?: string;
  limit?: number;
  offset?: number;
}

export interface AnalyticsQueryResponse<T = any> {
  status: "success" | "error";
  data: T[];
  meta: {
    catalog_version: string;
    analytics_release_id: string;
    reference_period: string;
    domain: string;
    scope: {
      type: string;
      states: string[];
      covered_municipality_count?: number;
    };
    pagination?: {
      limit: number;
      offset: number;
      total_groups?: number;
      has_more: boolean;
    };
  };
}

export class SusConectaClientError extends Error {
  constructor(
    public readonly statusCode: number,
    public readonly code: string,
    message: string,
    public readonly details?: any,
  ) {
    super(`SusConecta API Error [HTTP ${statusCode}] (${code}): ${message}`);
    this.name = "SusConectaClientError";
  }
}

export class SusConectaClient {
  private readonly baseUrl: string;
  private readonly apiKey: string;
  private readonly timeoutMs: number;

  constructor(config: SusConectaConfig) {
    if (!config.apiKey) {
      throw new Error("SusConectaClient: 'apiKey' é obrigatória.");
    }
    this.baseUrl = (
      config.baseUrl || "https://api.susconecta.com.br"
    ).replace(/\/+$/, "");
    this.apiKey = config.apiKey;
    this.timeoutMs = config.timeoutMs || 20000;
  }

  private async request<T>(
    path: string,
    options: RequestInit = {},
  ): Promise<T> {
    const url = `${this.baseUrl}${path.startsWith("/") ? path : `/${path}`}`;
    const headers = new Headers(options.headers);

    headers.set("Authorization", `Bearer ${this.apiKey}`);
    headers.set("Accept", "application/json");
    if (options.body && typeof options.body === "string") {
      headers.set("Content-Type", "application/json");
    }

    const response = await fetch(url, {
      ...options,
      headers,
      signal: AbortSignal.timeout(this.timeoutMs),
    }).catch((err) => {
      if (err.name === "TimeoutError" || err.name === "AbortError") {
        throw new SusConectaClientError(
          408,
          "REQUEST_TIMEOUT",
          `Requisição excedeu o tempo limite de ${this.timeoutMs}ms.`,
        );
      }
      throw new SusConectaClientError(0, "NETWORK_ERROR", err.message);
    });

    if (!response.ok) {
      let errorBody: any = {};
      try {
        errorBody = await response.json();
      } catch {
        errorBody = { message: response.statusText };
      }

      throw new SusConectaClientError(
        response.status,
        errorBody.code || "UNKNOWN_ERROR",
        errorBody.message || "Erro não especificado pela API.",
        errorBody.details,
      );
    }

    return (await response.json()) as T;
  }

  /**
   * Consulta o catálogo analítico oficial de métricas e dimensões
   */
  async getCatalog(): Promise<any> {
    return this.request("/v1/analytics/catalog", { method: "GET" });
  }

  /**
   * Executa consulta analítica sobre métricas padronizadas
   */
  async queryAnalytics(
    payload: AnalyticsQueryPayload,
  ): Promise<AnalyticsQueryResponse> {
    return this.request<AnalyticsQueryResponse>("/v1/analytics/query", {
      method: "POST",
      body: JSON.stringify(payload),
    });
  }

  /**
   * Consulta listagem de municípios homologados no escopo territorial
   */
  async getMunicipalities(stateUf?: string): Promise<any> {
    const query = stateUf ? `?state=${encodeURIComponent(stateUf)}` : "";
    return this.request(`/v1/municipalities${query}`, { method: "GET" });
  }

  /**
   * Consulta estabelecimentos de saúde cadastrados no CNES
   */
  async getFacilities(
    params: {
      municipality_ibge?: number;
      state?: string;
      limit?: number;
      offset?: number;
    } = {},
  ): Promise<any> {
    const searchParams = new URLSearchParams();
    if (params.municipality_ibge)
      searchParams.set("municipality_ibge", String(params.municipality_ibge));
    if (params.state) searchParams.set("state", params.state);
    if (params.limit) searchParams.set("limit", String(params.limit));
    if (params.offset) searchParams.set("offset", String(params.offset));

    const query = searchParams.toString() ? `?${searchParams.toString()}` : "";
    return this.request(`/v1/facilities${query}`, { method: "GET" });
  }
}

🚀 Exemplo de Uso na Sua Aplicação ​

typescript
import { SusConectaClient } from "./client.js";

const client = new SusConectaClient({
  apiKey: process.env.SUSCONECTA_API_KEY!,
  baseUrl: process.env.SUSCONECTA_API_BASE_URL,
});

async function main() {
  try {
    const result = await client.queryAnalytics({
      metrics: ["bed_capacity_existing", "bed_capacity_sus"],
      group_by: ["state"],
      filters: [{ dimension: "state", operator: "IN", value: ["GO", "MT"] }],
    });

    console.log("Release:", result.meta.analytics_release_id);
    console.log("Dados:", result.data);
  } catch (error) {
    if (error instanceof SusConectaClientError) {
      console.error(`Falha [${error.code}]:`, error.message);
    }
  }
}

main();

SusConecta — Plataforma Canônica de Dados Públicos de Saúde do SUS.