Skip to main content

Sample Javascript Expressions

Introduction

This document provides examples and explanations of JavaScript expression snippets for use with the Conscia Digital Experience Engine (DX Engine). To learn more about expressions, visit the Expressions section.

Going forward, we will be updating this document to add more and more examples.

Accessing Context Values

You can use the contextField() function to access values in the context of a DX Component. For example, if the context contains a currency specification:

{
"currency": "USD"
}

You can use contextField to access the currency value:

contextField("currency")

You do not need to define a context field through the UI or API to use the contextField() function to retrieve a value from context.

You can use the contextField() function to construct Webservice URLs. For example, if a Webservice requires invocation of a path such as /cart/{cartId}, in a Conscia Universal API Component that receives context that specifies a cart ID:

{
"cartId": "{cartId}"
}

For Webservice Path, set "Get value from" to "JS Expression" and set the value to:

`/carts/${contextField('cartId')}`

At runtime, Conscia will expand this value to /carts/{cartId}, where cartId is the value passed in context.

The backticks (`) indicate a JavaScript template literal, which allows features such as string interpolation within what would otherwise be a string literal. In other words, a template literal is a string that can contain variables and function calls that the JavaScript engine expands before other logic accesses the string value. This allows a combination of literals, variable references, and function calls without the need to concatenate values. Note the use of the dollar sign ($) and curly braces ({}) to enclose function calls and variable references.

Accessing Secrets

You can use the secret() function to access secrets.

For example, in the Base URL property of a Conscia connection that connects to Commercetools, you can set "Get value from" to "JS Expression" and set its value to a JavaScript template literal such as the following to construct a URL that embeds the values of two secrets into a literal value:

`https://api.${secret('commercetools-region')}.gcp.commercetools.com/${secret('commercetools-project')}`

Then, under Base Headers, create an entry named Authorization, set "Get value from" to "JS Expression", and set its value to:

commerceTools.generateToken(secret('commercetools-region') 
+ '.gcp', secret('commercetools-project'),
secret('commercetools-client'),
secret('commercetools-secret')).then(token => 'Bearer ' + token)

Because a function call returns the entire required value, there is no need for a template literal in this case.

Creating a Payload for a Webservice Call

You can use the assign() function from the Lodash library to define the payload for a Webservice call.

For example, if the context contains a currency identifier:

{
"currency": "USD"
}

To pass the currency value from context as the body of a Webservice, you can use the assign() function in the Body property of the Conscia DX Component that invokes that Webservice:

_.assign({}, {'currency': contextField('currency')})

The underscore (_) represents the Lodash library. The empty curly braces ({}) passed as the first parameter creates an empty object. The second parameter contains values to populate that object.

Define Component Dependencies

You can use the componentStatus() function to specify component dependencies. For example, if a DX Component depends on successful invocation of two other Orchestration Components with component identifiers component-a and component-b, set the Trigger property of the depending component to the following:

componentStatus('component-a') === 'VALID'
&& componentStatus('component-b') === 'VALID'

For more information about DX Component status, see: Conscia DX Engine Component Anatomy

Additionally, Conscia registers dependencies wherever a component enriches a context field used by another component.

You can also use the componentResponse() function to specify component dependencies as described in the next section.

Access Component Response

You can use the response object to access the response of the current component. For example, if the response of a DX Component appears as follows:

"response": {
"type": "Cart",
"id": "6684135f-bc0a-4a01-be42-f8195531aea6"
//...
}

And you only want the component to return only the value of the id key under a key named cart-id, you can use the following expression as the value of the Component's Response Transform:

_.assign({}, {
'cart-id': response.id
})

You can use the componentResponse() function to access the response of another DX component. For example, if the format of the response of the fetch-product-ids component is as follows:

{
"productIds": [
"productId1",
"productId2"
]
}

You can use the following expression to access the first productId using the castArray function of the Lodash library (Lodash castArray documentation):

_.castArray(componentResponse('fetch-product-ids').productIds)[0]

Process Handlebars Templates

You can use the processHandlebars() function to process Handlebars templates. The first argument to the processHandlebars() function is the Handlebars template. The second argument to the processHandlebars() function is the data to process with that template. The result of the processHandlebars() function is the result of using Handlebars to invoke the template with the specified values.

For further details, see:

Convert JSON Object to JSON Array

Conscia constructs generally return JSON objects. Attribute lists require an array format.

You can use the map() function in the Lodash library to convert a JSON object to a JSON array.

For example, if you have a Component that would return this result:

{
"containsArray": [
{
"key": "key",
"key2": "value2",
"key3": "value3"
},
{
"key": "value",
"key2": "value2",
"key3": "value3"
},
{
"key": "value",
"key2": "value2",
"key3": "value3"
}
]
}

You can use the following Response Transformation in this Component:

_.map(response.containsArray, record => _.assign({ "value": record.key, "name": record.key2 }))

This returns an array of objects with the values from key and key2 in the source data under new keys named value and name, with this result:

[
{
"value": "value",
"name": "value2",
},
{
"value": "value",
"name": "value2",
},
{
"value": "value",
"name": "value2",
}
]

Generate an Object

You can use the identity() method in the Lodash library to construct an object and return that object as a value.

_.identity({ 'key': value });