0.0.5 • Published 5 months ago

photoniq-eds-sdk v0.0.5

Weekly downloads
-
License
Apache-2.0
Repository
github
Last release
5 months ago

SDK for PhotonIQ EDS

PhotonIQ offers SDK to enable you connect to and deliver event streams to your applications, services, and several other data-volatile use cases. It supports both WebSocket and Server-Sent Events (SSE) connections.

Quick Start

This section demonstrates some simple tasks to help get you started using this client SDK in two ways.

This quickstart guide will guide you through:

  • Connecting to an event delivery service
  • Querying and subscribing that service and receiving query results and updates

Basic Example:

Connect to Event Delivery Service, retrieve and subsribe to SQL:

let config = {
    host: "<YOUR-PHOTONIQ>.photoniq.macrometa.io",
    customerId: "<YOUR-CUSTOMER-ID>",
    apiKey: "<YOUR-API-KEY>",
    fabric: "<YOUR-FABRIC>",
};

let connection = PhotoniqEdsSdk.connect(config);

let querySet = connection.querySet();

querySet.retrieveAndSubscribe("SELECT * FROM <YOUR-COLLECTION> WHERE key=<YOUR-KEY>", (event) => {
    console.log(`Message event: `, event);
})

NOTE

The example uses a WebSocket connection. To switch to an SSE connection, add connectionTypes: ["sse"] to the config. For a priority connection that falls back to WebSocket in case of network issues, use connectionTypes: ["sse", "ws"].


Supported Methods

Connect

Create a new Connection instance and establish connection to PhotonIQ EDS server:

let connection: Connection = PhotoniqEdsSdk.connect(config);

Create

Create a new Connection instance:

let connection = PhotoniqEdsSdk.create(config);

Config instance schema:

PropertyTypeRequredDescription
hoststringYesHost of the connection
customerIdstringYesCustomer ID credentails
apiKeystringYesApiKey credentails
fabricstringNoFabric to be used. Default is _system
urlParametersobjectNoCustom URL query parameters set as key value properties
connectionTypes(string|SubConfig)[]NoUse type of connection and priority. Default is ["ws"]. Types: ws, sse
autoReconnectbooleanNoAutomatically reconnect in case of network issues. Default is true

SubConfig instance schema:

PropertyTypeRequredDescription
typestringYesType of the connection. Value: ws or sse
customerIdstringNoCustomer ID credentails. Default set from Config
apiKeystringNoApiKey credentails. Default set from Config
fabricstringNoFabric to be used. Default set from Config
urlBasestringNoSet custom URL for connection.
urlParametersobjectNoCustom URL query parameters set as key:value properties
pingSecondsnumberNoSeconds between ping-pong messages to the WebSocket server. Default is 29. Acceptable only for ws connection.
flushTimeoutMsnumberNoSeconds between ping-pong messages to the WebSocket server. Default is 20. Acceptable only for sse connection.

Connection Instance

It maintains a WebSocket/SSE connection:

Supported methods

connect

Connects to the Event Delivery Service. This method can be used to reconnect after a disconnection, such as after using the disconnect method:

connection.connect();

getConfig

Retrieves the configuration of the connection. Returns a Config instance:

connection.getConfig();
ArgumentTypeDescription
returnConfigClient configuration of the connection

getId

Retrieves the connection ID:

connection.getId();
ArgumentTypeDescription
returnnumberID of the connection

getStatus

Checks status of the connection:

connection.getStatus();

The method can return the next ConnectionType enum values:

TypeDescription
ConnectionType.ClosedConnection closed
ConnectionType.ConnectingConnection is opening
ConnectionType.OpenConnection opened
ConnectionType.ClosingConnection is closing

getProperty

Get property of a connection:

connection.getProperty(name);
ArgumentTypeDescription
namestringName of a property
returnstringValue of a property

getProperties

Get all properties of a connection:

connection.getProperties();
ArgumentTypeDescription
returnobjectObject of all property:value pairs

querySet

Create a QuerySet instance:

