Skip to main content

Module: RouterClient

For communications amongst desktop services, components, or outside the container entirely, Finsemble provides an event infrastructure with high level protocols. The Router is the center of this functionality, sending and receiving messages between windows.

See the Router tutorial for an overview.

Interfaces

Type Aliases

ListenerCallback

Ƭ ListenerCallback<T>: (err: null | string, response: ListenerResponse<T>) => void

Type parameters

NameType
Tany

Type declaration

▸ (err, response): void

Parameters
NameType
errnull | string
responseListenerResponse<T>
Returns

void


ListenerResponse

Ƭ ListenerResponse<T>: TransmitMessageFromService<T> & { originatedHere: () => void }

Type parameters

NameType
Tany

PublishCallback

Ƭ PublishCallback<T>: (err: null | string, data: PublishHookMessage<T>) => void

Type parameters

NameType
Tany

Type declaration

▸ (err, data): void

Parameters
NameType
errnull | string
dataPublishHookMessage<T>
Returns

void


PublishHookMessage

Ƭ PublishHookMessage<T>: PublishMessageFromService & { sendNotifyToAllSubscribers: (err: null | string, data: T) => void }

Type parameters

NameType
Tany

QueryResponse

Ƭ QueryResponse<T>: Object

Type parameters

NameType
Tany

Type declaration

NameType
data?T
headerRouterHeader

QueryResponseCallback

Ƭ QueryResponseCallback<T>: (err: null | string, response: QueryResponse<T>) => void

Type parameters

NameType
Tany

Type declaration

▸ (err, response): void

Parameters
NameType
errnull | string
responseQueryResponse<T>
Returns

void


ResponderMessage

Ƭ ResponderMessage<Q, R>: QueryMessageFromService<Q> & { originatedHere: () => void ; sendQueryResponse: (error: StandardError, data?: R) => any }

Q = type of query (sent by client call to query() ) R = type of response (returned by server call to sendQueryResponse() )

Type parameters

NameType
Qany
Rany

RouterConfig

Ƭ RouterConfig: Object

Type declaration

NameTypeDescription
routerDomainRoot?stringOnly required for shared worker
transportNamestringWhich transport to enable. Use Startup/RouterConfig.getRecommendedTransport() Set this to "FinsembleTransport" when in freestanding mode.
transportSettings?RouterTransportSettings-
windowNamestring-

RouterListenerUnsubscribe

Ƭ RouterListenerUnsubscribe: () => void

Type declaration

▸ (): void

Call this to unsubscribe to a prior listener call.

Returns

void


RouterTransportSettings

Ƭ RouterTransportSettings: Object

Type declaration

NameType
FinsembleTransport?{ serverAddress?: string }
FinsembleTransport.serverAddress?string

StandardQueryResponse

Ƭ StandardQueryResponse<T>: Object

Type parameters

NameType
Tany

Type declaration

NameType
err?null | string
responseQueryResponse<T>

SubscribeCallback

Ƭ SubscribeCallback<T>: (err: null | string, data: SubscribeHookMessage<T>) => void

Type parameters

NameType
Tany

Type declaration

▸ (err, data): void

Parameters
NameType
errnull | string
dataSubscribeHookMessage<T>
Returns

void


SubscribeHookMessage

Ƭ SubscribeHookMessage<T>: SubscribeMessageFromService & { sendNotifyToSubscriber: (err: null | string, data?: T) => void }

Type parameters

NameType
Tany

SubscriberResponse

Ƭ SubscriberResponse<T>: SendToRouter & { data: T ; header: { error?: string | null ; subscribeID: string ; topic: string } ; originatedHere: () => boolean }

Type parameters

NameType
Tany

UnsubscribeCallback

Ƭ UnsubscribeCallback: (err: null | string, data: UnsubscribeHookMessage) => void

Type declaration

▸ (err, data): void

Parameters
NameType
errnull | string
dataUnsubscribeHookMessage
Returns

void


UnsubscribeHookMessage

Ƭ UnsubscribeHookMessage: UnsubscribeMessageFromService & { removeSubscriber: () => void }

Functions

addListener

addListener<T>(channel, eventHandler): RouterListenerUnsubscribe

Adds a listener for incoming transmit events on the specified channel. Each of the incoming events will trigger the specified event handler. The number of listeners is not limited (either local to this Finsemble window or in a separate Finsemble window).

