Skip to content
Velo

velo.watch

Opens a live subscription from a completed subscription request. The connection starts immediately, and the returned promise resolves with a reusable watcher once the subscription is live.

The subscription kind determines the returned watcher and its events:

RequestWatcherEvents
velo.news.feed()NewsWatcherstory, edit, delete, error, close
velo.channels.feed(...)ChannelsWatchererror, close

Imports

import { Velo } from 'velo-sdk';

Examples

News feeds

Pass listeners with the initial call so they are attached before the connection opens:

import { Velo, news } from 'velo-sdk';
 
const velo = new Velo({ apiKey: process.env.VELO_API_KEY! });
 
const watcher = await velo.watch(news.feed(), {
  on: {
    story: (story) => console.log('New:', story.headline),
    edit: (story) => console.log('Edited:', story.headline),
    delete: ({ id }) => console.log('Deleted:', id),
    error: (error) => console.error(error),
  },
});
 
// Permanently close the subscription when it is no longer needed.
watcher.close();

on can instead be one listener receiving every event as a discriminated union:

const watcher = await velo.watch(news.feed(), {
  on: (event) => {
    if (event.type === 'story') {
      console.log(event.event.headline);
    }
  },
});

Market-data feeds

Attach data listeners to the channels before watching the feed. The watcher's on option receives connection events:

const openInterest = velo.channels.openInterest({ coin: 'BTC' }, { metric: 'coins' }).on({
  data: (entries) => console.table(entries),
  error: ({ reason }) => console.error('Channel error:', reason),
});
 
const channelsWatcher = await velo.watch(velo.channels.feed([openInterest]), {
  on: {
    error: (error) => console.error('Connection error:', error),
    close: ({ code, reason }) => console.log('Connection closed:', code, reason),
  },
});
 
// Later:
channelsWatcher.close();

Definition

function watch<K extends WatchableKind, P extends WatchParams<K>>(
  input: WatchInput<K, P>,
  options?: WatchOptions<K>,
): Promise<Watcher<K>>;

Parameters

input

  • Type: WatchInput<K, P>

A direct subscription request or completed subscription builder. Query requests cannot be watched; pass them to velo.query() or, when supported, velo.stream().

options

  • Type: WatchOptions<K>
  • Optional

Both feed kinds share these connection settings. The available on events are inferred from the subscription kind:

PropertyTypeDescription
onlistenersA map of watcher-event listeners, or one function receiving every watcher event tagged with type. Channel data and channel errors use the channel's own .on() listeners.
reconnectboolean | Partial<ResumeOptions>Controls retries for the initial connection and automatic reconnection after unexpected drops. Enabled by default.
signalAbortSignalPermanently closes the watcher when aborted, including during an initial connection or backoff.
heartbeatTimeoutnumberMaximum time between heartbeat messages in milliseconds. Defaults to 300_000.
connectTimeoutnumberMaximum time for each connection attempt in milliseconds. Defaults to 30_000.
onListenerError(error: unknown) => unknownHandles errors thrown or rejected by event listeners.

For channel feeds, on receives these connection events:

EventPayloadDescription
errorVeloErrorA connection failure, such as a heartbeat timeout or a malformed message that cannot be attributed to a channel.
closeWebSocketCloseEventThe connection's close code, reason, and wasClean status.

Listeners supplied through on are attached before connecting, so an event cannot arrive between opening the subscription and registering its initial listeners. Channel listeners can also receive data before the promise resolves.

Reconnection

Automatic reconnection uses jittered exponential backoff:

reconnect valueBehavior
Omitted or trueRetries the initial connection up to 5 times, then reconnects indefinitely after unexpected drops.
falseMakes one initial attempt and does not reconnect after a drop.
An options objectOverrides retries, baseDelayMs, or maxDelayMs. Omitting retries keeps the default limits: up to 5 initial retries, then unlimited reconnection attempts.

The default base delay is 500 milliseconds and the maximum delay is 30_000 milliseconds. The initial connection makes one immediate attempt followed by at most retries retries. After a drop, the watcher makes at most retries reconnection attempts, or unlimited attempts when retries is omitted.

A connection that stays open for 5 seconds ends the outage, so the next drop starts again from the base delay with a fresh retry budget. A connection that drops sooner continues the current backoff and retry count.

Retrying stops immediately when the server refuses the connection with a non-retryable HTTP error, such as 401 or 403 for an invalid API key. Network failures, timeouts (408), rate limits (429), and 500, 502, 503, or 504 server errors are retried.

Intentional endings do not reconnect: disconnect() leaves the watcher reusable, while close() and aborting signal close it permanently. Events missed while disconnected are not replayed.

Return Type

  • Type: Promise<Watcher<K>>

The promise resolves the first time the subscription becomes live. With the default reconnect policy, it remains pending while failed initial connections are retried. It rejects when reconnection is disabled, the initial retry budget is exhausted, the server refuses the connection with a non-retryable error, or the operation is aborted before connecting.

For channels, resolution means all required sockets are open and subscription commands have been sent. It does not confirm that every channel is delivering data. A server rejection can arrive afterward at that channel's error listener.

The resolved watcher exposes a read-only state and the following methods:

MemberDescription
stateOne of idle, connecting, open, disconnected, or closed.
.on(type, listener)Adds a watcher-event listener and returns the watcher.
.off(type, listener)Removes a watcher-event listener and returns the watcher.
.connect()Reopens an intentionally disconnected watcher. Returns Promise<void>. Concurrent calls share one attempt.
.disconnect()Disconnects intentionally and leaves the watcher idle, preserving its subscriptions and listeners for reuse.
.close()Permanently closes the watcher and clears its listeners. Calling it repeatedly is safe.

ChannelsWatcher also provides these methods:

MethodDescription
.subscribe(channel)Adds a channel without reconnecting the existing subscriptions. Returns void.
.unsubscribe(channel)Removes a channel previously passed to the feed or subscribe(). Returns void.

See Managing subscriptions for adding and removing channels, and news.feed() for news event payloads.

Errors

Invalid options throw synchronously. Connection failures during the initial sequence reject the promise only after reconnection is disabled, its retry budget is exhausted, or the server refuses the connection with a non-retryable error. Failures after the watcher has opened are delivered through its typed error event while automatic reconnection continues according to the selected policy.

Failures attributable to one channel go to its own error listener while other channels continue. See Error handling for server rejection and decoding errors.

Errors from user listeners do not close the connection. They are passed to onListenerError, or reported through the runtime's default error reporting when no handler is supplied.