Skip to content

Writing services

Nirmal Lanka edited this page Mar 20, 2018 · 14 revisions

Introduction by example

Take this example of a send-abstraction service:

//πŸ“/send-service.js

exports.sendText = function(userId, msg) { 
  return this.$.send.text(userId, msg)
};

exports.sendTiles = function(userId, elements) {
  return this.$.send.tiles.generic(userId, elements)
};

An Evilbot service is similar in use to an ASP.NET or Angular service. In the most straightforward terms, it's an abstraction mechanism that employs simple injection of APIs as objects.

this.$ is the access-point of references necessary for a service.

this.$ children available for services

API Description
factories Construction methods for rich response creation
send Send methods for different supported types of responses

factories methods example

//πŸ“/tiles-factory.js

exports.createSimpleTile = function() { 
  
  const createAction = this.$.factories.action.url;
  const createButton = this.$.factories.button.postback;
  const createGenericTile = this.$.factories.tile.generic;
  
  return createGenericTile(
    'My tile', 
    'Lorem ipsum dolor sit amet', 
    'https://___.png', 
    createAction('https://medium.com/emblatech'),
    [ 
      createButton('Tap me!', 'demo.simpleTile.buttons.1'), // button-text, arbritary button-id
      createButton('Tap me!', 'demo.simpleTile.buttons.2'),
    ]
  );
}

It's important to write the methods that access this.$ as function () instead of lambdas in the form of () => due to the scoping rules in Javascript.

In the above example, buttons and an URL-redirect action is created and then referred inside the generic tile construction. This pattern is helpful in composing complex rich response objects to reply with.

This service can be used in an interaction as follows:

//πŸ“/bot.js

const simpleTileObj = SimpleTileFactory.createSimpleTile()

send methods example

//πŸ“/send-service.js

exports.sendTiles = function(userId, elements) {
  return this.$.send.tiles.generic(userId, elements)
};

Here a complex item, in this case a list of tiles, is sent using the send API. This service can be used in an interaction as follows:

//πŸ“/bot.js

SendService.sendTiles(_.userId, [ 
  simpleTileObj,
  simpleTileObj,
  simpleTileObj
]).subscribe()

Clone this wiki locally