or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

async-operations.mdauthentication.mdcache.mderrors.mdindex.mdlogging.mdtransport.mduser-agent.md
tile.json

tessl/npm-algolia--client-common

Common package for the Algolia JavaScript API client providing shared utilities for authentication, transport, caching, and async operations.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/@algolia/client-common@5.35.x

To install, run

npx @tessl/cli install tessl/npm-algolia--client-common@5.35.0

index.mddocs/

Algolia Client Common

Algolia Client Common is a foundational TypeScript library providing shared utilities and functionality for the Algolia JavaScript API client ecosystem. It includes core components for authentication, transport layer management, caching mechanisms, logging capabilities, and async operations with retry logic.

Package Information

  • Package Name: @algolia/client-common
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install @algolia/client-common

Core Imports

import {
  createAuth,
  createAlgoliaAgent,
  createTransporter,
  createMemoryCache,
  createIterablePromise
} from "@algolia/client-common";

For CommonJS:

const {
  createAuth,
  createAlgoliaAgent,
  createTransporter,
  createMemoryCache,
  createIterablePromise
} = require("@algolia/client-common");

Basic Usage

import {
  createAuth,
  createAlgoliaAgent,
  createTransporter,
  createMemoryCache,
  createNullLogger
} from "@algolia/client-common";

// Create authentication
const auth = createAuth("YourApplicationID", "YourAPIKey");

// Create user agent
const algoliaAgent = createAlgoliaAgent("5.35.0").add({
  segment: "MyClient",
  version: "1.0.0"
});

// Create caches
const hostsCache = createMemoryCache();
const requestsCache = createMemoryCache();
const responsesCache = createMemoryCache();

// Create logger
const logger = createNullLogger();

// Example transporter setup (requires a requester implementation)
const transporter = createTransporter({
  hosts: [
    { url: "algolia.net", accept: "readWrite", protocol: "https" }
  ],
  hostsCache,
  logger,
  requester: yourRequesterImplementation, // Must be provided
  requestsCache,
  responsesCache,
  timeouts: { connect: 2000, read: 5000, write: 30000 },
  baseHeaders: auth.headers(),
  baseQueryParameters: auth.queryParameters(),
  algoliaAgent
});

Architecture

Algolia Client Common is built around several key architectural components:

  • Authentication Layer: Handles API key authentication with configurable modes (headers vs query parameters)
  • Transport System: Manages HTTP requests with retry logic, host failover, and caching
  • Cache Implementations: Multiple cache types (memory, localStorage, null, fallback) for different environments
  • Logging Interface: Structured logging with debug, info, and error levels
  • User Agent Management: Automatic user agent generation and extension for request tracking
  • Async Utilities: Promise-based retry mechanisms with validation and timeout handling

Capabilities

Authentication

Core authentication functionality for Algolia API access with configurable credential placement.

function createAuth(
  appId: string,
  apiKey: string,
  authMode?: AuthMode
): {
  readonly headers: () => Headers;
  readonly queryParameters: () => QueryParameters;
};

type AuthMode = 'WithinHeaders' | 'WithinQueryParameters';

Authentication

User Agent Management

User agent creation and management for client identification and tracking.

function createAlgoliaAgent(version: string): AlgoliaAgent;

function getAlgoliaAgent(options: GetAlgoliaAgent): AlgoliaAgent;

interface AlgoliaAgent {
  value: string;
  add: (options: AlgoliaAgentOptions) => AlgoliaAgent;
}

interface AlgoliaAgentOptions {
  segment: string;
  version?: string;
}

User Agent Management

Cache System

Comprehensive caching system with multiple implementations for different environments and use cases.

function createMemoryCache(options?: MemoryCacheOptions): Cache;
function createNullCache(): Cache;
function createBrowserLocalStorageCache(options: BrowserLocalStorageOptions): Cache;
function createFallbackableCache(options: FallbackableCacheOptions): Cache;