See transmit for sending a corresponding event message to the listener. See removeListener to remove the listener.

FSBL.Clients.RouterClient.addListener("SomeChannelName", function (error, response) {
if (error) {
Logger.system.error("ChannelA Error: " + JSON.stringify(error));
} else {
var data response.data;
if (response.originatedHere()) {
Logger.system.warn("Received a message from the calling window, ignoring");
} else {
// Logic to perform with data
}
}
});

Type parameters

NameType
Tany

Parameters

NameTypeDescription
channelstringA unique string to identify the channel (must match corresponding transmit channel name).
eventHandlerListenerCallback<T>A callback handling any possible error and the response. Use response.originatedHere() to determine if the message came from the same window. (see example below).

Returns

RouterListenerUnsubscribe

Returns a function that can be called to unsubscribe (convenient alternative to removeListener)


addPubSubResponder

addPubSubResponder<T>(topic, initialState?, params?, callback?): void

Adds a PubSub responder for the specified topic (either a specific string or a regular-expression match). PubSub topics are stateful. New subscribers to the topic are automatically provided the most recent state. Once a responder has been added, other apps can subscribe to and publish state on the topic

See publish() and subscribe().

Only one responder may be set per topic across the entire system (otherwise a warning will show in Central Logger). If another responder is set with an overlapping regular-expression then the responder with an exact string is still guaranteed to get the messages (the regex responder will not receive messages that match a responder with a matching string).

If multiple responders are set with overlapping regular-expressions, then the receiver is indeterminate.

When initializing a responder, hooks can be provided to intercept and manipulate publish, subscribe, and unsubscribe events (see parameters).

// Example, initializing a responder without any optional hooks:
FSBL.Clients.RouterClient.addPubSubResponder("topicABC", { "State": "start" });

// Example, initializing a responder with a regex for matching topics:
FSBL.Clients.RouterClient.addPubSubResponder(\/topicA*\/, { "State": "start" });

// Example, initializing a responder with all three hooks and an initial state:
FSBL.Clients.RouterClient.addPubSubResponder("topicABC", { "State": "start" },
{
subscribeCallback:subscribeCallback,
publishCallback:publishCallback,
unsubscribeCallback:unsubscribeCallback
});

// Example publish hook:
function publishCallback(error, publish) {
if (publish) {
// `publish.data` contains the data that the originating app published.
console.log(publish.data);

// This function must be called to complete the publication. Set the first parameter to `null`
// to complete the publication. Set the first parameter to a string in order to suppress the publication
// and return an error to the publisher.
//
// The second parameter must contain the data that you wish to publish. This data will be sent to all
// subscribers including the originating app. It can be either the originating state (from `publish.data`)
// or a different/manipulated state. This will become the new current state for the topic.
publish.sendNotifyToAllSubscribers(null, { someOtherData: "blah"});
}
}

// Example subscribe hook:
function subscribeCallback(error, subscribe) {
if (subscribe) {
// This function must be called to accept or reject the subscription. Send an error code as the first parameter
// to reject. Send null as the first parameter to accept. Once accepted, the subscriber will receive
// the current topic's state unless the second parameter is provided which will override what is sent
// to the subscriber (but not override the topic's actual internal state).
subscribe.sendNotifyToSubscriber(null, { "NOTIFICATION-STATE": "One" });
}
}

// Example unsubscribe hook:
function unsubscribeCallback(error, unsubscribe) {
if (unsubscribe) {
// This function must be called to accept or reject the unsubscription. Send null (or nothing) as the first
// parameter to accept the unsubscription. Send an error code to reject it.
unsubscribe.removeSubscriber(null);
}
}

Type parameters

NameType
Tany

Parameters

