UNPKG

diffusion

Version:

Diffusion JavaScript client

412 lines (303 loc) 19.9 kB
## Diffusion JavaScript API The Diffusion JavaScript API allows interaction with a Diffusion server from both the browser and Node.js. Clients use a WebSocket or HTTP connection to send and receive data, as well as perform other functions such as adding, removing or updating topics. For a full list of capabilities in the JavaScript API, see the [Contents](https://download.pushtechnology.com/docs/6.11.6/js/index.html#section-contents) section below. ### Installing Install the client using ```npm install diffusion --save``` Pre-bundled browser artifacts are included in ```node_modules/diffusion/dist``` To import Diffusion use either `require` or ES6 style syntax **require** ```javascript var diffusion = require('diffusion'); ``` **ES6** ```javascript import * as diffusion from 'diffusion'; ``` ### Browser Bundles Browser bundles can be found in the `dist` folder located in the package root. * When installing via `npm`, the bundles are located in `node_modules/diffusion/dist/`. * In the on-premise installation of Diffusion, they can be found in the `clients/js/` folder. * When unpacking the `diffusion-js-x.y.z.tgz`, they are extracted to the `package/dist/` folder. * They can also be downloaded directly from the [Diffusion release pages](https://www.pushtechnology.com/developers/release/latest#js-sdk) The bundles are organized into the following files: `diffusion.js`: The complete diffusion client including all features. It exposes the `diffusion` object as a global variable. `diffusion-worker.js`: A script that can be loaded into a shared worker. The location of this script can be passed to [diffusion.connectShared()](https://download.pushtechnology.com/docs/6.11.6/js/globals.html#connectshared) to create sessions that are shared across browser tabs. `modular/diffusion-core.js`: The core bundle of the modular client. Just like the `diffusion.js` package, this exposes the `diffusion` object in the global context. Sessions created from this package will lack any features except [value streams and topic subscription](https://download.pushtechnology.com/docs/6.11.6/js/interfaces/topics.html). Attempting to access a feature that hasn't yet been loaded into the browser will result in an Error being thrown. Additional features can be loaded dynamically **after** a session has been created. Features will be available to all sessions once the respective feature bundle has been loaded into the browser. `modular/diffusion-feature-XYZ.js`: The bundle for the feature XYZ. These bundles can be loaded into the browser dynamically after the core bundle of the modular client. Each bundle will provide an additional feature to the client. The following bundles are available. * `diffusion-feature-client-control.js`: [Client Control Feature](https://download.pushtechnology.com/docs/6.11.6/js/interfaces/clientcontrol.html) * `diffusion-feature-messages.js`: [Request Response Messaging Feature](https://download.pushtechnology.com/docs/6.11.6/js/interfaces/messages.html) * `diffusion-feature-remote-servers.js`: [Remote Servers Feature](https://download.pushtechnology.com/docs/6.11.6/js/interfaces/remoteservers.html) * `diffusion-feature-security.js`: [Security Feature](https://download.pushtechnology.com/docs/6.11.6/js/interfaces/security.html) * `diffusion-feature-session-lock.js`: [Session Locks Feature](https://download.pushtechnology.com/docs/6.11.6/js/interfaces/sessionlock.html) * `diffusion-feature-time-series.js`: [Time Series Feature](https://download.pushtechnology.com/docs/6.11.6/js/interfaces/timeseries.html) * `diffusion-feature-topic-control.js`: [Topic Control Feature](https://download.pushtechnology.com/docs/6.11.6/js/interfaces/topiccontrol.html) * `diffusion-feature-topic-notifications.js`: [Topic Notifications Feature](https://download.pushtechnology.com/docs/6.11.6/js/interfaces/topicnotifications.html) * `diffusion-feature-topic-update.js`: [Topic Update Feature](https://download.pushtechnology.com/docs/6.11.6/js/interfaces/topicupdate.html) * `diffusion-feature-topic-views.js`: [Topic Views Feature](https://download.pushtechnology.com/docs/6.11.6/js/interfaces/topicviews.html) A feature can be loaded into the browser by dynamically creating a `<script>` element and setting the `src` attribute. ```javascript // create a new script element const script = document.createElement('script'); // set the src attribute to the path of the module bundle script.src = 'path_to_library/diffusion-feature-topic-update.js'; script.onload = function () { // the Topic Update feature is now available on all future and existing // sessions }; // add the script to the document to ensure loading document.head.appendChild(script); ``` ### TypeScript The Diffusion package includes TypeScript bindings, specified in ```node_modules/diffusion/typescript``` ### The diffusion object The documentation will frequently refer to the `diffusion` object. Technically, this is the module object that is obtained when importing the Diffusion library using one of the methods described above. The diffusion object exposes a number of global constants and functions. When using one of the pre-bundled packages in the browser, the `diffusion` object will be attached to the global `windows` object. #### Constants [`version: string;`](https://download.pushtechnology.com/docs/6.11.6/js/globals.html#version)<br> The version of this client library in the form major.minor.patch [`build: string`](https://download.pushtechnology.com/docs/6.11.6/js/globals.html#build)<br> The build version of this client library #### Functions [`function log(level: LogLevel | keyof typeof LogLevel)`](https://download.pushtechnology.com/docs/6.11.6/js/globals.html#log)<br> Set the level of logging used by Diffusion. [`function connect(options: Options): Result<Session>`](https://download.pushtechnology.com/docs/6.11.6/js/globals.html#connect)<br> Connect to a specified Diffusion server. [`function escape(s: string)`](https://download.pushtechnology.com/docs/6.11.6/js/globals.html#escape)<br> Escapes special characters in a string that is to be used within a topic property or a session filter. [`function stringToRoles(s: string)`](https://download.pushtechnology.com/docs/6.11.6/js/globals.html#stringtoroles)<br> Utility method which converts a string of the format required by the [$Roles](https://download.pushtechnology.com/docs/6.11.6/js/interfaces/propertykeys.html#roles) session property into a mutable set of strings. [`rolesToString(roles: Set<string> | string[])`](https://download.pushtechnology.com/docs/6.11.6/js/globals.html#rolestostring)<br> Utility method which converts a set of authorization roles to the string format required by the [$Roles](https://download.pushtechnology.com/docs/6.11.6/js/interfaces/propertykeys.html#roles) session property. [`function updateConstraints(): UpdateConstraintFactory`](https://download.pushtechnology.com/docs/6.11.6/js/globals.html#updateconstraints)<br> Returns an update constraint factory. #### Namespaces [`const datatypes`](https://download.pushtechnology.com/docs/6.11.6/js/interfaces/datatypes.html)<br> Access to the *datatypes* namespace [`const locks`](https://download.pushtechnology.com/docs/6.11.6/js/globals.html#sessionlockoptions)<br> Access to the *locks* namespace [`const selectors `](https://download.pushtechnology.com/docs/6.11.6/js/classes/topicselectors.html)<br> Access to the *selectors* namespace [`const topics`](https://download.pushtechnology.com/docs/6.11.6/js/interfaces/topicsnamespace.html)<br> Access to the *topics* namespace [`const topicUpdate`](https://download.pushtechnology.com/docs/6.11.6/js/globals.html#topicupdatenamespace)<br> Access to the *topicUpdate* namespace [`const errors`](https://download.pushtechnology.com/docs/6.11.6/js/globals.html#errorreason)<br> The [ErrorReason](https://download.pushtechnology.com/docs/6.11.6/js/globals.html#errorreason) enum [`const clients`](https://download.pushtechnology.com/docs/6.11.6/js/globals.html#clientcontroloptions)<br> Access to [PropertyKeys](https://download.pushtechnology.com/docs/6.11.6/js/globals.html#clientcontroloptions.propertykeys) and other client control options ### Quick start A client [Session](https://download.pushtechnology.com/docs/6.11.6/js/interfaces/session.html) maintains a connection to the server. To create a session, simply do ```javascript diffusion.connect('diffusion.example.com'); ``` It is also possible to [connect](https://download.pushtechnology.com/docs/6.11.6/js/globals.html#connect) with a map of [options](https://download.pushtechnology.com/docs/6.11.6/js/interfaces/options.html) ```javascript diffusion.connect({ host : 'diffusion.example.com', port : 8080, secure : false, principal : 'admin', credentials : 'password' }); ``` Connecting returns a [Promise](https://promisesaplus.com/) - this will succeed if the session could be connected, or fail if not. ```javascript diffusion.connect('diffusion.example.com').then(function(session) { // Connected! }, function(error) { // Failed to connect :( }); ``` Sessions emit events to indicate their status such as when they are [disconnected](https://download.pushtechnology.com/docs/6.11.6/js/interfaces/session.html#event-disconnect) or [closed](https://download.pushtechnology.com/docs/6.11.6/js/interfaces/session.html#event-close). These events are easy to listen to: ```javascript session.on('disconnect', function(reason) { // Lost connection to the server! }); session.on('close', function() { // Session is closed! }); ``` Once a session is closed, it can never be re-opened. #### Subscriptions Data in Diffusion is distributed via *topics*. A topic has state, which can be updated. The state can be simple - such as a string or an integer - or more complex - such as a JSON document. Each topic has a unique path and is addressed through a [topic selector](https://download.pushtechnology.com/docs/6.11.6/js/interfaces/topicselector.html). The way that a session receives data is by [subscribing](https://download.pushtechnology.com/docs/6.11.6/js/interfaces/session.html#select). Subscriptions allow the session to select one or more topics to receive values from. A session may subscribe to many topics, as well as subscribe to the same topic multiple times. ```javascript session.select('topic/foo') ``` To attach listeners for received values, a [ValueStream](https://download.pushtechnology.com/docs/6.11.6/js/interfaces/valuestream.html) is used. The stream that is returned will emit [value](https://download.pushtechnology.com/docs/6.11.6/js/interfaces/valuestream.html#event-value) events when the value of the selected topic changes. ```javascript session.addStream('topic/foo', diffusion.datatypes.json()).on('value', function(topic, specification, newValue, oldValue) { // Do something with the value var value = newValue.get(); }); ``` It is possible to register any number of streams to a subscription's events. They will each be called when a new value is received. ### <a name="section-contents"></a> Contents The JavaScript client provides namespaces, classes, and methods that support the following capabilities: #### Basics * Connect the JavaScript client to Diffusion or Diffusion Cloud by using the [diffusion.connect](https://download.pushtechnology.com/docs/6.11.6/js/globals.html#connect) method. * To change the security principal that the client is connected with, use the [changePrincipal](https://download.pushtechnology.com/docs/6.11.6/js/interfaces/security.html#changeprincipal) method. * The client can log out information by using the [diffusion.log](https://download.pushtechnology.com/docs/6.11.6/js/globals.html#log) method. * The client can check its connectivity and roundtrip time to the server by using the [pingServer](https://download.pushtechnology.com/docs/6.11.6/js/interfaces/session.html#pingserver) method. #### Receive data from topics * Subscribe to topics. Use the [session.select](https://download.pushtechnology.com/docs/6.11.6/js/interfaces/session.html#select) method to subscribe to a topic. The updates to a topic can be interacted with by registering a [ValueStream](https://download.pushtechnology.com/docs/6.11.6/js/interfaces/valuestream.html) and a provided datatype to start receiving the values of that datatype. * Fetch data from topics. Use the [fetch](https://download.pushtechnology.com/docs/6.11.6/js/interfaces/session.html#fetch) method to make a fetch request and get a [FetchResult](https://download.pushtechnology.com/docs/6.11.6/js/interfaces/fetchresult.html) object that you can use to receive fetched values. #### Create and manage topics Creating and managing topics is handled through the [topics](https://download.pushtechnology.com/docs/6.11.6/js/interfaces/topiccontrol.html) feature. * Add a topic. Use the [add](https://download.pushtechnology.com/docs/6.11.6/js/interfaces/topiccontrol.html#add) method to add a topic. You can create a topic by explicitly defining the topic type, or by providing a [TopicSpecification](https://download.pushtechnology.com/docs/6.11.6/js/classes/topicspecification.html) with optional properties. * Handle missing topics. Use the [addMissingTopicHandler](https://download.pushtechnology.com/docs/6.11.6/js/interfaces/topiccontrol.html#addmissingtopichandler) method to register a [MissingTopicHandler](https://download.pushtechnology.com/docs/6.11.6/js/interfaces/missingtopichandler.html). This handler receives a [MissingTopicNotification](https://download.pushtechnology.com/docs/6.11.6/js/interfaces/missingtopicnotification.html) when a client session subscribes to a topic that does not currently exist. The notified client can then choose to create that topic if appropriate. * Remove topics. Use the [remove](https://download.pushtechnology.com/docs/6.11.6/js/interfaces/topiccontrol.html#remove) method to remove topics. You can also mark topics to be removed automatically with the TopicSpecification property [REMOVAL](https://download.pushtechnology.com/docs/6.11.6/js/classes/topicspecification.html#removal). #### Update topics Updating topics is handled through the [topicUpdate](https://download.pushtechnology.com/docs/6.11.6/js/interfaces/topicupdate.html) feature. * Update a topic using the [set](https://download.pushtechnology.com/docs/6.11.6/js/interfaces/topicupdate.html#set) method. * Create an update stream for creating and updating a specific topic using the [createUpdateStream](https://download.pushtechnology.com/docs/6.11.6/js/interfaces/topicupdate.html#createupdatestream) * Update topics by using the classes in the [diffusion.datatypes](https://download.pushtechnology.com/docs/6.11.6/js/interfaces/datatypes.html) namespace to create update values. #### Manage other clients Updating topics is handled through the [clients](https://download.pushtechnology.com/docs/6.11.6/js/interfaces/clientcontrol.html) feature. * Subscribe other client sessions to topics. Use the [subscribe](https://download.pushtechnology.com/docs/6.11.6/js/interfaces/clientcontrol.html#subscribe) and [unsubscribe](https://download.pushtechnology.com/docs/6.11.6/js/interfaces/clientcontrol.html#unsubscribe) methods to manage another client session's subscriptions. * Receive notifications about other sessions and their properties. Use the [setSessionPropertiesListener](https://download.pushtechnology.com/docs/6.11.6/js/interfaces/clientcontrol.html#setsessionpropertieslistener) method to register a [SessionPropertiesListener](https://download.pushtechnology.com/docs/6.11.6/js/interfaces/sessionpropertieslistener.html) to receive notifications for session events or when a session changes properties. * Query the session properties of a specific session. Use the [getSessionProperties](https://download.pushtechnology.com/docs/6.11.6/js/interfaces/clientcontrol.html#getsessionproperties) method. Specify which sets of properties to receive using [PropertyKeys](https://download.pushtechnology.com/docs/6.11.6/js/interfaces/propertykeys.html). #### Send messages Sending and receiving messages is handled through the [messages](https://download.pushtechnology.com/docs/6.11.6/js/interfaces/messages.html) feature. * Send a message. Use the [send](https://download.pushtechnology.com/docs/6.11.6/js/interfaces/messages.html#sendrequest) method to either send a message to a specific client session or send a message to a path. * Receive messages sent to this client session. Use the [setRequestStream](https://download.pushtechnology.com/docs/6.11.6/js/interfaces/messages.html#setrequeststream) method to receive messages sent to this client session through a [RequestStream](https://download.pushtechnology.com/docs/6.11.6/js/interfaces/requeststream.html). * Receive messages sent to a path. Use the [addRequestHandler](https://download.pushtechnology.com/docs/6.11.6/js/interfaces/messages.html#addrequesthandler) method to register a [RequestHandler](https://download.pushtechnology.com/docs/6.11.6/js/interfaces/requesthandler.html) that receives messages sent to a path. #### Authenticating clients Authenticating clients and modifying the authentication store is handled through the [security](https://download.pushtechnology.com/docs/6.11.6/js/interfaces/security.html) feature. * Register an authentication handler to authenticate other client sessions. Implement an [Authenticator](https://download.pushtechnology.com/docs/6.11.6/js/interfaces/authenticator.html) and use the [setAuthenticator](https://download.pushtechnology.com/docs/6.11.6/js/interfaces/security.html#setauthenticator) method to register it with the server. The server also uses information stored in the system authentication store to authenticate connecting clients. * Get the system authentication store information with the [getSystemAuthenticationConfiguration](https://download.pushtechnology.com/docs/6.11.6/js/interfaces/security.html#getsystemauthenticationconfiguration) method. * Update the system authentication store. Use the [authenticationScriptBuilder](https://download.pushtechnology.com/docs/6.11.6/js/interfaces/security.html#authenticationscriptbuilder) method to get a [SystemAuthenticationScriptBuilder](https://download.pushtechnology.com/docs/6.11.6/js/interfaces/systemauthenticationscriptbuilder.html). The builder can be used to create a script. Pass the script to the [updateAuthenticationStore](https://download.pushtechnology.com/docs/6.11.6/js/interfaces/security.html#updateauthenticationstore) method to update the system authentication store. #### Updating security roles The [security](https://download.pushtechnology.com/docs/6.11.6/js/interfaces/security.html) feature also allows querying and updating a session's security roles. * Get the security store information [getSecurityConfiguration](https://download.pushtechnology.com/docs/6.11.6/js/interfaces/security.html#getsecurityconfiguration) method. * Update the security store. Use the [securityScriptBuilder](https://download.pushtechnology.com/docs/6.11.6/js/interfaces/security.html#securityscriptbuilder) method to get a [SecurityScriptBuilder](https://download.pushtechnology.com/docs/6.11.6/js/interfaces/securityscriptbuilder.html). The builder can be used to create a script. Pass the script to the [updateSecurityStore](https://download.pushtechnology.com/docs/6.11.6/js/interfaces/security.html#updatesecuritystore) method to update the system authentication store.