How to implement User Defined Functions using Velocity

In the previous post, we have seen implementing User defined functions using Groovy.
Now we will check use of Velocity template in a User Defined Function.

  • Velocity Template Language(VTL) can be used to form a text template.E.g. customizing the body of an email
  • It can be used to substitute a variable value in a text output. E.g. substituting receiver’s name from a variable etc.

Example

Here is a simple schema to format a message. formatMessage function substitutes name and code into a message String.

type Query {
formatMessage(name: String, code: Int):
    String @tan(type:Velocity, inline: "Hi $name ! Your input code is $code")
}

Let’s execute the function.

query{
  formatMessage(name: "abc", code: 999)
}
#result
{
  "data": {
    "formatMessage": "Hi abc ! Your input code is 999"
  }
}

Using Velocity Templates is easy.
Whenever you have a requirement to formulate a text message with dynamic behaviour, simply use VTL!