NameTypeDescription
topicstring | RegExp-
initialState?objectThe initial state for the topic (defaults to {}).
params?ObjectOptional hooks
params.publishCallback?PublishCallback<T>This hook is called whenever a remote app publishes new state. [arg2].sendNotifyToAllSubscribers() must be called to complete the publication but can send a different state than what was published by the originating app (the originating publishing app will receive this state on its subscriptions). See example below.
params.subscribeCallback?SubscribeCallback<T>This hook is called whenever a remote app subscribes to this responder's topic. It can be used to deny subscriptions or to run independent code for any new subscription. [arg2].sendNotifyToSubscriber() must be called in order for the responder to complete the subscription, and can optionally provide the subscribing app with a different initial than the topic's current state. See example below.
params.unsubscribeCallback?UnsubscribeCallbackThis hook is called whenever a remote app unsubscribes from this responder's topic. [arg2].removeSubscriber() must be called in order to complete the unsubscription. See example below.
callback?(err?: string | Error, result?: "success") => voidAn optional callback function which should accept a possible error. If addPubSubResponder() failed then the first parameter to the callback will contain the error condition. The most common error is when adding a responder for a topic that already has a responder: "RouterClient.addPubSubResponder: Responder already locally defined for topic ${topic}";

Returns

void


addResponder

addResponder<Q, R>(channel, queryEventHandler): void

Adds a query responder to the specified channel. The responder's queryEventHandler function will receive all incoming queries for the specified channel (whether from this Finsemble window or remote Finsemble windows).

Note: Only one responder is allowed per channel within Finsemble.

See query for sending a corresponding query-event message to this responder.

FSBL.Clients.RouterClient.addResponder("ResponderChannelName", function (error, queryMessage) {
if (error) {
Logger.system.log('addResponder failed: ' + JSON.stringify(error));
} else {
console.log("incoming data=" + queryMessage.data);
var response="Back at ya"; // Responses can be objects or strings
queryMessage.sendQueryResponse(null, response); // The callback must respond, else a timeout will occur on the querying client.
}
});

Type parameters

NameType
Qany
Rany

Parameters

NameTypeDescription
channelstringA unique string to identify the channel (must match corresponding query channel name); only one responder is allowed per channel.
queryEventHandlerStandardErrorCallback<ResponderMessage<Q, R>>A function to handle the incoming query (see example below); note the incoming queryMessage contains a function to send the response.

Returns

void


disconnectAll

disconnectAll(): void

Removes all listeners, responders, and subscribers for this router client -- automatically called when the client is shutting down. Can be called multiple times.

Returns

void


onReady

onReady(cb?): Promise<void>

Checks if Router is ready. May be invoked multiple times. Invokes optional callback and resolves promise when ready, which may be immediately. Router is not ready until underlying transport to Router Service is ready.

deprecated Don't use this method. (Apps that use the FSBL API and wait on the global onReady event are guaranteed that the router will be ready). Internal code should wait on Startup.onReady().

Parameters

NameType
cb?() => void

Returns

Promise<void>

Promise resolves when Router is ready


publish

publish<T>(topic, event): void

Publish to a PubSub Responder, which will trigger a corresponding notification to all subscribers (local in this window or remote in other windows). There may be multiple publishers for a topic (again, in same window or remote windows).

See addPubSubResponder for corresponding addition of a PubSub publisher (i.e., sending notifications to all subscriber). See Subscribe for corresponding subscription published results (in the form of a Notify event).

FSBL.Clients.RouterClient.publish("topicABC", topicState);

Type parameters

NameType
Tany

Parameters

NameTypeDescription
topicstringA unique string representing the topic being published.
eventTThe topic state to be published to all subscribers (unless the PubSub responder optionally modifies in between).

Returns

void


query

query<Q, R>(responderChannel, queryEvent, queryParams?, responseEventHandler?): Promise<StandardQueryResponse<R>>

Sends a query to the responder listening on the specified channel. The responder may be in this Finsemble window or another Finsemble window.

See addResponder to add a responder to receive the query.

FSBL.Clients.RouterClient.query("someChannelName", {}, function (error, queryResponseMessage) {
if (error) {
Logger.system.log('query failed: ' + JSON.stringify(error));
} else {
// process income query response message
var responseData = queryResponseMessage.data;
Logger.system.log('query response: ' + JSON.stringify(queryResponseMessage));
}
});

FSBL.Clients.RouterClient.query("someChannelName", { queryKey: "abc123"}, { timeout: 1000 }, function (error, queryResponseMessage) {
if (!error) {
// process income query response message
var responseData = queryResponseMessage.data;
}
});

Type parameters

NameType
Qany
Rany

Parameters

NameTypeDescription
responderChannelstringA unique string that identifies the channel (must match the channel name on which a responder is listening).
queryEventQThe event message sent to the responder.
queryParams?{ logWhenNoResponder?: boolean ; timeout?: number } | QueryResponseCallback<R>-
responseEventHandler?QueryResponseCallback<R>An event handler to receive the query response (sent from a responder that is listening on this channel).