connection.querySet();
ArgumentTypeDescription
returnQuerySetQuery set instance

disconnect

Disconnect from the Event Delivery Service:

connection.disconnect();
ArgumentTypeDescription
returnbooleantrue if disconnected; false if it was not connected

reconnect

Forcefully disconnects from the WebSocket/SSE connection to immediately connect to the next configuration if it exists:

connection.reconnect();
ArgumentTypeDescription
returnbooleantrue if disconnect triggered; false if it was not connected or autoReconnect is false

type

Type of connection:

connection.type();
ArgumentTypeDescription
returnstringPossible values: sse, ws

getQueries

Get a list of all listened queries for the connection:

connection.getQueries();
ArgumentTypeDescription
returnstring[]List of all listened queries for the connection

getQuerySets

Get a list of all QuerySet instances for the connection:

connection.getQuerySets();
ArgumentTypeDescription
returnQuerySet[]List of all QuerySet instances for the connection

Query Set And Batch

This abstract layer helps to manage a group of queries instead of working with each query independently. To initialize a new QuerySet instance, call the following method from the Connection instance:

let querySet = connection.querySet();

Supported methods

retrieve

Only retrieves initial data and immediately removes the query from the Event Delivery Service after the response:

querySet.retrieve("SELECT * FROM <YOUR-COLLECTION> WHERE key=<YOUR-KEY>", (event) => {
    console.log(`Message event: `, event);
})
ArgumentTypeRequredDescription
querystringYesSQL query to retrieve/listen
resultListenerfunctionYesSet result listener
errorListenerOrOptionsfunction|QueryOptionsNoSet error listener or set query options
optionsQueryOptionsNoSet query options.

retrieveAndSubscribe

Retrieves initial data and subscribes to changes in the query:

querySet.retrieveAndSubscribe("SELECT * FROM <YOUR-COLLECTION> WHERE key=<YOUR-KEY>", (event) => {
    console.log(`Message event: `, event);
})

Retrieves compressed initial data and subscribes to changes in the query:

querySet.retrieveAndSubscribe("SELECT * FROM <YOUR-COLLECTION> WHERE key=<YOUR-KEY>", (event) => {
    console.log(`Message event: `, event);
}, {
    compress: true
})
ArgumentTypeRequredDescription
querystringYesSQL query to retrieve/listen
resultListenerfunctionYesSet result listener
errorListenerOrOptionsfunction|QueryOptionsNoSet error listener or set query options
optionsQueryOptionsNoSet query options.

subscribe

Only subscribes to changes in the query:

querySet.subscribe("SELECT * FROM <YOUR-COLLECTION> WHERE key=<YOUR-KEY>", (event) => {
    console.log(`Message event: `, event);
})
ArgumentTypeRequredDescription
querystringYesSQL query to retrieve/listen
resultListenerfunctionYesSet result listener
errorListenerOrOptionsfunction|QueryOptionsNoSet error listener or set query options
optionsQueryOptionsNoSet query options.

unubscribe

Removes a subscription if the query was subscribed in the QuerySet. This applies only to the retrieveAndSubscribe and subscribe methods:

querySet.unsubscribe("SELECT * FROM <YOUR-COLLECTION> WHERE key=<YOUR-KEY>");

unubscribe

Removes a subscription if the query was subscribed in the QuerySet. This applies only to the retrieveAndSubscribe and subscribe methods:

querySet.unsubscribe("SELECT * FROM <YOUR-COLLECTION> WHERE key=<YOUR-KEY>");

unubscribeAll

Removes all subscriptions in the QuerySet:

querySet.unsubscribeAll();

getQueries

Get a list of all listened queries for the QuerySet:

querySet.getQueries();
ArgumentTypeDescription
returnstring[]List of all listened queries for the QuerySet

batch

To make requests to the Event Delivery Service more efficient, it is possible to join them into one WebSocket/SSE message. This returns a QueryBatch instance, which has the same methods (retrieve, retrieveAndSubscribe, subscribe, unsubscribe) as QuerySet. The final method should beassemble(), which builds and sends the message:

