Resolver mapping template utility reference
AWS AppSync defines a set of utilities which can be leveraged within a GraphQL resolver to simplify interactions with data sources. Some of these utilities are general to be used with any data source, such as the generation of IDs or timestamps, while others are specific to a data source itself.
Utility helpers in $util
The $util
variable contains general utility methods that make it easier to
work with data.
Unless otherwise specified, all utilities use the UTF-8 character set.
-
$util.qr()
and$util.quiet()
-
Executes a VTL statement while suppressing the returned value of the execution. This is useful if you wish to run methods without using temporary placeholders such as adding items to a map, etc. For example:
#set ($myMap = {}) #set($discard = $myMap.put("id", "first value"))
Becomes:
#set ($myMap = {}) $util.qr($myMap.put("id", "first value"))
-
$util.escapeJavaScript(String) : String
-
Returns the input string as a JavasScript escaped string.
-
$util.urlEncode(String) : String
-
Returns the input string as an
application/x-www-form-urlencoded
encoded string. -
$util.urlDecode(String) : String
-
Decodes an
application/x-www-form-urlencoded
encoded string back to its non-encoded form. -
$util.base64Encode( byte[] ) : String
-
Encodes the input into a base64-encoded string.
-
$util.base64Decode(String) : byte[]
-
Decodes the data from a base64-encoded string.
-
$util.parseJson(String) : Object
-
Takes “stringified” JSON and returns an object representation of the result.
-
$util.toJson(Object) : String
-
Takes an object and returns a “stringified” JSON representation of that object.
-
$util.autoId() : String
-
Returns a 128-bit randomly generated UUID.
-
$util.unauthorized()
-
Throws
Unauthorized
for the field being resolved. This can be used in request or response mapping templates to decide if the caller should be allowed to resolve the field. -
$util.error(String)
-
Throws a custom error. This can be used in request or response mapping templates if the template detects an error with the request or with the invocation result.
-
$util.error(String, String)
-
Throws a custom error. This can be used in request or response mapping templates if the template detects an error with the request or with the invocation result. Additionally, an
errorType
can be specified. -
$util.error(String, String, Object)
-
Throws a custom error. This can be used in request or response mapping templates if the template detects an error with the request or with the invocation result. Additionally, an
errorType
and adata
field can be specified. Thedata
value will be added to the correspondingerror
block insideerrors
in the GraphQL response. Note:data
will be filtered based on the query selection set. -
$util.error(String, String, Object, Object)
-
Throws a custom error. This can be used in request or response mapping templates if the template detects an error with the request or with the invocation result. Additionally, an
errorType
field, adata
field, and aerrorInfo
field can be specified. Thedata
value will be added to the correspondingerror
block insideerrors
in the GraphQL response. Note:data
will be filtered based on the query selection set. TheerrorInfo
value will be added to the correspondingerror
block insideerrors
in the GraphQL response. Note:errorInfo
will NOT be filtered based on the query selection set. -
$util.appendError(String)
-
Appends a custom error. This can be used in request or response mapping templates if the template detects an error with the request or with the invocation result. Unlike
$util.error(String)
, the template evaluation will not be interrupted, so that data can be returned to the caller. -
$util.appendError(String, String)
-
Appends a custom error. This can be used in request or response mapping templates if the template detects an error with the request or with the invocation result. Additionally, an
errorType
can be specified. Unlike$util.error(String, String)
, the template evaluation will not be interrupted, so that data can be returned to the caller. -
$util.appendError(String, String, Object)
-
Appends a custom error. This can be used in request or response mapping templates if the template detects an error with the request or with the invocation result. Additionally, an
errorType
and adata
field can be specified. Unlike$util.error(String, String, Object)
, the template evaluation will not be interrupted, so that data can be returned to the caller. Thedata
value will be added to the correspondingerror
block insideerrors
in the GraphQL response. Note:data
will be filtered based on the query selection set. -
$util.appendError(String, String, Object, Object)
-
Appends a custom error. This can be used in request or response mapping templates if the template detects an error with the request or with the invocation result. Additionally, an
errorType
field, adata
field, and aerrorInfo
field can be specified. Unlike$util.error(String, String, Object, Object)
, the template evaluation will not be interrupted, so that data can be returned to the caller. Thedata
value will be added to the correspondingerror
block insideerrors
in the GraphQL response. Note:data
will be filtered based on the query selection set. TheerrorInfo
value will be added to the correspondingerror
block insideerrors
in the GraphQL response. Note:errorInfo
will NOT be filtered based on the query selection set. -
$util.validate(boolean, String) : void
-
If the condition is false, throw a CustomTemplateException with the specified message.
-
$util.validate(boolean, String, String) : void
-
If the condition is false, throw a CustomTemplateException with the specified message and error type.
-
$util.validate(boolean, String, String, Object) : void
-
If the condition is false, throw a CustomTemplateException with the specified message and error type, as well as data to return in the response.
-
$util.isNull(Object) : boolean
-
Returns true if the supplied object is null.
-
$util.isNullOrEmpty(String) : boolean
-
Returns true if the supplied data is null or an empty string. Otherwise, returns false.
-
$util.isNullOrBlank(String) : boolean
-
Returns true if the supplied data is null or a blank string. Otherwise, returns false.
-
$util.defaultIfNull(Object, Object) : Object
-
Returns the first Object if it is not null. Otherwise, returns second object as a “default Object”.
-
$util.defaultIfNullOrEmpty(String, String) : String
-
Returns the first String if it is not null or empty. Otherwise, returns second String as a “default String”.
-
$util.defaultIfNullOrBlank(String, String) : String
-
Returns the first String if it is not null or blank. Otherwise, returns second String as a “default String”.
-
$util.isString(Object) : boolean
-
Returns true if Object is a String.
-
$util.isNumber(Object) : boolean
-
Returns true if Object is a Number.
-
$util.isBoolean(Object) : boolean
-
Returns true if Object is a Boolean.
-
$util.isList(Object) : boolean
-
Returns true if Object is a List.
-
$util.isMap(Object) : boolean
-
Returns true if Object is a Map.
-
$util.typeOf(Object) : String
-
Returns a String describing the type of the Object. Supported type identifications are: “Null”, “Number”, “String”, “Map”, “List”, “Boolean”. If a type cannot be identified, the return type is “Object”.
-
$util.matches(String, String) : Boolean
-
Returns true if the specified pattern in the first argument matches the supplied data in the second argument. The pattern must be a regular expression such as
$util.matches("a*b", "aaaaab")
. The functionality is based on Pattern, which you can reference for further documentation. -
$util.authType() : String
-
Returns a String describing the multi-auth type being used by a request, returning back either "IAM Authorization", "User Pool Authorization", "Open ID Connect Authorization", or "API Key Authorization".
AWS AppSync directives
AppSync exposes directives to facilitate developer productivity when writing Velocity.
#return(Object)
The #return
directive comes handy if you need to
return prematurely from any mapping template. #return
is analogous to the
return keyword in programming languages, as
it will return from the closest scoped block of logic. What this means is using
#return
inside a resolver mapping template will return from the resolver.
Additionally, using #return
from a function mapping template will return from
the function and will continue the execution to either the next function in the pipeline
or
the resolver response mapping template.
#return
Same as #return(Object)
but null
will be
returned instead.
Time helpers in $util.time
The $util.time
variable contains datetime methods to help generate
timestamps, convert between datetime formats, and parse datetime strings. The syntax
for
datetime formats is based on DateTimeFormatter
Standalone function examples
$util.time.nowISO8601() : 2018-02-06T19:01:35.749Z $util.time.nowEpochSeconds() : 1517943695 $util.time.nowEpochMilliSeconds() : 1517943695750 $util.time.nowFormatted("yyyy-MM-dd HH:mm:ssZ") : 2018-02-06 19:01:35+0000 $util.time.nowFormatted("yyyy-MM-dd HH:mm:ssZ", "+08:00") : 2018-02-07 03:01:35+0800 $util.time.nowFormatted("yyyy-MM-dd HH:mm:ssZ", "Australia/Perth") : 2018-02-07 03:01:35+0800
Conversion examples
#set( $nowEpochMillis = 1517943695758 ) $util.time.epochMilliSecondsToSeconds($nowEpochMillis) : 1517943695 $util.time.epochMilliSecondsToISO8601($nowEpochMillis) : 2018-02-06T19:01:35.758Z $util.time.epochMilliSecondsToFormatted($nowEpochMillis, "yyyy-MM-dd HH:mm:ssZ") : 2018-02-06 19:01:35+0000 $util.time.epochMilliSecondsToFormatted($nowEpochMillis, "yyyy-MM-dd HH:mm:ssZ", "+08:00") : 2018-02-07 03:01:35+0800
Parsing examples
$util.time.parseISO8601ToEpochMilliSeconds("2018-02-01T17:21:05.180+08:00") : 1517476865180 $util.time.parseFormattedToEpochMilliSeconds("2018-02-02 01:19:22+0800", "yyyy-MM-dd HH:mm:ssZ") : 1517505562000 $util.time.parseFormattedToEpochMilliSeconds("2018-02-02 01:19:22", "yyyy-MM-dd HH:mm:ss", "+08:00") : 1517505562000
Usage with AWS scalars
The following formats are compatible with AWSDate
,
AWSDateTime
, and AWSTime
.
$util.time.nowFormatted("yyyy-MM-dd[XXX]", "-07:00:30") : 2018-07-11-07:00 $util.time.nowFormatted("yyyy-MM-dd'T'HH:mm:ss[XXXXX]", "-07:00:30") : 2018-07-11T15:14:15-07:00:30
-
$util.time.nowISO8601() : String
-
Returns a String representation of UTC in ISO8601 format
. -
$util.time.nowEpochSeconds() : long
-
Returns the number of seconds from the epoch of 1970-01-01T00:00:00Z to now.
-
$util.time.nowEpochMilliSeconds() : long
-
Returns the number of milliseconds from the epoch of 1970-01-01T00:00:00Z to now.
-
$util.time.nowFormatted(String) : String
-
Returns a string of the current timestamp in UTC using the specified format from a String input type.
-
$util.time.nowFormatted(String, String) : String
-
Returns a string of the current timestamp for a timezone using the specified format and timezone from String input types.
-
$util.time.parseFormattedToEpochMilliSeconds(String, String) : Long
-
Parses a timestamp passed as a String, along with a format, and return the timestamp as milliseconds since epoch.
-
$util.time.parseFormattedToEpochMilliSeconds(String, String, String) : Long
-
Parses a timestamp passed as a String, along with a format and time zone, and return the timestamp as milliseconds since epoch.
-
$util.time.parseISO8601ToEpochMilliSeconds(String) : Long
-
Parses an ISO8601 timestamp, passed as a String, and return the timestamp as milliseconds since epoch.
-
$util.time.epochMilliSecondsToSeconds(long) : long
-
Converts an epoch milliseconds timestamp to an epoch seconds timestamp.
-
$util.time.epochMilliSecondsToISO8601(long) : String
-
Converts a epoch milliseconds timestamp to an ISO8601 timestamp.
-
$util.time.epochMilliSecondsToFormatted(long, String) : String
-
Converts a epoch milliseconds timestamp, passed as long, to a timestamp formatted according to the supplied format in UTC.
-
$util.time.epochMilliSecondsToFormatted(long, String, String) : String
-
Converts a epoch milliseconds timestamp, passed as a long, to a timestamp formatted according to the supplied format in the supplied timezone.
List helpers in $util.list
$util.list
contains methods to help with common List operations, such as
removing or retaining items from a list for filtering use cases.
-
$util.list.copyAndRetainAll(List, List) : List
-
Makes a shallow copy of the supplied list in the first argument, retaining only the items specified in the second argument, if they are present. All other items will be removed from the copy.
-
$util.list.copyAndRemoveAll(List, List) : List
-
Makes a shallow copy of the supplied list in the first argument, removing any items where the item is specified in the second argument, if they are present. All other items will be retained in the copy.
-
$util.list.sortList(List, Boolean, String) : List
-
Sorts a list of objects, which is provided in the first argument. If the second argument is true, the list is sorted in a descending manner; if the second argument is false, the list is sorted in an ascending manner. The third argument is the string name of the property used to sort a list of custom objects. If it's a list of just Strings, Integers, Floats, or Doubles, the third argument can be any random string. If all of the objects are not from the same class, the original list is returned. Only lists containing a maximum of 1000 objects are supported. The following is an example of this utility's usage:
INPUT: $util.list.sortList([{"description":"youngest", "age":5},{"description":"middle", "age":45}, {"description":"oldest", "age":85}], false, "description") OUTPUT: [{"description":"middle", "age":45}, {"description":"oldest", "age":85}, {"description":"youngest", "age":5}]
Map helpers in $util.map
$util.map
contains methods to help with common Map operations, such as
removing or retaining items from a Map for filtering use cases.
-
$util.map.copyAndRetainAllKeys(Map, List) : Map
-
Makes a shallow copy of the first map, retaining only the keys specified in the list, if they are present. All other keys will be removed from the copy.
-
$util.map.copyAndRemoveAllKeys(Map, List) : Map
-
Makes a shallow copy of the first map, removing any entries where the key is specified in the list, if they are present. All other keys will be retained in the copy.
DynamoDB helpers in $util.dynamodb
$util.dynamodb
contains helper methods that make it easier to write and read
data to Amazon DynamoDB, such as automatic type mapping and formatting. These methods
are
designed to make mapping primitive types and Lists to the proper DynamoDB input format
automatically, which is a Map
of the format { "TYPE" : VALUE
}
.
For example, previously, a request mapping template to create a new item in DynamoDB might have looked like this:
{ "version" : "2017-02-28", "operation" : "PutItem", "key": { "id" : { "S" : "$util.autoId()" } }, "attributeValues" : { "title" : { "S" : $util.toJson($ctx.args.title) }, "author" : { "S" : $util.toJson($ctx.args.author) }, "version" : { "N", $util.toJson($ctx.args.version) } } }
If we wanted to add fields to the object we would have to update the GraphQL query in the schema, as well as the request mapping template. However, we can now restructure our request mapping template so it automatically picks up new fields added in our schema and adds them to DynamoDB with the correct types:
{ "version" : "2017-02-28", "operation" : "PutItem", "key": { "id" : $util.dynamodb.toDynamoDBJson($util.autoId()) }, "attributeValues" : $util.dynamodb.toMapValuesJson($ctx.args) }
In the previous example, we are using the
$util.dynamodb.toDynamoDBJson(...)
helper to automatically take the
generated id and convert it to the DynamoDB representation of a string attribute.
We then take
all the arguments and convert them to their DynamoDB representations and output them
to the
attributeValues
field in the template.
Each helper has two versions: a version that returns an object (for example,
$util.dynamodb.toString(...)
), and a version that returns the object as a
JSON string (for example, $util.dynamodb.toStringJson(...)
). In the previous
example, we used the version that returns the data as a JSON string. If you want to
manipulate the object before it’s used in the template, you can choose to return an
object
instead, as shown following:
{ "version" : "2017-02-28", "operation" : "PutItem", "key": { "id" : $util.dynamodb.toDynamoDBJson($util.autoId()) }, #set( $myFoo = $util.dynamodb.toMapValues($ctx.args) ) #set( $myFoo.version = $util.dynamodb.toNumber(1) ) #set( $myFoo.timestamp = $util.dynamodb.toString($util.time.nowISO8601())) "attributeValues" : $util.toJson($myFoo) }
In the previous example, we are returning the converted arguments as a map instead
of a
JSON string, and are then adding the version
and timestamp
fields
before finally outputting them to the attributeValues
field in the template
using $util.toJson(...)
.
The JSON version of each of the helpers is equivalent to wrapping the non-JSON version
in $util.toJson(...)
. For example, the following statements are exactly the
same:
$util.toStringJson("Hello, World!") $util.toJson($util.toString("Hello, World!"))
-
$util.dynamodb.toDynamoDB(Object) : Map
-
General object conversion tool for DynamoDB that converts input objects to the appropriate DynamoDB representation. It’s opinionated about how it represents some types: e.g., it will use lists (“L”) rather than sets (“SS”, “NS”, “BS”). This returns an object that describes the DynamoDB attribute value.
String example:
Input: $util.dynamodb.toDynamoDB("foo") Output: { "S" : "foo" }
Number example:
Input: $util.dynamodb.toDynamoDB(12345) Output: { "N" : 12345 }
Boolean example:
Input: $util.dynamodb.toDynamoDB(true) Output: { "BOOL" : true }
List example:
Input: $util.dynamodb.toDynamoDB([ "foo", 123, { "bar" : "baz" } ]) Output: { "L" : [ { "S" : "foo" }, { "N" : 123 }, { "M" : { "bar" : { "S" : "baz" } } } ] }
Map example:
Input: $util.dynamodb.toDynamoDB({ "foo": "bar", "baz" : 1234, "beep": [ "boop"] }) Output: { "M" : { "foo" : { "S" : "bar" }, "baz" : { "N" : 1234 }, "beep" : { "L" : [ { "S" : "boop" } ] } } }
-
$util.dynamodb.toDynamoDBJson(Object) : String
-
The same as
$util.dynamodb.toDynamoDB(Object) : Map
, but returns the DynamoDB attribute value as a JSON encoded string. -
$util.dynamodb.toString(String) : String
-
Convert an input string to the DynamoDB string format. This returns an object that describes the DynamoDB attribute value.
Input: $util.dynamodb.toString("foo") Output: { "S" : "foo" }
-
$util.dynamodb.toStringJson(String) : Map
-
The same as
$util.dynamodb.toString(String) : String
, but returns the DynamoDB attribute value as a JSON encoded string. -
$util.dynamodb.toStringSet(List<String>) : Map
-
Converts a lists with Strings to the DynamoDB string set format. This returns an object that describes the DynamoDB attribute value.
Input: $util.dynamodb.toStringSet([ "foo", "bar", "baz" ]) Output: { "SS" : [ "foo", "bar", "baz" ] }
-
$util.dynamodb.toStringSetJson(List<String>) : String
-
The same as
$util.dynamodb.toStringSet(List<String>) : Map
, but returns the DynamoDB attribute value as a JSON encoded string. -
$util.dynamodb.toNumber(Number) : Map
-
Converts a number to the DynamoDB number format. This returns an object that describes the DynamoDB attribute value.
Input: $util.dynamodb.toNumber(12345) Output: { "N" : 12345 }
-
$util.dynamodb.toNumberJson(Number) : String
-
The same as
$util.dynamodb.toNumber(Number) : Map
, but returns the DynamoDB attribute value as a JSON encoded string. -
$util.dynamodb.toNumberSet(List<Number>) : Map
-
Converts a list of numbers to the DynamoDB number set format. This returns an object that describes the DynamoDB attribute value.
Input: $util.dynamodb.toNumberSet([ 1, 23, 4.56 ]) Output: { "NS" : [ 1, 23, 4.56 ] }
-
$util.dynamodb.toNumberSetJson(List<Number>) : String
-
The same as
$util.dynamodb.toNumberSet(List<Number>) : Map
, but returns the DynamoDB attribute value as a JSON encoded string. -
$util.dynamodb.toBinary(String) : Map
-
Converts binary data encoded as a base64 string to DynamoDB binary format. This returns an object that describes the DynamoDB attribute value.
Input: $util.dynamodb.toBinary("foo") Output: { "B" : "foo" }
-
$util.dynamodb.toBinaryJson(String) : String
-
The same as
$util.dynamodb.toBinary(String) : Map
, but returns the DynamoDB attribute value as a JSON encoded string. -
$util.dynamodb.toBinarySet(List<String>) : Map
-
Converts a list of binary data encoded as base64 strings to DynamoDB binary set format. This returns an object that describes the DynamoDB attribute value.
Input: $util.dynamodb.toBinarySet([ "foo", "bar", "baz" ]) Output: { "BS" : [ "foo", "bar", "baz" ] }
-
$util.dynamodb.toBinarySetJson(List<String>) : String
-
The same as
$util.dynamodb.toBinarySet(List<String>) : Map
, but returns the DynamoDB attribute value as a JSON encoded string. -
$util.dynamodb.toBoolean(boolean) : Map
-
Converts a boolean to the appropriate DynamoDB boolean format. This returns an object that describes the DynamoDB attribute value.
Input: $util.dynamodb.toBoolean(true) Output: { "BOOL" : true }
-
$util.dynamodb.toBooleanJson(boolean) : String
-
The same as
$util.dynamodb.toBoolean(boolean) : Map
, but returns the DynamoDB attribute value as a JSON encoded string. -
$util.dynamodb.toNull() : Map
-
Returns a null in DynamoDB null format. This returns an object that describes the DynamoDB attribute value.
Input: $util.dynamodb.toNull() Output: { "NULL" : null }
-
$util.dynamodb.toNullJson() : String
-
The same as
$util.dynamodb.toNull() : Map
, but returns the DynamoDB attribute value as a JSON encoded string. -
$util.dynamodb.toList(List) : Map
-
Converts a list of object to DynamoDB list format. Each item in the list is also converted to its appropriate DynamoDB format. It’s opinionated about how it represents some of the nested objects: e.g., it will use lists (“L”) rather than sets (“SS”, “NS”, “BS”). This returns an object that describes the DynamoDB attribute value.
Input: $util.dynamodb.toList([ "foo", 123, { "bar" : "baz" } ]) Output: { "L" : [ { "S" : "foo" }, { "N" : 123 }, { "M" : { "bar" : { "S" : "baz" } } } ] }
-
$util.dynamodb.toListJson(List) : String
-
The same as
$util.dynamodb.toList(List) : Map
, but returns the DynamoDB attribute value as a JSON encoded string. -
$util.dynamodb.toMap(Map) : Map
-
Converts a map to DynamoDB map format. Each value in the map is also converted to its appropriate DynamoDB format. It’s opinionated about how it represents some of the nested objects: e.g., it will use lists (“L”) rather than sets (“SS”, “NS”, “BS”). This returns an object that describes the DynamoDB attribute value.
Input: $util.dynamodb.toMap({ "foo": "bar", "baz" : 1234, "beep": [ "boop"] }) Output: { "M" : { "foo" : { "S" : "bar" }, "baz" : { "N" : 1234 }, "beep" : { "L" : [ { "S" : "boop" } ] } } }
-
$util.dynamodb.toMapJson(Map) : String
-
The same as
$util.dynamodb.toMap(Map) : Map
, but returns the DynamoDB attribute value as a JSON encoded string. -
$util.dynamodb.toMapValues(Map) : Map
-
Creates a copy of the map where each value has been converted to its appropriate DynamoDB format. It’s opinionated about how it represents some of the nested objects: e.g., it will use lists (“L”) rather than sets (“SS”, “NS”, “BS”).
Input: $util.dynamodb.toMapValues({ "foo": "bar", "baz" : 1234, "beep": [ "boop"] }) Output: { "foo" : { "S" : "bar" }, "baz" : { "N" : 1234 }, "beep" : { "L" : [ { "S" : "boop" } ] } }
Note: this is slightly different to
$util.dynamodb.toMap(Map) : Map
as it returns only the contents of the DynamoDB attribute value, but not the whole attribute value itself. For example, the following statements are exactly the same:$util.dynamodb.toMapValues($map) $util.dynamodb.toMap($map).get("M")
-
$util.dynamodb.toMapValuesJson(Map) : String
-
The same as
$util.dynamodb.toMapValues(Map) : Map
, but returns the DynamoDB attribute value as a JSON encoded string. -
$util.dynamodb.toS3Object(String key, String bucket, String region) : Map
-
Converts the key, bucket and region into the DynamoDB S3 Object representation. This returns an object that describes the DynamoDB attribute value.
Input: $util.dynamodb.toS3Object("foo", "bar", region = "baz") Output: { "S" : "{ \"s3\" : { \"key\" : \"foo", \"bucket\" : \"bar", \"region\" : \"baz" } }" }
-
$util.dynamodb.toS3ObjectJson(String key, String bucket, String region) : String
-
The same as
$util.dynamodb.toS3Object(String key, String bucket, String region) : Map
, but returns the DynamoDB attribute value as a JSON encoded string. -
$util.dynamodb.toS3Object(String key, String bucket, String region, String version) : Map
-
Converts the key, bucket, region and optional version into the DynamoDB S3 Object representation. This returns an object that describes the DynamoDB attribute value.
Input: $util.dynamodb.toS3Object("foo", "bar", "baz", "beep") Output: { "S" : "{ \"s3\" : { \"key\" : \"foo\", \"bucket\" : \"bar\", \"region\" : \"baz\", \"version\" = \"beep\" } }" }
-
$util.dynamodb.toS3ObjectJson(String key, String bucket, String region, String version) : String
-
The same as
$util.dynamodb.toS3Object(String key, String bucket, String region, String version) : Map
, but returns the DynamoDB attribute value as a JSON encoded string. -
$util.dynamodb.fromS3ObjectJson(String) : Map
-
Accepts the string value of a DynamoDB S3 Object and returns a map that contains the key, bucket, region and optional version.
Input: $util.dynamodb.fromS3ObjectJson({ "S" : "{ \"s3\" : { \"key\" : \"foo\", \"bucket\" : \"bar\", \"region\" : \"baz\", \"version\" = \"beep\" } }" }) Output: { "key" : "foo", "bucket" : "bar", "region" : "baz", "version" : "beep" }
RDS helpers in $util.rds
$util.rds.toJsonString(String serializedSQLResult): String
Returns a String
by transforming the stringified raw RDS Data API result format to a more concise string. The
returning string is a serialized list of lists of SQL records of the result set. Every
record is represented as a collection of key-value pairs. The keys are the corresponding
column names.
An empty list is returned if the corresponding statement in the input was a SQL query
that would cause a mutation (for example INSERT, UPDATE, DELETE). For example, the
query
select * from Books limit 2
provides the raw result from the RDS Data
API:
{ "sqlStatementResults": [ { "numberOfRecordsUpdated": 0, "records": [ [ { "stringValue": "Mark Twain" }, { "stringValue": "Adventures of Huckleberry Finn" }, { "stringValue": "978-1948132817" } ], [ { "stringValue": "Jack London" }, { "stringValue": "The Call of the Wild" }, { "stringValue": "978-1948132275" } ] ], "columnMetadata": [ { "isSigned": false, "isCurrency": false, "label": "author", "precision": 200, "typeName": "VARCHAR", "scale": 0, "isAutoIncrement": false, "isCaseSensitive": false, "schemaName": "", "tableName": "Books", "type": 12, "nullable": 0, "arrayBaseColumnType": 0, "name": "author" }, { "isSigned": false, "isCurrency": false, "label": "title", "precision": 200, "typeName": "VARCHAR", "scale": 0, "isAutoIncrement": false, "isCaseSensitive": false, "schemaName": "", "tableName": "Books", "type": 12, "nullable": 0, "arrayBaseColumnType": 0, "name": "title" }, { "isSigned": false, "isCurrency": false, "label": "ISBN-13", "precision": 15, "typeName": "VARCHAR", "scale": 0, "isAutoIncrement": false, "isCaseSensitive": false, "schemaName": "", "tableName": "Books", "type": 12, "nullable": 0, "arrayBaseColumnType": 0, "name": "ISBN-13" } ] } ] }
The util.rds.toJsonString
will be:
[ { "author": "Mark Twain", "title": "Adventures of Huckleberry Finn", "ISBN-13": "978-1948132817" }, { "author": "Jack London", "title": "The Call of the Wild", "ISBN-13": "978-1948132275" }, ]
$util.rds.toJsonObject(String serializedSQLResult): Object
Same as util.rds.toJsonString
but with the result to be a JSON
Object
.
HTTP helpers in $util.http
$util.http
contains helper methods that make it easier to deal with http
request parameters.
-
$util.http.copyHeaders(Map) : Map
-
Copies the header from the map without the restricted set of HTTP header. This is useful for forwarding Request headers to your downstream HTTP endpoint.
{ ... "params": { ... "headers": $util.http.copyHeaders($ctx.request.headers), ... }, ... }
XML helpers in $util.xml
$util.xml
contains helper methods that make it easier to translate XML
responses to JSON or a Dictionary.
$util.xml.toMap(String) : Map
Converts an XML String to a Dictionary.
Input: <?xml version="1.0" encoding="UTF-8"?> <posts> <post> <id>1</id> <title>Getting Started with GraphQL</title> </post> </posts> Output (JSON representation): { "posts":{ "post":{ "id":1, "title":"Getting Started with GraphQL" } } } Input: <?xml version="1.0" encoding="UTF-8"?> <posts> <post> <id>1</id> <title>Getting Started with GraphQL</title> </post> <post> <id>2</id> <title>Getting Started with AWS AppSync</title> </post> </posts> Output (JSON representation): { "posts":{ "post":[ { "id":1, "title":"Getting Started with GraphQL" }, { "id":2, "title":"Getting Started with AWS AppSync" } ] } }
$util.xml.toJsonString(String) : String
Converts an XML string to a JSON string. This is similar to toMap except that the output is a string. This is useful if you want to directly convert and return the XML response from an HTTP object to JSON.
$util.xml.toJsonString(String, boolean) : String
Converts an XML string to a JSON string with an optional boolean parameter to determine if you want to string encode the JSON.
Transformation helpers in $util.transform
$util.transform
contains helper methods that make it easier to perform complex
operations against data sources, such as Amazon DynamoDB filter operations.
$util.transform.toDynamoDBFilterExpression(Map) : Map
Converts an input string to a filter expression for use with Amazon DynamoDB.
Input: $util.transform.toDynamoDBFilterExpression({ "title":{ "contains":"Hello World" } }) Output: { "expression" : "contains(#title, :title_contains)" "expressionNames" : { "#title" : "title", }, "expressionValues" : { ":title_contains" : { "S" : "Hello World" } }, }
$util.transform.toElasticsearchQueryDSL(Map) : Map
Converts the given input into its equivalent Elasticsearch Query DSL expression, returning it as a JSON string.
Input: $util.transform.toElasticsearchQueryDSL({ "upvotes":{ "ne":15, "range":[ 10, 20 ] }, "title":{ "eq":"hihihi", "wildcard":"h*i" } }) Output: { "bool":{ "must":[ { "bool":{ "must":[ { "bool":{ "must_not":{ "term":{ "upvotes":15 } } } }, { "range":{ "upvotes":{ "gte":10, "lte":20 } } } ] } }, { "bool":{ "must":[ { "term":{ "title":"hihihi" } }, { "wildcard":{ "title":"h*i" } } ] } } ] } }
The default Operator is assumed to be AND.
Math helpers in $util.math
$util.math
contains methods to help with common Math operations.
-
$util.math.roundNum(Double) : Integer
-
Takes a double and rounds it to the nearest integer.
-
$util.math.minVal(Double, Double) : Double
-
Takes two doubles and returns the minimum value between the two doubles.
-
$util.math.maxVal(Double, Double) : Double
-
Takes two doubles and returns the maximum value between the two doubles.
-
$util.math.randomDouble() : Double
-
Returns a random double between 0 and 1.
Important This function shouldn’t be used for anything that needs high entropy randomness (for example, cryptography).
-
$util.math.randomWithinRange(Integer, Integer) : Integer
-
Returns a random integer value within the specified range, with the first argument specifying the lower value of the range and the second argument specifying the upper value of the range.
Important This function shouldn’t be used for anything that needs high entropy randomness (for example, cryptography).
String helpers in $util.str
$util.str
contains methods to help with common String operations.
-
$util.str.toUpper(String) : String
-
Takes a string and converts it to be entirely uppercase.
-
$util.str.toLower(String) : String
-
Takes a string and converts it to be entirely lowercase.
-
$util.str.toReplace(String, String, String) : String
-
Replaces a substring within a string with another string. The first argument specifies the string on which to perform the replacement operation. The second argument specifies the substring to replace. The third argument specifies the string to replace the second argument with. The following is an example of this utility's usage:
INPUT: $util.str.toReplace("hello world", "hello", "mellow") OUTPUT: "mellow world"
-
$util.str.normalize(String, String) : String
-
Normalizes a string using one of the four unicode normalization forms: NFC, NFD, NFKC, or NFKD. The first argument is the string to normalize. The second argument is either "nfc", "nfd", "nfkc", or "nfkd" specifying the normalization type to use for the normalization process.