Get Loyalty Points from an External Resource

In most use cases the loyalty points are set up and calculated in an external service.

For our example we created a fake loyalty service called Shopgate Tutorial Points. It’s a mock for a real provider.

In this part of the tutorial we want to create an implementation to access this service.

Installing dependencies

Since we already have a step in place we just need to replace the static value with the value of the response.

To create a request more easily and to parallelize the requests we need the request helper library request-promise and the promise helper library bluebird.

To install we need to:

  1. Navigate to the extension folder: cd extensions/@myAwesomeOrganization-loyaltyPoints/extension
  2. Install modules: npm install request request-promise bluebird

Implementing the request

Now we are ready to include both modules into our step.

With the request-promise library we will create a request to the URL of the service. To get loyalty points for this specific product we also need to pass the product id as a query string.

The Array.map function which we used for the static value works only for synchronous calls. The library bluebird helps us to also use the method “map” in the context of a promise.

After the implementation it should look like this:

const request = require('request-promise')
const Promise = require('bluebird')

module.exports = async (context, input) => {
  const products = await Promise.map(input.products, async (product) => {
    const result = await requestLoyaltyPoints(product.id)
    product.loyaltyPoints = result.loyaltyPoints
    return product
  })

  return {products: products}
}

function requestLoyaltyPoints (productId) {
  const options = {
    url: 'https://data.shopgate.com/tutorials/loyaltyPoints.json',
    qs: { productId: productId },
    json: true
  }
  return request(options)
}

Test

To test our new implementation we need to call the pipeline again with the same parameter as in the step before:

Set up the request:

  • Method: POST
  • URL: http://localhost:8090/pipelines/shopgate.catalog.getProducts.v1.json
  • Body-type: JSON (application/json)
  • Body: {“categoryId”:"[Insert the category number here]"}

You should now find the loyaltyPoints property with the value 42 in every product.