let queryBatch = querySet.batch();
queryBatch
    .retrieve("SELECT * FROM <YOUR-COLLECTION> WHERE key=<YOUR-KEY>", (event) => {
       console.log(`Message event: `, event);
    })
    .retrieveAndSubscribe("SELECT * FROM <YOUR-COLLECTION> WHERE key=<YOUR-KEY>", (event) => {
       console.log(`Message event: `, event);
    })
    .subscribe("SELECT * FROM <YOUR-COLLECTION> WHERE key=<YOUR-KEY>", (event) => {
       console.log(`Message event: `, event);
    })
    .unsubscribe("SELECT * FROM <YOUR-COLLECTION> WHERE key=<YOUR-KEY>")
    .assemble();

QueryOptions instance schema:

PropertyTypeRequredDescription
compressbooleanNocompress response data

Listeners and Error Handling

The Client has two types of event listeners: global and query.

Global Listener

The listener can be attached to the client when use connect method to Event Delivery Service

Example

let globalListener = function(event) {
    if (event.type === "open") {
        console.log('EDS connection established: ', event);
    } else if (event.type === "properties") {
        console.log("EDS assigned properties: ", event.data);
    } else if (event.type === "server-global-error") {
        console.log(`EDS replied with an Error: `, event);
    }else if (event.type === "server-query-error") {
        console.log(`EDS replied with an Error for query '${event.query}': `, event);
    } else if (event.type === "client-global-error") {
        console.log(`Client global error: `, event);
    } else if (event.type === "client-query-error") {
        console.log(`Client error for query '${event.query}': `, event);
    } else if (event.type === "message") {
        console.log('Message event: ', event);
    } else if (event.type === "close") {
        console.log('EDS connection closed: ', event);
    }
};

let connection = PhotoniqEdsSdk.connect({
host: "<YOUR-PHOTONIQ>.photoniq.macrometa.io",
customerId: "<YOUR-CUSTOMER-ID>",
apiKey: "<YOUR-API-KEY>",
fabric: "<YOUR-FABRIC>",
}, globalListener);

EDSEvent Schema

The globalListener function returns EDSEvent instance which has the next schema:

PropertyTypeRequredDescription
typeEDSEventTypeYesList of event types generated by EDS driver
connectionConnectionYesAn instance used for the WebSocket/SSE connection
dataanyNoPresent for events with data like message, cnnection-id types
codenumberNoError code, only present for server side errors
messagestringNoError message, only present in error's event
querystringNoError for a query, only present for query's errors

EDSEventType Schema

The type property can have the next EDSEventType enum values:

TypeDescription
openOpenned WebSocket/SSE connection
propertiesReceived properties of connection
server-query-errorServer-side error related to a query
server-global-errorServer-side error not related to a query
client-query-errorClient-side error related to a query
client-global-errorClient-side error not related to a query
messageMessage event
closeClosed WebSocket/SSE connection

Query Listeners

The functions listen to events related to a specific query and are divided into result and error listeners.

Result Listener

It listens only for events with event.type === "message" and is passed as the second parameter to the retrieve, retrieveAndSubscribe, and subscribe methods:

let sql = "SELECT * FROM <YOUR-COLLECTION> WHERE key=<YOUR-KEY>";
let resultListener = (event) => {
    console.log(`Message event: `, event);
};
querySet.retrieve(sql, resultListener);

Error Listener

The error listener handles error messages related to a query, which can have the types event.type === "server-query-error" or event.type === "client-query-error"

let sql = "SELECT * FROM <YOUR-COLLECTION> WHERE key=<YOUR-KEY>";
let resultListener = (event) => {
    console.log(`Message event: `, event);
};
let errorListener = (event) => {
    console.log(`Error event: `, event);
};
querySet.retrieve(sql, resultListener, errorListener);
0.0.5

5 months ago

0.0.4

10 months ago

0.0.3

10 months ago

0.0.2

10 months ago

0.0.1

10 months ago

0.1.0

11 months ago