Caseblocks Logo

How to create a reusable script

How To Create Reusable scripts

Lifecycle functions are defined to perform a particular task, be that send an email based with some case data, or perform complicated validations.  Each have a different purpose, however, they may share common features.  Splitting the code into reusable parts is a proven way to reduce bugs and increase productivity in software development.

Library Functions

CaseBlocks gives you the ability to split off your code into library functions as a separate script.

Script Claim/library

{
  cityValid: function(city) {
    return city !== undefined && city.length > 0
  },
  getWeather: function(payload) {
    return new Promise(function(resolve, reject) {
      httpGetJson("http://api.openweathermap.org/data/2.5/weather?q=" + payload.city + "&appid=cb56f21e4cbd3cb916f65974209e1dfc", function(result) {
        var weatherSummary = result.weather.map(function(d) { d.main }).join(", ") + " " + result.main.temp - 273.15 + "°"
        payload.weather = weatherSummary
        resolve(payload)
      })
    })
  }
}

The above example has two functions. The first is a synchronous call to check some validation, and the second is an asynchronous function that gets the current weather in the city listed on the case. It will then update the payload with a weather summary and return. If we are running a Task to update the weather, the script for this is below:

Script; Event/updateWeather

var library = fn.claim.library;

if (library.validCity(payload.city)) {
  library.getWeather(payload).
  then((payload) => exit(payload))
} else {
  fail("City must be specified")
}

Splitting up your code into reusable code is a good way to improve productivity in a team, and to limit bugs entering your code. One other benefit is that you now have a list of functions that you can write tests for to make sure they are functioning as you would expect, expect a How To on that coming soon.