Transformers

transformers

Introduction

Waylay rule engine is protocol agnostic. Among other things, that simplifies templating rules. For instance, we can use the same rule for smart meters that are connected over different networks (Sigfox, LoRA) and different protocols (HTTPS and Websockets). In order to bridge different protocols, you need to use Waylay Broker or you can push data directly towards rule engine using REST over HTTPS. In addition to bridging different protocols, Broker also stores messages in three different storages as presented in the architecture overview.

Such approach is very robust, but there are use cases when this is still not enough. Bridging protocols is great, but one thing that Broker imposes is implicit: JSON payload format that is waylay specific.

Transform functions - transformers allow you to pre-process messages before being forwarded to the Broker. That way you can do additional payload decoding or data enrichment before forwarding and storing data in waylay.

In most cases, transformers should be combined together with webscripts(/features/data_ingestion/Webhooks/webscripts/) - especially when we integrate LoRa or Sigfox devices LPWAN integration.

Let’s now see the code:

waylay.data.baseUrl = options.globalSettings.waylay_data ||  "https://data.waylay.io"

//data that needs to be transformed
var data = options.requiredProperties.data

/*
resource under which to store the data. If that is in the payload, you can do this:
var resource = JSON.parse(data).resource
Otherwise it is provided as the input argument:
*/
var resource = options.requiredProperties.resource

//replace this with your own implementation
var payloadTransformation = function(data){
    return JSON.parse(data)
}

// In case you want to store the data
waylay.data.postSeries(resource, payloadTransformation(data))
   .then(response=> {
        console.log("message stored")
        send()
        }
    ).catch(err =>{
      send(new Error(err))
    })

// In case you only want to return data
// send(null, {data: payloadTransformation(data)})

here we assume that we only need to adjust the temperature measurements (dividing it by 10) that comes in this format:

{ data: { temperature : 244 } }

In the transformer above, first we transformed the data and then forwarded and stored it under the resource name resource using waylayUtil package. Transformers can also be accessed directly over REST.