Returns

Promise<StandardQueryResponse<R>>


removeListener

removeListener(channel, eventHandler): void

Removes an event listener from the specified channel for the specific event handler; only listeners created locally can be removed.

See addListener for corresponding add of a listener.

Parameters

NameTypeDescription
channelstringThe unique channel name from which to remove the listener.
eventHandlerFunctionFunction used for the event handler when the listener was added.

Returns

void


removePubSubResponder

removePubSubResponder(topic): void

Removes a PubSub responder from the specified topic. Only locally created responders (i.e. created in the local window) can be removed.

See addPubSubResponder for corresponding addition of a PubSub responder.

FSBL.Clients.RouterClient.removePubSubResponder("topicABC");

Parameters

NameTypeDescription
topicstring | RegExpUnique topic for responder being removed (may be RegEx, but if so much be exact RegEx used previously with addPubSubResponder).

Returns

void


removeResponder

removeResponder(responderChannel): void

Removes the query responder from the specified channel. Only a locally added responder can be removed (i.e., a responder defined in the same component or service).

See addResponder() for adding a query responder.

FSBL.Clients.RouterClient.removeResponder("someChannelName");

Parameters

NameTypeDescription
responderChannelstringString identifying the channel from which to remove the responder.

Returns

void


subscribe

subscribe<T>(topic, notifyCallback): Object

Subscribe to a PubSub responder. Each responder topic can have many subscribers (local in this window or remote in other windows). Each subscriber immediately (but asynchronously) receives back current state in a notify; new notifications are received for each publish sent to the same topic.

See addPubSubResponder for corresponding addition of a PubSub responder to handle the subscribe. See publish() for how to publish data to subscribers.

var subscribeId = RouterClient.subscribe("topicABC", function(err, notify) {
if (!err) {
var notificationStateData = notify.data;
// do something with notify data
}
});

Type parameters

NameType
Tany

Parameters

NameTypeDescription
topicstringA unique string representing the topic being subscribed to.
notifyCallback(err: StandardError, response: SubscriberResponse<T>) => voidInvoked on immediately upon subscription, then again on each incoming notification for the specified topic.

Returns

Object

An object containing a unique id representing the subscription. This can be used later to unsubscribe.

NameType
subscribeIDstring
topicstring

transmit

transmit<T>(toChannel, data, options?): void

Transmits data to all listeners on the specified channel. If there are no listeners on the channel, the event is discarded without error. All listeners on the channel in this Finsemble window and other Finsemble windows will receive the transmit.

See addListener to add a listener to receive the transmit.

FSBL.Clients.RouterClient.transmit("SomeChannelName", event);

Type parameters

NameType
Tany

Parameters

NameTypeDescription
toChannelstringA unique string to identify the channel (must match corresponding listener channel name).
dataTAn object or primitive type to be transmitted.
options?ObjectAn object containing options for your transmission.
options.suppressWarningsbooleanBy default, the Router will log warnings if you transmit to a channel with no listeners. Set this to true to eliminate those warnings.

Returns

void


trustedMessage

trustedMessage(incomingMessage): boolean

Tests an incoming Router message to see if it originated from the same origin (i.e., a trusted source; not cross-domain).

Currently, the origin of an incoming Router message is determined by way of the SharedWorker transport. By definition, SharedWorkers do not work across domains. This means any message coming in over the transport will not be trusted. However, by default, all same-origin components and services connect to the Router using a SharedWorker transport.

FSBL.Clients.RouterClient.trustedMessage(incomingRouterMessage);

Parameters

NameTypeDescription
incomingMessageRouterMessage<any>An incoming Router message (e.g., transmit, query, notification) to test to see if trusted.

Returns

boolean


unsubscribe

unsubscribe(subscribeIDStruct): void

Unsubscribes from a PubSub responder so no more notifications are received (but doesn't affect other subscriptions). Only works from the window the PubSub responder was created in.

See subscribe for corresponding subscription being removed.

FSBL.Clients.RouterClient.unsubscribe(subscribeId);

Parameters

NameTypeDescription
subscribeIDStructObject
subscribeIDStruct.subscribeIDstringThe id returned from the corresponding subscription to the topic.
subscribeIDStruct.topicstringThe topic for the subscription.

Returns

void