sse_type_util module

Functions for data transforms.

coerce/2

Turns an input of any type into a specified data type. Returns a default value in the specified type if the transformation is not possible.

coerce(type(), term()) ->
  term().

The function has shorthand invocations per type.

Table 1. Transform options, shorthands and default values
Option Shorthand Default value
sse_type_util:coerce(boolean, Value) b(Value) false
sse_type_util:coerce(float, Value) f(Value) 0.0
sse_type_util:coerce(integer, Value) i(Value) 0
sse_type_util:coerce(string, Value) s(Value) ""
sse_type_util:coerce(binary, Value) n/a <<>>
sse_type_util:coerce(utf8, Value) u(Value) <<>>

The example below constructs a single Erlang string from a number of input fields. To do that, it turns price - originally a float - into a string. It also turns the outcome Erlang string into a utf8 string to make the Erlang map suitable for a JSON transformation.

<request name="BuildMessage"
    service="Expr"
    fields="time price stock">
    <prop name="expr.src"
        content-type="text/x-erlang"><![CDATA[
Stock = get("stock"),
Time = get("time"),
Price = get("price"),

% Get Erlang string version of price - originally a float
StringPrice = s(Price),

% Build message text from input fields
Text = 
    "The price of " ++ Stock ++ 
    " as of " ++ Time ++
    " is " ++ StringPrice ++ ".",

% Build message map, turning text into utf8 string as message field is of type json 
Message = #{
    "text" => u(Text)
},
put("message", Message),
"Ok".

    ]]></prop>
    <reply name="Ok"
        fields="message"/>
</request>
Tip: SPARKL fields enforce their type on the data they carry. For example, the integer 1 sent in a string type field arrives as "1". A JSON type field transforms an Erlang map into a JSON object. If the transformation fails, SPARKL sends a default value in the field.