interface Cache {
  get: <TValue>(
    key: Record<string, any> | string,
    defaultValue: () => Promise<TValue>,
    events?: CacheEvents<TValue>
  ) => Promise<TValue>;
  set: <TValue>(key: Record<string, any> | string, value: TValue) => Promise<TValue>;
  delete: (key: Record<string, any> | string) => Promise<void>;
  clear: () => Promise<void>;
}

Cache System

Transport Layer

HTTP transport system with retry logic, host failover, and request/response caching.

function createTransporter(options: TransporterOptions): Transporter;

function createStatefulHost(host: Host, status?: StatefulHost['status']): StatefulHost;

interface Transporter extends TransporterOptions {
  request: <TResponse>(
    baseRequest: Request,
    baseRequestOptions?: RequestOptions
  ) => Promise<TResponse>;
}

Transport Layer

Async Operations

Promise-based retry mechanisms with validation, aggregation, and timeout handling.

function createIterablePromise<TResponse>(
  options: CreateIterablePromise<TResponse>
): Promise<TResponse>;

interface CreateIterablePromise<TResponse> {
  func: (previousResponse?: TResponse) => Promise<TResponse>;
  validate: (response: TResponse) => boolean | PromiseLike<boolean>;
  aggregator?: (response: TResponse) => unknown | PromiseLike<unknown>;
  error?: {
    validate: (response: TResponse) => boolean | PromiseLike<boolean>;
    message: (response: TResponse) => string | PromiseLike<string>;
  };
  timeout?: () => number | PromiseLike<number>;
}

Async Operations

Logging

Structured logging interface with debug, info, and error levels.

function createNullLogger(): Logger;

interface Logger {
  debug: (message: string, args?: any) => Promise<void>;
  info: (message: string, args?: any) => Promise<void>;
  error: (message: string, args?: any) => Promise<void>;
}

Logging

Error Handling

Comprehensive error system with specific error types for different failure scenarios.

class AlgoliaError extends Error {
  name: string;
  constructor(message: string, name: string);
}

class ApiError extends ErrorWithStackTrace {
  status: number;
  constructor(message: string, status: number, stackTrace: StackFrame[], name?: string);
}

class RetryError extends ErrorWithStackTrace {
  constructor(stackTrace: StackFrame[]);
}

Error Handling

Core Types

type Headers = Record<string, string>;
type QueryParameters = Record<string, any>;
type Method = 'DELETE' | 'GET' | 'PATCH' | 'POST' | 'PUT';

interface Host {
  url: string;
  accept: 'read' | 'readWrite' | 'write';
  protocol: 'http' | 'https';
  port?: number;
}

interface Request {
  method: Method;
  path: string;
  queryParameters: QueryParameters;
  data?: Array<Record<string, any>> | Record<string, any>;
  headers: Headers;
  cacheable?: boolean;
  useReadTransporter?: boolean;
}

interface Response {
  content: string;
  isTimedOut: boolean;
  status: number;
}

interface Timeouts {
  connect: number;
  read: number;
  write: number;
}

Client Creation Types

type CreateClientOptions = Omit<TransporterOptions, 'baseHeaders' | 'baseQueryParameters' | 'hosts' | 'algoliaAgent'> &
  Partial<Pick<TransporterOptions, 'baseHeaders' | 'baseQueryParameters' | 'hosts'>> & {
    appId: string;
    apiKey: string;
    authMode?: AuthMode;
    algoliaAgents: AlgoliaAgentOptions[];
  };

type ClientOptions = Partial<Omit<CreateClientOptions, 'apiKey' | 'appId'>>;

Constants

const DEFAULT_CONNECT_TIMEOUT_BROWSER = 1000;
const DEFAULT_READ_TIMEOUT_BROWSER = 2000;
const DEFAULT_WRITE_TIMEOUT_BROWSER = 30000;
const DEFAULT_CONNECT_TIMEOUT_NODE = 2000;
const DEFAULT_READ_TIMEOUT_NODE = 5000;
const DEFAULT_WRITE_TIMEOUT_NODE = 30000;