Skip to Content
APICoreConnectivityClient

ConnectivityClient

Singleton client that detects connectivity, manages offline action queueing, retry, and deduplication.

Creating an instance

import { ConnectivityClient, getConnectivityClient } from '@connectivity-js/core'; // Option 1: static method const client = ConnectivityClient.getInstance(options); // Option 2: shorthand (identical) const client = getConnectivityClient(options);

options apply only on the first call. Subsequent calls return the existing instance.

ConnectivityClientOptions

FieldTypeDefaultDescription
detectorsDetector[](required)Connectivity detection strategies
initialStatusConnectivityStatus'unknown'Initial state
gracePeriodMsnumber0Grace period before offline transition (ms)
onJobError(error, job) => voidCalled when a job reaches terminal failure
maxQueueSizenumberundefinedMaximum number of jobs allowed in the queue. Throws when exceeded.
defaultOptions.actionsActionOptionsGlobal action defaults

Methods

start()

Activates registered detectors. Auto-called by ConnectivityProvider. Duplicate calls are no-ops. Throws if the client has been destroyed.

client.start();

stop()

Stops all detectors without clearing actions, jobs, or listeners. Auto-called on ConnectivityProvider unmount. Call start() to resume.

client.stop(); // later… client.start(); // detectors resume, actions/jobs preserved

destroy()

Terminal. Stops detectors and clears all actions, jobs, and listeners. After destroy(), start() and execute() will throw. Use resetInstance() for singletons or create a new instance.

client.destroy();

getState()

Returns an immutable snapshot of current connectivity state.

const state = client.getState(); // { status: 'online', since: 1700000000000, quality: { rttMs: 42 } }

subscribe(listener)

Subscribes to connectivity state changes.

const unsubscribe = client.subscribe((state, transition) => { console.log(state.status, transition?.from, '→', transition?.to); });
ParameterType
listener(state: ConnectivityState, transition?: ConnectivityTransition) => void
Returns() => void (unsubscribe)

registerAction(actionKey, action)

Registers an action. Re-registering the same key overwrites the previous one.

client.registerAction('save', { request: (input) => api.save(input), options: { whenOffline: 'queue', retry: { maxAttempts: 3, backoffMs: (n) => n * 1_000 }, dedupeKey: (input) => (input as { id: string }).id, }, });

execute(actionKey, input)

Executes a registered action. Supports two call styles:

String key (backward compatible):

const result = await client.execute('save', { id: '1', data: 'hello' }); if (result.enqueued) { console.log(result.jobId); } else { console.log(result.result); }
ParameterType
actionKeystring
inputunknown
ReturnsPromise<{ enqueued: true; jobId: string } | { enqueued: false; result: unknown }>

Type-safe with actionOptions():

Pass an actionOptions() config to get fully inferred TInput and TResult. The action is auto-registered if not already present.

import { actionOptions } from '@connectivity-js/core'; const saveAction = actionOptions({ actionKey: 'save', request: (input: { id: string; data: string }) => api.save(input), whenOffline: 'queue', dedupeKey: (input) => input.id, }); const result = await client.execute(saveAction, { id: '1', data: 'hello' }); if (!result.enqueued) { console.log(result.result); // fully typed as the return of api.save() }

getQueue()

Returns a snapshot of the entire job queue.

const jobs = client.getQueue();

getActionQueue(actionKey)

Returns jobs for a specific action. Returns the same reference if unchanged.

const saveJobs = client.getActionQueue('save');

subscribeQueue(listener)

Subscribes to job queue changes.

const unsubscribe = client.subscribeQueue(() => { const jobs = client.getQueue(); console.log('queued:', jobs.filter(j => j.status === 'queued').length); });

retry(jobId)

Retries a failed or queued job. Resets the attempt counter to 0, allowing the full retry cycle.

await client.retry('job_1_1700000000000');

cancel(jobId)

Cancels a queued job.

client.cancel('job_1_1700000000000');

flush(options?)

Manually flushes pending jobs.

await client.flush(); await client.flush({ onlyActionKey: 'save' });

setOnJobError(handler)

Updates the error handler called when a job reaches terminal failure. Used by ConnectivityProvider to track the latest onJobError callback via ref. Pass undefined to remove the handler.

client.setOnJobError((error, job) => { console.error(`Job ${job.id} failed:`, error); reportError(error); });
ParameterType
handler((error: unknown, job: QueuedJob) => void) | undefined

resetInstance() (static)

Destroys the singleton. Testing only.

afterEach(() => { ConnectivityClient.resetInstance(); });
Last updated on