actionhero / actionhero-node-client

actionhero client (for other node servers)
Apache License 2.0
34 stars 11 forks source link

ActionheroNodeClient

For one node.js servers talking to another ActionHero server, over the socket protocol.

NPM Version Node Version Greenkeeper badge test

This library makes it easy for one nodeJS process to talk to a remote actionhero server.

This library makes use of actionhero's TCP socket connections to enable fast, stateful connections. This library also allows for many concurrent and asynchronous requests to be running in parallel by making use of actionhero's message counter.

notes:

Setup

Installation should be as simple as:

npm install --save actionhero-node-client

and then you can include it in your projects with:

var ActionheroNodeClient = require("actionhero-node-client");
var client = new ActionheroNodeClient();

Once you have included the ActionheroClient library within your project, you can connect like this:

await client.connect({
  host: "127.0.0.1",
  port: "5000",
});

default options (which you can override) are:

var defaults = {
  host: "127.0.0.1",
  port: "5000",
  delimiter: "\r\n",
  logLength: 100,
  secure: false,
  timeout: 5000,
  reconnectTimeout: 1000,
  reconnectAttempts: 10,
};

Methods

One you are connected (by waiting for the "connected" event or using the connect callback), the following methods will be available to you:

Events

ActionheroNodeClient will emit a few types of events (many of which are caught in the example below). Here are the events, and how you might catch them:

Data

There are a few data elements you can inspect on actionheroClient:

Example

var ActionheroNodeClient = require("actionhero-node-client");

async function main () {
  const client = new ActionheroNodeClient()

  client.on('say', (message) => {
    console.log(' > SAY: ' + message.message + ' | from: ' + message.from)
  })

  client.on('welcome', (welcome) => {
    console.log('WELCOME: ' + welcome)
  })

  client.on('error', (error) => {
    console.log('ERROR: ' + error)
  })

  client.on('end', () => {
    console.log('Connection Ended')
  })

  client.on('timeout', (request, caller) => {
    console.log(request + ' timed out')
  })

  await client.connect({host: '127.0.0.1', port: '5000'})

  // get details about myself
  console.log('My Details: ', client.details)

  // try an action
  const params = { key: 'mykey', value: 'myValue' }
  let {error, data, delta} = await client.actionWithParams('cacheTest', params)
  if (error) { throw error }
  console.log('cacheTest action response: ', data)
  console.log(' ~ request duration: ', delta)

  // join a chat room and talk
  await client.roomAdd('defaultRoom')
  await client.say('defaultRoom', 'Hello from the actionheroClient')
  await client.roomLeave('defaultRoom')

  // leave
  await client.disconnect()
  console.log('all done!')
}

main()