Class openiap

OpenIAP

Hierarchy

  • EventEmitter
    • openiap

Constructors

  • Create a client for connecting to an OpenIAP flow instace. By default it loads the apiurl from environment variable apiurl, grpcapiurl or wscapiurl You can supply username and password in the URL ( remember this needs to e URL encoded ) or you can supply a JWT token in the jwt environment variable or as the second parameter to the constructor.

    You can connect using one of these protocols

    • Using google RPC by using grpc:// as protocol. This require you also supply a port number. Example: grpc://host.name:port For docker or kubernetes deployments this is usually the main domain prefixed with grpc. for instance if your main domain is app.openiap.io then the grpc url would be grpc://grpc.app.openiap.io:443 For developer installations, the grpc url would be grpc://localhost:50051
    • Using WebSocket by using ws:// or wss:// as protocol. wss when using certificates. ws when unsecured For example wss://app.openiap.io or ws://localhost.openiap.io
    • Using named pipes by using pipe:// as protocol. For example pipe://localhost/testpipe
    • Using TCP sockets by using tcp:// as protocol. For example tcp://localhost.openiap.io:8080
    • Using HTTP/REST by using http:// or https:// as protocol. https when using certificates. http when unsecured For example https://app.openiap.io/api/v2 or http://localhost.openiap.io/api/v2

    Example

    Connect to OpenIAP flow instance

    const { openiap } = require("@openiap/nodeapi");
    client.connect().then(async client=> {
    console.log("Connected")
    const result = await client.Query({ query: { "_type": "test" } });
    console.log(result);
    client.Close();
    }).catch(err => {
    console.log("Failed to connect: " + err)
    }

    Example

    Connect to OpenIAP using a connection string.

    const { openiap } = require("@openiap/nodeapi");
    async function main() {
    const client = new openiap("grpc://grpc.app.openiap.io:443");
    await client.connect();
    const user = client.Signin({username: "henrik", password: "SuperSecret"});
    }
    main();

    Example

    Alternatively we can supply credentials in the connection string, then we do not need to call Signin

    const { openiap } = require("@openiap/nodeapi");
    async function main() {
    const client = new openiap("grpc://henrik:SuperSecret@grpc.app.openiap.io:443");
    await client.connect();
    }
    main();

    Parameters

    • url: string = ""

      By default we read from environment variable apiurl, grpcapiurl or wscapiurl but can be overriden here

    • jwt: string = ""

      By default we read from environment variable jwt but can be overriden here

    Returns openiap

Properties

agent: clientAgent = "node"

Define client type when authenticating toward the server

allowconnectgiveup: boolean = true

If false, the client will never give up trying to connect to the server, if true, will give up after 17 seconds

client: client

The internal client object

connected: boolean = false

Define if connected to server

connecting: boolean = false

Define if we are trying to (re)connect

defaltqueue: string = ""
flowconfig: any = {}
jwt: string = ""

The JWT used when authenticating to the server

loginreject: any
loginresolve: any
pingerhandle: any
queuecallbacks: any = {}
queues: any = {}
reconnectms: number = 100
signedin: boolean = false

If connected, are we also signed in or is server waiting on use to authenticate

url: string = ""

The URL used when connecting to the server

version: string = "0.0.14"

Define the version of the client sent to the server

watchids: any = {}
captureRejectionSymbol: typeof captureRejectionSymbol
captureRejections: boolean

Sets or gets the default captureRejection value for all emitters.

defaultMaxListeners: number
errorMonitor: typeof errorMonitor

This symbol shall be used to install a listener for only monitoring 'error' events. Listeners installed using this symbol are called before the regular 'error' listeners are called.

Installing a listener using this symbol does not change the behavior once an 'error' event is emitted, therefore the process will still crash if no regular 'error' listener is installed.

Methods

  • Create a new workitem queue. Workitem queues are registered in the wiq collection.

    Parameters

    • options: AddWorkItemQueueOptions

      AddWorkItemQueueOptions

    • priority: number = 2

      Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration

    • span: Span = null

    Returns Promise<WorkItemQueue>

  • Run an mongodb aggregation pipeline toward the OpenIAP flow database. See https://docs.mongodb.com/manual/aggregation/ for more information

    Returns

    An array of documents matching the aggregation pipeline

    See

    https://docs.mongodb.com/manual/aggregation/

    Example

    Get the count of all documents with type "test" from entities collection

    const result = await client.Aggregate({ collectionname: "entities", aggregates: [{ "$match": { "_type": "test" } }, { "$count": "count" }] });
    

    Type Parameters

    • T

    Parameters

    • options: AggregateOptions
    • priority: number = 2

      Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration

    • span: Span = null

    Returns Promise<T[]>

  • Close connection to server. Use this to ensure the client will not reconnect to the server

    Returns void

  • Getting the count of documents in a collection can be done using this function. Leave query empty to get the total count of documents in the collection.

    Returns

    The number of documents matching the query

    Example

    Get the count of documents with type "test" from entities collection

    const result = await client.Count({ collectionname: "entities", query: { "_type": "test" } });
    

    Example

    Get the total number of documents in the entities collection

    const result = await client.Count({ collectionname: "entities" });
    

    Parameters

    • options: CountOptions
    • priority: number = 2

      Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration

    • span: Span = null

    Returns Promise<number>

  • Create a collection removing all data from the collection. Only users with admin rights can Create collections.

    Parameters

    • options: CreateCollectionOptions

      CreateCollectionOptions

    • priority: number = 2

      Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration

    • span: Span = null

    Returns Promise<void>

  • Return the console output of an running agent, can be in docker, kubernetes or running remote. Requires invoke permission on agent

    Returns

    Returns the index name

    Parameters

    • options: CreateIndexOptions

      CreateIndexOptions

    • priority: number = 2

      Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration

    • span: Span = null

    Returns Promise<string>

  • Old command used by nodered "Workflow in" and "assign" nodes for creating a new workflow instance.

    Returns

    Parameters

    • options: CreateWorkflowInstanceOptions
    • priority: number = 2

      Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration

    • span: Span = null

    Returns Promise<string>

  • Run custom commands not defined in the protocol yet. This is how new functioanlly is added and tested, before it is finally added to the offical proto3 protocol.

    Returns

    If command has a result, this will be returned as a string. This will most likely need to be parser as JSON

    Type Parameters

    • T

    Parameters

    • options: CustomCommandOptions
    • priority: number = 2

      Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration

    • span: Span = null

    Returns Promise<string>

  • Remove an agent if running. Docker and Kubernetes only. Removes instance on docker, remove deployment, ingress and other resources on Kubernetes Requires delete permission on agent

    Returns

    void

    Parameters

    • options: DeleteAgentOptions

      DeleteAgentOptions

    • priority: number = 2

      Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration

    • span: Span = null

    Returns Promise<void>

  • Remove an agent pod, found with GetAgentPods. Docker and Kubernetes only. Requires invoke permission on agent

    Returns

    void

    Parameters

    • options: DeleteAgentPodOptions

      DeleteAgentPodOptions

    • priority: number = 2

      Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration

    • span: Span = null

    Returns Promise<void>

  • Delete many documents from a collection based on a query. Will return 0 if no documents are deleted.

    Returns

    The number of deleted documents

    Example

    Delete all documents with name "find me" in entities collection

    const result = await client.DeleteMany({ query: { name: "find me" } });
    console.log("Deleted " + result + " documents");

    Delete all documents with type "invoice" in entities collection

    const result = await client.DeleteMany({ query: { _type: "invoice" } });
    console.log("Deleted " + result + " documents");

    Parameters

    • options: DeleteManyOptions
    • priority: number = 2

      Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration

    • span: Span = null

    Returns Promise<number>

  • Delete one document from a collection. Will throw an error if document does not exist or you don't have the right permissions. if recursive is set to true, all asssoicated documents will be deleted as well. Currently only user and customer objects in the "users" collection are supported for recursive deletion.

    Returns

    Number of deleted documents (will always be 1)

    Example

    Delete a document with id "643917fb153b7c2c1466fb21" in entities collection

    const result = await client.DeleteOne({ id: "643917fb153b7c2c1466fb21" } });
    console.log("Deleted " + result + " documents");

    Parameters

    • options: DeleteOneOptions
    • priority: number = 2

      Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration

    • span: Span = null

    Returns Promise<number>

  • Delete an agent Package. Removes the associated file and then delete te package from the agents collection. Requires delete permission on the Package

    Returns

    void

    Parameters

    • options: DeletePackageOptions

      DeletePackageOptions

    • priority: number = 2

      Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration

    • span: Span = null

    Returns Promise<void>

  • Delete a workitem queue. Workitem queues are registered in the wiq collection. If queue has workitems in it, the request will fail, unless purge is set to true.

    Parameters

    • options: DeleteWorkItemQueueOptions

      DeleteWorkItemQueueOptions

    • priority: number = 2

      Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration

    • span: Span = null

    Returns Promise<void>

  • Delete one workitem and all associated files from a workitem queue.

    Example

    Delete a workitem

    client.DeleteWorkitem({ id: "64366f12cffb7419a89d5e10" });
    

    Parameters

    • options: DeleteWorkitemOptions
    • priority: number = 2

      Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration

    • span: Span = null

    Returns Promise<void>

  • Finds the distinct values for a specified field across a single collection

    Returns

    returns the results in an array

    Example

    Get the distinct name of all documents with type "test"

    const result = await client.Distinct({ collectionname: "entities", field: "name", query: { "_type": "test" } });
    

    Example

    Get the distinct types in the entities collection

    const result = await client.Distinct({ collectionname: "entities", field: "_type" });
    

    Parameters

    • options: DistinctOptions

      DistinctOptions

    • priority: number = 2

      Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration

    • span: Span = null

    Returns Promise<string[]>

  • Drop a collection removing all data from the collection. Only users with admin rights can drop collections.

    Parameters

    • options: DropCollectionOptions
    • priority: number = 2

      Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration

    • span: Span = null

    Returns Promise<void>

  • Drop a MongoDB index from a collection. Requires admins permission

    Returns

    void

    Parameters

    • options: DropIndexOptions

      DropIndexOptions

    • priority: number = 2

      Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration

    • span: Span = null

    Returns Promise<void>

  • Create a collection removing all data from the collection. Only users with admin rights can Create collections.

    Parameters

    • options: EnsureCustomerOptions

      EnsureCustomerOptions

    • priority: number = 2

      Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration

    • span: Span = null

    Returns Promise<EnsureCustomerResponse>

  • Query a collection for data and return the first document

    Returns

    a document matching the query

    Example

    Get the first document with type "test" from entities collection

    const result = await client.FindOne({ query: { "_type": "test" } });
    

    Example

    Get the first document with type "test" from entities collection and only return the name field

    const result = await client.FindOne({ collectionname: "entities", query: { "_type": "test" }, projection: { "name": 1 } });
    

    Example

    Get the first document with type "test" from entities collection and only return the name field and order by name

    const result = await client.FindOne({ collectionname: "entities", query: { "_type": "test" }, projection: { "name": 1 }, orderby: { "name": 1 } });
    

    Type Parameters

    • T

    Parameters

    • options: FindOneOptions
    • priority: number = 2

      Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration

    • span: Span = null

    Returns Promise<T>

  • Return the console output of an running agent, can be in docker, kubernetes or running remote. Requires invoke permission on agent

    Returns

    Return pods console output

    Parameters

    • options: GetAgentLogOptions

      GetAgentLogOptions

    • priority: number = 2

      Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration

    • span: Span = null

    Returns Promise<string>

  • Return a list of pods for an running agent. Docker and Kubernetes only. Requires invoke permission on agent

    Returns

    Array of pods

    Parameters

    • options: GetAgentPodsOptions

      GetAgentPodsOptions

    • priority: number = 2

      Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration

    • span: Span = null

    Returns Promise<any[]>

  • By default OpenIAP will keep history information about all data in the database. This function will try and reconstruct the document at it was at a given version. This can be used to restore data to a previous state or even restore deleted data.

    Returns

    The reconstructed document

    Example

    Get the document with id "643917fb153b7c2c1466fb21" from entities collection at version 1

    const result = await client.GetDocumentVersion({ id: "643917fb153b7c2c1466fb21", version: 1 });
    

    Type Parameters

    • T

    Parameters

    Returns Promise<T[]>

  • Dummy function used to test the connection to the server.

    Returns

    xpath with added text

    Parameters

    • xpath: string

    Returns Promise<string>

  • Parameters

    • options: GetIndexesOptions
    • priority: number = 2
    • span: Span = null

    Returns Promise<any[]>

  • Bulk insert multiple documents into a collection, this is faster than using InsertOne multiple times.

    Returns

    When skipresults is false, will return an array of the documents that was created, including the _id field

    Example

    Insert multiple documents with type "test" into entities collection

    const result = await client.InsertMany({ collectionname: "entities", items: [{ "_type": "test", name: "find me" }, { "_type": "test", name: "find me too" }] });
    

    Type Parameters

    • T

    Parameters

    • options: InsertManyOptions
    • priority: number = 2

      Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration

    • span: Span = null

    Returns Promise<T[]>

  • Insert a document into a collection

    Returns

    The object that was created, including the _id field

    Example

    Insert a document with type "test" into entities collection

    const result = await client.InsertOne({ collectionname: "entities", item: { "_type": "test", name: "find me" } });
    

    Type Parameters

    • T

    Parameters

    • options: InsertOneOptions
    • priority: number = 2

      Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration

    • span: Span = null

    Returns Promise<T>

  • Will match all documents toward a collection using the uniqeness parameters ( _id if left out ) and update it if it exists, or insert it if it does not exist. Will trhow an error if more than one document exists that matches the uniqeness parameters. This will use bulk operations to speed up the process.

    Returns

    The updated or inserted documents including the _id field

    Example

    Insert or update multiple invoice documents in entities collection

    const invoices = [{ "_type": "invoice", invoiceid: "1234", name: "find me" }, { "_type": "invoice", invoiceid: "1235", name: "find me too" }]
    const result = await client.InsertOrUpdateMany({ items: invoices, uniqeness: ["invoiceid"] });
    console.log("Inserted document with id: " + result[0]._id + " and name: " + result[0].name);
    console.log("Inserted document with id: " + result[1]._id + " and name: " + result[1].name);

    const same_invoice = [{ "_type": "invoice", invoiceid: "1234", name: "Can you still find me?"}, { "_type": "invoice", invoiceid: "1235", name: "Can you still find me too?"}]
    const updated = await client.InsertOrUpdateMany({ items: same_invoice, uniqeness: ["invoiceid"] });
    console.log("Updated document with id: " + updated[0]._id + " and new name: " + updated[0].name);
    console.log("Updated document with id: " + updated[1]._id + " and new name: " + updated[1].name);

    Type Parameters

    • T

    Parameters

    Returns Promise<T[]>

  • Will match a document in a collection on the uniqeness parameters ( _id if left out ) and update it if it exists, or insert it if it does not exist. Will trhow an error if more than one document exists that matches the uniqeness parameters.

    Returns

    The updated or inserted document including the _id field

    Example

    Insert or update a document with invoiceid "1234" in entities collection

    const result = await client.InsertOrUpdateOne({ item: { "_type": "invoice", invoiceid: "1234", name: "find me" }, uniqeness: ["invoiceid"] });
    console.log("Inserted document with id: " + result._id + " and name: " + result.name);

    const same_invoice = { "_type": "invoice", invoiceid: "1234", name: "Can you still find me?"}
    const updated = await client.InsertOrUpdateOne({ item: same_invoice, uniqeness: ["invoiceid"] });
    console.log("Updated document with id: " + updated._id + " and new name: " + updated.name);

    Type Parameters

    • T

    Parameters

    Returns Promise<T>

  • Invoke an OpenRPA workflow on a robot or a role with multiple robots in. At writing, this command is only supprted using OpenAPI endpoint

    Returns

    null if rpc is false, else the result of the workflow if workflow has any inout/out parameters

    Type Parameters

    • T

    Parameters

    • options: InvokeOpenRPAOptions

      InvokeOpenRPAOptions

    • priority: number = 2

      Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration

    • span: Span = null

    Returns Promise<T>

  • Returns a list of all known collections. By default filtering out history collectins.

    Returns

    Parameters

    • options: ListCollectionsOptions = {}
    • priority: number = 2

      Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration

    • span: Span = null

    Returns Promise<any[]>

  • Used internally to send a ping message to server, to keep the connection alive. Only used if server require pings, or if the client is configured to send pings using DoPing

    Returns Promise<void>

  • Pop an item of a workitem queue. An items aviailable in the queue will be determined by it's status, retry time and runat time steamp. If multiple items are available, the items will be fatched based on each wrkitem's priority field.

    Returns

    If no workitem is available, this will return null.

    Parameters

    • options: PopWorkitemOptions
    • priority: number = 2

      Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration

    • span: Span = null

    Returns Promise<Workitem>

  • Push a workitem to a workqueue. Workitem can be processed by a worker after calling PopWorkitem

    Returns

    Returns the workitem that was pushed, including the workitem id

    See

    Example

    Push a workitem to myworkqueue

    const workitem = await client.PushWorkitem({ wiq: "myworkqueue", payload: { "hello": "world" } });
    console.log("Pushed workitem with id " + workitem._id);

    Example

    Push a workitem with a file to myworkqueue

    import * as path  from 'path';
    import * as fs from "fs";
    import * as pako from 'pako';
    // ....
    const filepath = "/path/data.csv";
    const filename = path.basename(filepath);
    const workitem = await client.PushWorkitem({
    payload: {"name": "test " + filename}, wiq: "q2", name: "file test " + filename,
    files: [{ _id:"", filename, compressed: true, file: pako.deflate(fs.readFileSync(filepath, null)) }]});
    console.log("Pushed workitem with id " + workitem._id);

    Parameters

    • options: PushWorkitemOptions
    • priority: number = 2

      Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration

    • span: Span = null

    Returns Promise<Workitem>

  • Push multiple workitems to a workqueue. Workitems can be processed by a worker after calling PopWorkitem

    Returns

    an array of workitems that was pushed, including the workitem id's

    Parameters

    • options: PushWorkitemsOptions
    • priority: number = 2

      Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration

    • span: Span = null

    Returns Promise<Workitem[]>

  • Query a collection for data

    Returns

    an array of documents matching the query

    Example

    Get all documents with type "test" from entities collection

    const result = await client.Query({ query: { "_type": "test" } });
    

    Example

    Get all documents with type "test" from entities collection and only return the name field

    const result = await client.Query({ collectionname: "entities", query: { "_type": "test" }, projection: { "name": 1 } });
    

    Example

    Get all documents with type "test" from entities collection and only return the name field and order by name

    const result = await client.Query({ collectionname: "entities", query: { "_type": "test" }, projection: { "name": 1 }, orderby: { "name": 1 } });
    

    Type Parameters

    • T

    Parameters

    • options: QueryOptions
    • priority: number = 2

      Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration

    • span: Span = null

    Returns Promise<T[]>

  • Send message to queue or exchange. If recevied sends a reply back, set rpc = true to recevied response as return value. Be aware, right now there is no timeout on the wait, so if recevier never sends a reply it will hang for ever

    Returns

    If rpc is trye, will return the reply from the queue. If rpc is false, will return null when server has received the message

    See

    Example

    Send message to myqueue and wait for reply, then dump the result to console

    const result = await client.QueueMessage({ queuename: "myqueue", data: { "hello": "world" } }, true);
    console.log("result from queue " + JSON.stringify(result, null, 2));

    Example

    Send message to myexchange

    await client.QueueMessage({ exchangename: "myexchange", data: { "hello": "world" } }, false);
    

    Parameters

    • options: QueueMessageOptions
    • rpc: boolean = false
    • priority: number = 2

      Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration

    • span: Span = null

    Returns Promise<any>

  • Register an exchange and a message queue and consume it. Exchange's are registered in the mq collection. This uses streams to notify client about messages, and is therefore not supported using REST interface.

    Returns

    Returns the queue name, used to consume the exchange. Use this when unregistering the exchange with UnRegisterQueue

    See

    Example

    const queuename = await client.RegisterExchange({ exchange: "myexchange" }, (msg, payload, user, jwt) => {
    console.log(JSON.stringify(payload, null, 2));
    });
    console.log("registered exchange myexchange and is consuming it using queue " + queuename);

    Parameters

    • options: RegisterExchangeOptions
    • callback: ((msg: QueueEvent, payload: any, user: any, jwt: string) => any)
        • (msg: QueueEvent, payload: any, user: any, jwt: string): any
        • Parameters

          • msg: QueueEvent
          • payload: any
          • user: any
          • jwt: string

          Returns any

    • priority: number = 2

      Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration

    • span: Span = null

    Returns Promise<string>

  • Register and consume a Message Queue. Queues are registered in the mq collection. If no queue name is provided, a random queue name is generated. This uses streams to notify client about messages, and is therefore not supported using REST interface.

    Returns

    Returns the queue name. Use this name to send messages to the queue. Also use this to unregister the queue with UnRegisterQueue

    See

    Example

    const queuename = await client.RegisterQueue({ queuename: "myqueue" }, (msg, payload, user, jwt) => {
    console.log(JSON.stringify(payload, null, 2));
    if(payload == null) payload = {}
    payload.result = true
    // If returning a onject, it will be sent back to the sender of the message, if caller requested a response using rpc = true.
    return payload;
    });
    console.log("registered queue " + queuename);

    Parameters

    • options: RegisterQueueOptions
    • callback: ((msg: QueueEvent, payload: any, user: any, jwt: string) => any)
        • (msg: QueueEvent, payload: any, user: any, jwt: string): any
        • Parameters

          • msg: QueueEvent
          • payload: any
          • user: any
          • jwt: string

          Returns any

    • priority: number = 2
    • span: Span = null

    Returns Promise<string>

  • By default we use crendetials from the connection string or from jwt environment variable. But you can also call Signin to login with a username and password or with a jwt token. This function can also be used to validate credentials without changing the current credentials by setting validateonly to true.

    Returns

    Parameters

    Returns Promise<SigninResponse>

  • Start an agent inside Docker or Kubernetes Requires invoke permission on agent

    Returns

    void

    Parameters

    • options: StartAgentOptions

      StartAgentOptions

    • priority: number = 2

      Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration

    • span: Span = null

    Returns Promise<void>

  • Stop an agent running inside Docker or Kubernetes Requires invoke permission on agent

    Returns

    void

    Parameters

    • options: StopAgentOptions

      StopAgentOptions

    • priority: number = 2

      Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration

    • span: Span = null

    Returns Promise<void>

  • Tell server to close queue and stop receving message from the queue ( or queue consuming an exchange )

    See

    Example

    const queuename = await client.RegisterExchange({ exchange: "myexchange" }, async (msg, payload, user, jwt) => {
    console.log(JSON.stringify(payload, null, 2));
    await client.UnRegisterQueue({ queuename: queuename });
    console.log("unregistered queue " + queuename);
    });
    console.log("registered exchange myexchange and is consuming it using queue " + queuename);

    Parameters

    • options: UnRegisterQueueOptions
    • priority: number = 2

      Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration

    • span: Span = null

    Returns Promise<void>

  • Unregister a change stream ( watch ) created with Watch to stop receiving notifications from the watch.

    Parameters

    • options: UnWatchOptions
    • priority: number = 2

      Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration

    • span: Span = null

    Returns Promise<void>

  • Update ( replace ) an existing document in a collection. Any fields that starts with underscoore will be preserved. This is to prevent the system from overwriting fields that are used by the system. So if you update a document but leave out any of the existing _ fields, they will be added back to the document.

    Returns

    Returns the document that was updated

    Example

    Update a document with type "test" in entities collection

    const result = await client.InsertOne({ item: { "_type": "test", name: "find me" } });
    console.log("Inserted document with id: " + result._id + " and name: " + result.name);
    result.name = "Can you still find me?"
    const updated = await client.UpdateOne({ item: result });
    console.log("Updated document with id: " + updated._id + " and name: " + updated.name);

    Type Parameters

    • T

    Parameters

    • options: UpdateOneOptions
    • priority: number = 2

      Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration

    • span: Span = null

    Returns Promise<T>

  • Create a new workitem queue. Workitem queues are registered in the wiq collection. To delete all items from qyueue, set purge to true.

    Parameters

    • options: UpdateWorkItemQueueOptions

      UpdateWorkItemQueueOptions

    • priority: number = 2

      Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration

    • span: Span = null

    Returns Promise<WorkItemQueue>

  • Update an existing workitem. Workitem can be fetched using PopWorkitem. Use this to update the status of a workitem. You can also update the payload, and update or add files to the workitem.

    Returns

    Returns the updated workitem

    See

    PopWorkitem

    Example

    Update a workitem

    const workitem = await client.PopWorkitem({ wiq: "purchase_orders" }); // Will update the workitem state to processing
    if(workitem == null) return;
    await new Promise(resolve => setTimeout(resolve, 1000)); // simulate processing
    if(workitem.payload == null) workitem.payload = {}
    workitem.payload.transaction = "ID45434" // update payload
    workitem.status = "successful" // must be successful, processing or retry
    await client.UpdateWorkitem({ workitem }); // update workitem
    console.log("Updated workitem with id " + workitem._id);

    Parameters

    • options: UpdateWorkitemOptions
    • priority: number = 2

      Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration

    • span: Span = null

    Returns Promise<Workitem>

  • Upload a file to OpenIAP flow database. This uses streams to download file content, and is therefore not supported using REST interface.

    Returns

    Server response, including the file id

    See

    Example

    Upload test.txt from current folder to OpenIAP flow database

    const res = await client.UploadFile({ filename: "test.txt" });
    console.log("file upladed with id " + res.id);

    Parameters

    Returns Promise<UploadResponse>

  • Register a change stream ( watch ) on a collection. Use paths to narrow the scope of the watch. The callback will be called for each document that matches the paths when ever it is inserted, updated or deleted from the database This uses streams to notify client about changes, and is therefore not supported using REST interface.

    Returns

    server id assigned to the watch. Used with UnWatch to stop receiving notifications from the watch.

    Example

    const watchid = await db.Watch({ collectionname: "entities", paths: ["$.[?(@._type == 'test')]"] }, (operation, document) => {
    console.log(operation + " on " + document.name);
    });

    Parameters

    • options: WatchOptions
    • callback: ((operation: string, document: any) => void)
        • (operation: string, document: any): void
        • Parameters

          • operation: string
          • document: any

          Returns void

    • priority: number = 2

      Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration

    • span: Span = null

    Returns Promise<string>

  • Alias for emitter.on(eventName, listener).

    Since

    v0.1.26

    Parameters

    • eventName: string | symbol
    • listener: ((...args: any[]) => void)
        • (...args: any[]): void
        • Parameters

          • Rest ...args: any[]

          Returns void

    Returns openiap

  • Override this function to get notified when the client receives a message from the server. This will only be called for messages that are not handled by the client it self. Using EventMitter is also possible .on("message", (client, command, message) => {})

    Parameters

    • client: client

      Return client instance that received the message

    • message: Envelope

      The message that was received

    Returns Promise<any>

  • Returns

    Returns the User object if login was successful, otherwise throws an error

    Example

    var client = new openiap();
    client.connect().then(async (user) => {
    console.log("Logged in as " + user.username);
    }).catch((err) => {
    console.log("Failed to login: " + err);
    });

    Parameters

    • first: boolean = true

      Should be left out or used as true. Is used internally for controlling retry logic

    Returns Promise<User>

  • Synchronously calls each of the listeners registered for the event namedeventName, in the order they were registered, passing the supplied arguments to each.

    Returns true if the event had listeners, false otherwise.

    const EventEmitter = require('events');
    const myEmitter = new EventEmitter();

    // First listener
    myEmitter.on('event', function firstListener() {
    console.log('Helloooo! first listener');
    });
    // Second listener
    myEmitter.on('event', function secondListener(arg1, arg2) {
    console.log(`event with parameters ${arg1}, ${arg2} in second listener`);
    });
    // Third listener
    myEmitter.on('event', function thirdListener(...args) {
    const parameters = args.join(', ');
    console.log(`event with parameters ${parameters} in third listener`);
    });

    console.log(myEmitter.listeners('event'));

    myEmitter.emit('event', 1, 2, 3, 4, 5);

    // Prints:
    // [
    // [Function: firstListener],
    // [Function: secondListener],
    // [Function: thirdListener]
    // ]
    // Helloooo! first listener
    // event with parameters 1, 2 in second listener
    // event with parameters 1, 2, 3, 4, 5 in third listener

    Since

    v0.1.26

    Parameters

    • eventName: string | symbol
    • Rest ...args: any[]

    Returns boolean

  • Returns an array listing the events for which the emitter has registered listeners. The values in the array are strings or Symbols.

    const EventEmitter = require('events');
    const myEE = new EventEmitter();
    myEE.on('foo', () => {});
    myEE.on('bar', () => {});

    const sym = Symbol('symbol');
    myEE.on(sym, () => {});

    console.log(myEE.eventNames());
    // Prints: [ 'foo', 'bar', Symbol(symbol) ]

    Since

    v6.0.0

    Returns (string | symbol)[]

  • Returns the current max listener value for the EventEmitter which is either set by emitter.setMaxListeners(n) or defaults to defaultMaxListeners.

    Since

    v1.0.0

    Returns number

  • Returns the number of listeners listening to the event named eventName.

    Since

    v3.2.0

    Parameters

    • eventName: string | symbol

      The name of the event being listened for

    Returns number

  • Returns a copy of the array of listeners for the event named eventName.

    server.on('connection', (stream) => {
    console.log('someone connected!');
    });
    console.log(util.inspect(server.listeners('connection')));
    // Prints: [ [Function] ]

    Since

    v0.1.26

    Parameters

    • eventName: string | symbol

    Returns Function[]

  • Alias for emitter.removeListener().

    Since

    v10.0.0

    Parameters

    • eventName: string | symbol
    • listener: ((...args: any[]) => void)
        • (...args: any[]): void
        • Parameters

          • Rest ...args: any[]

          Returns void

    Returns openiap

  • Adds the listener function to the end of the listeners array for the event named eventName. No checks are made to see if the listener has already been added. Multiple calls passing the same combination of eventNameand listener will result in the listener being added, and called, multiple times.

    server.on('connection', (stream) => {
    console.log('someone connected!');
    });

    Returns a reference to the EventEmitter, so that calls can be chained.

    By default, event listeners are invoked in the order they are added. Theemitter.prependListener() method can be used as an alternative to add the event listener to the beginning of the listeners array.

    const myEE = new EventEmitter();
    myEE.on('foo', () => console.log('a'));
    myEE.prependListener('foo', () => console.log('b'));
    myEE.emit('foo');
    // Prints:
    // b
    // a

    Since

    v0.1.101

    Parameters

    • eventName: string | symbol

      The name of the event.

    • listener: ((...args: any[]) => void)

      The callback function

        • (...args: any[]): void
        • Parameters

          • Rest ...args: any[]

          Returns void

    Returns openiap

  • Override this function to add logic executed when the client has connected to the server. If credentails has been set, the client will automatically login before calling this function Using EventMitter is also possible using client.on("connected", (client) => {})

    Example

    using onConnected override

    var client = new openiap();
    client.onConnected = (client) => {
    console.log("Connected to server");
    }
    client.connect();

    Example

    using EventEmitter. Remember to remove the listener when done to avoid memory leaks

    var client = new openiap();
    client.on("connected", (client) => {
    console.log("Connected to server");
    });
    client.connect();

    Parameters

    Returns Promise<void>

  • Override this function to add logic executed when the client has disconnected from the server. Using EventMitter is also possible .on("disconnected", (client, error) => {})

    Example

    using onConnected override

    var client = new openiap();
    client.onDisconnected = (client, err) => {
    console.log("Disconnected from server");
    }
    client.connect();

    Example

    using EventEmitter. Remember to remove the listener when done to avoid memory leaks

    var client = new openiap();
    client.on("disconnected", (client, err) => {
    console.log("Disconnected from server");
    });
    client.connect();

    Parameters

    • client: openiap

      Return client instance that disconnected

    • error: Error

      If the disconnect was caused by an error, this will contain the error object

    Returns void

  • Adds a one-timelistener function for the event named eventName. The next time eventName is triggered, this listener is removed and then invoked.

    server.once('connection', (stream) => {
    console.log('Ah, we have our first user!');
    });

    Returns a reference to the EventEmitter, so that calls can be chained.

    By default, event listeners are invoked in the order they are added. Theemitter.prependOnceListener() method can be used as an alternative to add the event listener to the beginning of the listeners array.

    const myEE = new EventEmitter();
    myEE.once('foo', () => console.log('a'));
    myEE.prependOnceListener('foo', () => console.log('b'));
    myEE.emit('foo');
    // Prints:
    // b
    // a

    Since

    v0.3.0

    Parameters

    • eventName: string | symbol

      The name of the event.

    • listener: ((...args: any[]) => void)

      The callback function

        • (...args: any[]): void
        • Parameters

          • Rest ...args: any[]

          Returns void

    Returns openiap

  • Adds the listener function to the beginning of the listeners array for the event named eventName. No checks are made to see if the listener has already been added. Multiple calls passing the same combination of eventNameand listener will result in the listener being added, and called, multiple times.

    server.prependListener('connection', (stream) => {
    console.log('someone connected!');
    });

    Returns a reference to the EventEmitter, so that calls can be chained.

    Since

    v6.0.0

    Parameters

    • eventName: string | symbol

      The name of the event.

    • listener: ((...args: any[]) => void)

      The callback function

        • (...args: any[]): void
        • Parameters

          • Rest ...args: any[]

          Returns void

    Returns openiap

  • Adds a one-timelistener function for the event named eventName to the beginning of the listeners array. The next time eventName is triggered, this listener is removed, and then invoked.

    server.prependOnceListener('connection', (stream) => {
    console.log('Ah, we have our first user!');
    });

    Returns a reference to the EventEmitter, so that calls can be chained.

    Since

    v6.0.0

    Parameters

    • eventName: string | symbol

      The name of the event.

    • listener: ((...args: any[]) => void)

      The callback function

        • (...args: any[]): void
        • Parameters

          • Rest ...args: any[]

          Returns void

    Returns openiap

  • Returns a copy of the array of listeners for the event named eventName, including any wrappers (such as those created by .once()).

    const emitter = new EventEmitter();
    emitter.once('log', () => console.log('log once'));

    // Returns a new Array with a function `onceWrapper` which has a property
    // `listener` which contains the original listener bound above
    const listeners = emitter.rawListeners('log');
    const logFnWrapper = listeners[0];

    // Logs "log once" to the console and does not unbind the `once` event
    logFnWrapper.listener();

    // Logs "log once" to the console and removes the listener
    logFnWrapper();

    emitter.on('log', () => console.log('log persistently'));
    // Will return a new Array with a single function bound by `.on()` above
    const newListeners = emitter.rawListeners('log');

    // Logs "log persistently" twice
    newListeners[0]();
    emitter.emit('log');

    Since

    v9.4.0

    Parameters

    • eventName: string | symbol

    Returns Function[]

  • Removes all listeners, or those of the specified eventName.

    It is bad practice to remove listeners added elsewhere in the code, particularly when the EventEmitter instance was created by some other component or module (e.g. sockets or file streams).

    Returns a reference to the EventEmitter, so that calls can be chained.

    Since

    v0.1.26

    Parameters

    • Optional event: string | symbol

    Returns openiap

  • Removes the specified listener from the listener array for the event namedeventName.

    const callback = (stream) => {
    console.log('someone connected!');
    };
    server.on('connection', callback);
    // ...
    server.removeListener('connection', callback);

    removeListener() will remove, at most, one instance of a listener from the listener array. If any single listener has been added multiple times to the listener array for the specified eventName, then removeListener() must be called multiple times to remove each instance.

    Once an event is emitted, all listeners attached to it at the time of emitting are called in order. This implies that anyremoveListener() or removeAllListeners() calls after emitting and before the last listener finishes execution will not remove them fromemit() in progress. Subsequent events behave as expected.

    const myEmitter = new MyEmitter();

    const callbackA = () => {
    console.log('A');
    myEmitter.removeListener('event', callbackB);
    };

    const callbackB = () => {
    console.log('B');
    };

    myEmitter.on('event', callbackA);

    myEmitter.on('event', callbackB);

    // callbackA removes listener callbackB but it will still be called.
    // Internal listener array at time of emit [callbackA, callbackB]
    myEmitter.emit('event');
    // Prints:
    // A
    // B

    // callbackB is now removed.
    // Internal listener array [callbackA]
    myEmitter.emit('event');
    // Prints:
    // A

    Because listeners are managed using an internal array, calling this will change the position indices of any listener registered after the listener being removed. This will not impact the order in which listeners are called, but it means that any copies of the listener array as returned by the emitter.listeners() method will need to be recreated.

    When a single function has been added as a handler multiple times for a single event (as in the example below), removeListener() will remove the most recently added instance. In the example the once('ping')listener is removed:

    const ee = new EventEmitter();

    function pong() {
    console.log('pong');
    }

    ee.on('ping', pong);
    ee.once('ping', pong);
    ee.removeListener('ping', pong);

    ee.emit('ping');
    ee.emit('ping');

    Returns a reference to the EventEmitter, so that calls can be chained.

    Since

    v0.1.26

    Parameters

    • eventName: string | symbol
    • listener: ((...args: any[]) => void)
        • (...args: any[]): void
        • Parameters

          • Rest ...args: any[]

          Returns void

    Returns openiap

  • By default EventEmitters will print a warning if more than 10 listeners are added for a particular event. This is a useful default that helps finding memory leaks. The emitter.setMaxListeners() method allows the limit to be modified for this specific EventEmitter instance. The value can be set toInfinity (or 0) to indicate an unlimited number of listeners.

    Returns a reference to the EventEmitter, so that calls can be chained.

    Since

    v0.3.5

    Parameters

    • n: number

    Returns openiap

  • Wrapper around JSON.stringify to allow serialiszing object with regular expressions

    Returns

    Parameters

    • object: any

      Object to serialize

    Returns string

  • Used to generate a unique identifier, used for example when creating new packages.

    Returns

    A unique identifier

    Returns string

  • Returns a copy of the array of listeners for the event named eventName.

    For EventEmitters this behaves exactly the same as calling .listeners on the emitter.

    For EventTargets this is the only way to get the event listeners for the event target. This is useful for debugging and diagnostic purposes.

    const { getEventListeners, EventEmitter } = require('events');

    {
    const ee = new EventEmitter();
    const listener = () => console.log('Events are fun');
    ee.on('foo', listener);
    getEventListeners(ee, 'foo'); // [listener]
    }
    {
    const et = new EventTarget();
    const listener = () => console.log('Events are fun');
    et.addEventListener('foo', listener);
    getEventListeners(et, 'foo'); // [listener]
    }

    Since

    v15.2.0, v14.17.0

    Parameters

    • emitter: EventEmitter | _DOMEventTarget
    • name: string | symbol

    Returns Function[]

  • A class method that returns the number of listeners for the given eventNameregistered on the given emitter.

    const { EventEmitter, listenerCount } = require('events');
    const myEmitter = new EventEmitter();
    myEmitter.on('event', () => {});
    myEmitter.on('event', () => {});
    console.log(listenerCount(myEmitter, 'event'));
    // Prints: 2

    Since

    v0.9.12

    Deprecated

    Since v3.2.0 - Use listenerCount instead.

    Parameters

    • emitter: EventEmitter

      The emitter to query

    • eventName: string | symbol

      The event name

    Returns number

  • const { on, EventEmitter } = require('events');

    (async () => {
    const ee = new EventEmitter();

    // Emit later on
    process.nextTick(() => {
    ee.emit('foo', 'bar');
    ee.emit('foo', 42);
    });

    for await (const event of on(ee, 'foo')) {
    // The execution of this inner block is synchronous and it
    // processes one event at a time (even with await). Do not use
    // if concurrent execution is required.
    console.log(event); // prints ['bar'] [42]
    }
    // Unreachable here
    })();

    Returns an AsyncIterator that iterates eventName events. It will throw if the EventEmitter emits 'error'. It removes all listeners when exiting the loop. The value returned by each iteration is an array composed of the emitted event arguments.

    An AbortSignal can be used to cancel waiting on events:

    const { on, EventEmitter } = require('events');
    const ac = new AbortController();

    (async () => {
    const ee = new EventEmitter();

    // Emit later on
    process.nextTick(() => {
    ee.emit('foo', 'bar');
    ee.emit('foo', 42);
    });

    for await (const event of on(ee, 'foo', { signal: ac.signal })) {
    // The execution of this inner block is synchronous and it
    // processes one event at a time (even with await). Do not use
    // if concurrent execution is required.
    console.log(event); // prints ['bar'] [42]
    }
    // Unreachable here
    })();

    process.nextTick(() => ac.abort());

    Since

    v13.6.0, v12.16.0

    Returns

    that iterates eventName events emitted by the emitter

    Parameters

    • emitter: EventEmitter
    • eventName: string

      The name of the event being listened for

    • Optional options: StaticEventEmitterOptions

    Returns AsyncIterableIterator<any>

  • Creates a Promise that is fulfilled when the EventEmitter emits the given event or that is rejected if the EventEmitter emits 'error' while waiting. The Promise will resolve with an array of all the arguments emitted to the given event.

    This method is intentionally generic and works with the web platform EventTarget interface, which has no special'error' event semantics and does not listen to the 'error' event.

    const { once, EventEmitter } = require('events');

    async function run() {
    const ee = new EventEmitter();

    process.nextTick(() => {
    ee.emit('myevent', 42);
    });

    const [value] = await once(ee, 'myevent');
    console.log(value);

    const err = new Error('kaboom');
    process.nextTick(() => {
    ee.emit('error', err);
    });

    try {
    await once(ee, 'myevent');
    } catch (err) {
    console.log('error happened', err);
    }
    }

    run();

    The special handling of the 'error' event is only used when events.once()is used to wait for another event. If events.once() is used to wait for the 'error' event itself, then it is treated as any other kind of event without special handling:

    const { EventEmitter, once } = require('events');

    const ee = new EventEmitter();

    once(ee, 'error')
    .then(([err]) => console.log('ok', err.message))
    .catch((err) => console.log('error', err.message));

    ee.emit('error', new Error('boom'));

    // Prints: ok boom

    An AbortSignal can be used to cancel waiting for the event:

    const { EventEmitter, once } = require('events');

    const ee = new EventEmitter();
    const ac = new AbortController();

    async function foo(emitter, event, signal) {
    try {
    await once(emitter, event, { signal });
    console.log('event emitted!');
    } catch (error) {
    if (error.name === 'AbortError') {
    console.error('Waiting for the event was canceled!');
    } else {
    console.error('There was an error', error.message);
    }
    }
    }

    foo(ee, 'foo', ac.signal);
    ac.abort(); // Abort waiting for the event
    ee.emit('foo'); // Prints: Waiting for the event was canceled!

    Since

    v11.13.0, v10.16.0

    Parameters

    • emitter: _NodeEventTarget
    • eventName: string | symbol
    • Optional options: StaticEventEmitterOptions

    Returns Promise<any[]>

  • Parameters

    • emitter: _DOMEventTarget
    • eventName: string
    • Optional options: StaticEventEmitterOptions

    Returns Promise<any[]>

  • const {
    setMaxListeners,
    EventEmitter
    } = require('events');

    const target = new EventTarget();
    const emitter = new EventEmitter();

    setMaxListeners(5, target, emitter);

    Since

    v15.4.0

    Parameters

    • Optional n: number

      A non-negative number. The maximum number of listeners per EventTarget event.

    • Rest ...eventTargets: (EventEmitter | _DOMEventTarget)[]

    Returns void

Generated using TypeDoc