

# AWS AppSync resolver mapping template utility reference
<a name="resolver-util-reference"></a>

**Note**  
We now primarily support the APPSYNC\$1JS runtime and its documentation. Please consider using the APPSYNC\$1JS runtime and its guides [here](https://docs.aws.amazon.com/appsync/latest/devguide/resolver-reference-js-version.html).

AWS AppSync defines a set of utilities that you can use within a GraphQL resolver to simplify interactions with data sources. Some of these utilities are for general use with any data source, such as generating IDs or timestamps. Others are specific to a type of data source. The following utilities are available:
+  [ Utility helpers in \$1util ](https://docs.aws.amazon.com/appsync/latest/devguide/utility-helpers-in-util.html) - The \$1util variable contains general utility methods to help you work with data. Unless otherwise specified, all utilities use the UTF-8 character set.
+ [ AppSync directives](https://docs.aws.amazon.com/appsync/latest/devguide/aws-appsync-directives.html) - AppSync exposes directives to facilitate developer productivity when writing in VTL.
+  [ Time helpers in \$1util.time ](https://docs.aws.amazon.com/appsync/latest/devguide/time-helpers-in-util-time.html) - The \$1util.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](https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html), which you can reference for further documentation.
+ [ List helpers in \$1util.list ](https://docs.aws.amazon.com/appsync/latest/devguide/list-helpers-in-util-list.html) - \$1util.list contains methods to help with common List operations such as removing or retaining items from a list for filtering use cases.
+  [ Map helpers in \$1util.map ](https://docs.aws.amazon.com/appsync/latest/devguide/utility-helpers-in-map.html) - \$1util.map contains methods to help with common Map operations such as removing or retaining items from a Map for filtering use cases.
+  [ DynamoDB helpers in \$1util.dynamodb ](https://docs.aws.amazon.com/appsync/latest/devguide/dynamodb-helpers-in-util-dynamodb.html) - \$1util.dynamodb contains helper methods that make it easier to write and read data to Amazon DynamoDB, such as automatic type mapping and formatting. 
+  [ Amazon RDS helpers in \$1util.rds ](https://docs.aws.amazon.com/appsync/latest/devguide/rds-helpers-in-util-rds.html) - \$1util.rds contains helper methods that format RDS operations by getting rid of extraneous data in result outputs.
+  [ HTTP helpers in \$1util.http ](https://docs.aws.amazon.com/appsync/latest/devguide/http-helpers-in-utils-http.html) - The \$1util.http utility provides helper methods that you can use to manage HTTP request parameters and to add response headers.
+  [ XML helpers in \$1util.xml ](https://docs.aws.amazon.com/appsync/latest/devguide/xml-helpers-in-utils-xml.html) - \$1util.xml contains helper methods that can make it easier to translate XML responses to JSON or a Dictionary.
+  [ Transformation helpers in \$1util.transform ](https://docs.aws.amazon.com/appsync/latest/devguide/transformation-helpers-in-utils-transform.html) - \$1util.transform contains helper methods that make it easier to perform complex operations against data sources, such as DynamoDB filter operations.
+  [ Math helpers in \$1util.math ](https://docs.aws.amazon.com/appsync/latest/devguide/math-helpers-in-util-math.html) - \$1util.math contains methods to help with common Math operations.
+  [ String helpers in \$1util.str ](https://docs.aws.amazon.com/appsync/latest/devguide/str-helpers-in-util-str.html) - \$1util.str contains methods to help with common String operations.
+  [ Extensions ](https://docs.aws.amazon.com/appsync/latest/devguide/extensions.html) - \$1extensions contains a set of methods to make additional actions within your resolvers.

# Utility helpers in \$1util
<a name="utility-helpers-in-util"></a>

**Note**  
We now primarily support the APPSYNC\$1JS runtime and its documentation. Please consider using the APPSYNC\$1JS runtime and its guides [here](https://docs.aws.amazon.com/appsync/latest/devguide/resolver-reference-js-version.html).

The `$util` variable contains general utility methods to help you work with data. Unless otherwise specified, all utilities use the UTF-8 character set.

## JSON parsing utils
<a name="utility-helpers-in-json-parsing"></a>

### JSON parsing utils list
<a name="utility-helpers-in-json-parsing-list"></a>

** **`$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.

## Encoding utils
<a name="utility-helpers-in-encoding"></a>

### Encoding utils list
<a name="utility-helpers-in-encoding-list"></a>

** **`$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.

## ID generation utils
<a name="utility-helpers-in-id-gen"></a>

### ID generation utils list
<a name="utility-helpers-in-id-gen-list"></a>

** **`$util.autoId() : String`** **  
Returns a 128-bit randomly generated UUID.

****`$util.autoUlid() : String`****  
Returns a 128-bit randomly generated ULID (Universally Unique Lexicographically Sortable Identifier).

****`$util.autoKsuid() : String`****  
Returns a 128-bit randomly generated KSUID (K-Sortable Unique Identifier) base62 encoded as a String with a length of 27.

## Error utils
<a name="utility-helpers-in-error"></a>

### Error utils list
<a name="utility-helpers-in-error-list"></a>

** `$util.error(String)` **  
Throws a custom error. Use this in request or response mapping templates to detect an error with the request or with the invocation result.

** `$util.error(String, String)` **  
Throws a custom error. Use this in request or response mapping templates to detect an error with the request or with the invocation result. You can also specify an `errorType`.

** `$util.error(String, String, Object)` **  
Throws a custom error. Use this in request or response mapping templates to detect an error with the request or with the invocation result. You can also specify an `errorType` and a `data` field. The `data` value will be added to the corresponding `error` block inside `errors` in the GraphQL response.  
`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, a `data` field, and an `errorInfo` field can be specified. The `data` value will be added to the corresponding `error` block inside `errors` in the GraphQL response.   
`data` will be filtered based on the query selection set. The `errorInfo` value will be added to the corresponding `error` block inside `errors` in the GraphQL response.  
`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 a `data` 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. The `data` value will be added to the corresponding `error` block inside `errors` in the GraphQL response.   
`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, a `data` field, and an `errorInfo` 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. The `data` value will be added to the corresponding `error` block inside `errors` in the GraphQL response.  
`data` will be filtered based on the query selection set. The `errorInfo` value will be added to the corresponding `error` block inside `errors` in the GraphQL response.  
`errorInfo` will **NOT** be filtered based on the query selection set.

## Condition validation utils
<a name="utility-helpers-in-condition"></a>

### Condition validation utils list
<a name="utility-helpers-in-condition-list"></a>

** `$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.

## Null behavior utils
<a name="utility-helpers-in-null-behavior"></a>

### Null behavior utils list
<a name="utility-helpers-in-null-behavior-list"></a>

** `$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".

## Pattern matching utils
<a name="utility-helpers-in-pattern-matching"></a>

### Type and pattern matching utils list
<a name="utility-helpers-in-type-pattern-matching-list"></a>

** `$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](https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html), 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".

## Object validation utils
<a name="utility-helpers-in-object-validation"></a>

### Object validation utils list
<a name="utility-helpers-in-object-validation-list"></a>

** `$util.isString(Object) : Boolean` **  
Returns true if the Object is a String.

** `$util.isNumber(Object) : Boolean` **  
Returns true if the Object is a Number.

** `$util.isBoolean(Object) : Boolean` **  
Returns true if the Object is a Boolean.

** `$util.isList(Object) : Boolean` **  
Returns true if the Object is a List.

** `$util.isMap(Object) : Boolean` **  
Returns true if the Object is a Map.

## CloudWatch logging utils
<a name="utility-helpers-in-logging"></a>

### CloudWatch logging utils list
<a name="utility-helpers-in-cloudwatch-logs"></a>

**`$util.log.info(Object) : Void`**  
Logs the String representation of the provided Object to the requested log stream when request-level and field-level CloudWatch logging is enabled with log level `ALL`, `INFO`, or `DEBUG` on an API.

**`$util.log.info(String, Object...) : Void`**  
Logs the String representation of the provided Objects to the requested log stream when request-level and field-level CloudWatch logging is enabled with log level `ALL` on an API. This utility will replace all variables indicated by "\$1\$1" in the first input format String with the String representation of the provided Objects in order.

**`$util.log.debug(Object) : Void`**  
Logs the String representation of the provided Object to the requested log stream when request-level and field-level CloudWatch logging is enabled with log level `ALL` or `DEBUG` on an API.

**`$util.log.debug(String, Object...) : Void`**  
Logs the String representation of the provided Objects to the requested log stream when field-level CloudWatch logging is enabled with log level `DEBUG` or log level `ALL` on an API. This utility will replace all variables indicated by "\$1\$1" in the first input format String with the String representation of the provided Objects in order.

**`$util.log.error(Object) : Void`**  
Logs the String representation of the provided Object to the requested log stream when field-level CloudWatch logging is enabled with **any** log level (`ALL`, `INFO`, `DEBUG`, etc.) on an API.

**`$util.log.error(String, Object...) : Void`**  
Logs the String representation of the provided Objects to the requested log stream when field-level CloudWatch logging is enabled with log level `ERROR` or log level `ALL` on an API. This utility will replace all variables indicated by "\$1\$1" in the first input format String with the String representation of the provided Objects in order.

## Return value behavior utils
<a name="utility-helpers-in-return-behavior"></a>

### Return value behavior utils list
<a name="utility-helpers-in-behavior-list"></a>

****`$util.qr()`** and `$util.quiet()` **  
Runs a VTL statement while suppressing the returned value. This is useful for running methods without using temporary placeholders, such as adding items to a map. 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 JavaScript 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.autoUlid() : String`****  
Returns a 128-bit randomly generated ULID (Universally Unique Lexicographically Sortable Identifier).  
****`$util.autoKsuid() : String`****  
Returns a 128-bit randomly generated KSUID (K-Sortable Unique Identifier) base62 encoded as a String with a length of 27.  
** `$util.unauthorized()` **  
Throws `Unauthorized` for the field being resolved. Use this in request or response mapping templates to determine whether to allow the caller to resolve the field.  
** `$util.error(String)` **  
Throws a custom error. Use this in request or response mapping templates to detect an error with the request or with the invocation result.  
** `$util.error(String, String)` **  
Throws a custom error. Use this in request or response mapping templates to detect an error with the request or with the invocation result. You can also specify an `errorType`.  
** `$util.error(String, String, Object)` **  
Throws a custom error. Use this in request or response mapping templates to detect an error with the request or with the invocation result. You can also specify an `errorType` and a `data` field. The `data` value will be added to the corresponding `error` block inside `errors` 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, a `data` field, and a `errorInfo` field can be specified. The `data` value will be added to the corresponding `error` block inside `errors` in the GraphQL response. **Note**: `data` will be filtered based on the query selection set. The `errorInfo` value will be added to the corresponding `error` block inside `errors` 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 a `data` 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. The `data` value will be added to the corresponding `error` block inside `errors` 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, a `data` field, and a `errorInfo` 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. The `data` value will be added to the corresponding `error` block inside `errors` in the GraphQL response. **Note**: `data` will be filtered based on the query selection set. The `errorInfo` value will be added to the corresponding `error` block inside `errors` 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](https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html), 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".  
****`$util.log.info(Object) : Void`****  
Logs the String representation of the provided Object to the requested log stream when request-level and field-level CloudWatch logging is enabled with log level `ALL` on an API.  
****`$util.log.info(String, Object...) : Void`****  
Logs the String representation of the provided Objects to the requested log stream when request-level and field-level CloudWatch logging is enabled with log level `ALL` on an API. This utility will replace all variables indicated by "\$1\$1" in the first input format String with the String representation of the provided Objects in order.  
****`$util.log.error(Object) : Void`****  
Logs the String representation of the provided Object to the requested log stream when field-level CloudWatch logging is enabled with log level `ERROR` or log level `ALL` on an API.  
****`$util.log.error(String, Object...) : Void`****  
Logs the String representation of the provided Objects to the requested log stream when field-level CloudWatch logging is enabled with log level `ERROR` or log level `ALL` on an API. This utility will replace all variables indicated by "\$1\$1" in the first input format String with the String representation of the provided Objects in order.

** `$util.escapeJavaScript(String) : String` **  
Returns the input string as a JavaScript escaped string.

## Resolver authorization
<a name="utility-helpers-in-resolver-auth"></a>

### Resolver authorization list
<a name="utility-helpers-in-resolver-auth-list"></a>

** `$util.unauthorized()` **  
Throws `Unauthorized` for the field being resolved. Use this in request or response mapping templates to determine whether to allow the caller to resolve the field.

# AWS AppSync directives
<a name="aws-appsync-directives"></a>

**Note**  
We now primarily support the APPSYNC\$1JS runtime and its documentation. Please consider using the APPSYNC\$1JS runtime and its guides [here](https://docs.aws.amazon.com/appsync/latest/devguide/resolver-reference-js-version.html).

AWS AppSync exposes directives to facilitate developer productivity when writing in VTL.

## Directive utils
<a name="utility-helpers-in-directives"></a>

****`#return(Object)`****  
The `#return(Object)` allows you to prematurely return from any mapping template. `#return(Object)` is analogous to the *return* keyword in programming languages, as it will return from the closest scoped block of logic. Using `#return(Object)` inside of a resolver mapping template will return from the resolver. Additionally, using `#return(Object)` from a function mapping template will return from the function and will continue the run to either the next function in the pipeline or the resolver response mapping template.

****`#return`****  
The `#return` directive exhibits the same behaviors as `#return(Object)`, but `null` will be returned instead.

# Time helpers in \$1util.time
<a name="time-helpers-in-util-time"></a>

**Note**  
We now primarily support the APPSYNC\$1JS runtime and its documentation. Please consider using the APPSYNC\$1JS runtime and its guides [here](https://docs.aws.amazon.com/appsync/latest/devguide/resolver-reference-js-version.html).

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](https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html) which you can reference for further documentation. We provide some examples below, as well as a list of available methods and descriptions.

## Time utils
<a name="utility-helpers-in-time"></a>

### Time utils list
<a name="utility-helpers-in-time-list"></a>

** `$util.time.nowISO8601() : String` **  
Returns a String representation of UTC in [ISO8601 format](https://en.wikipedia.org/wiki/ISO_8601).

** `$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 containing a time zone, then returns 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, then returns the timestamp as milliseconds since epoch.

** `$util.time.parseISO8601ToEpochMilliSeconds(String) : Long` **  
Parses an ISO8601 timestamp passed as a String, then returns 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 an epoch milliseconds timestamp to an ISO8601 timestamp.

** `$util.time.epochMilliSecondsToFormatted(long, String) : String` **  
Converts an 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 an epoch milliseconds timestamp, passed as a long, to a timestamp formatted according to the supplied format in the supplied timezone.

## Standalone function examples
<a name="standalone-function-examples"></a>

```
$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
<a name="conversion-examples"></a>

```
#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
<a name="parsing-examples"></a>

```
$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 AppSync defined scalars
<a name="usage-with-aws-scalars"></a>

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
```

# List helpers in \$1util.list
<a name="list-helpers-in-util-list"></a>

**Note**  
We now primarily support the APPSYNC\$1JS runtime and its documentation. Please consider using the APPSYNC\$1JS runtime and its guides [here](https://docs.aws.amazon.com/appsync/latest/devguide/resolver-reference-js-version.html).

`$util.list` contains methods to help with common List operations such as removing or retaining items from a list for filtering use cases.

## List utils
<a name="utility-helpers-in-list-utils"></a>

** `$util.list.copyAndRetainAll(List, List) : List` **  
Makes a shallow copy of the supplied list in the first argument while 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 while 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 \$1util.map
<a name="utility-helpers-in-map"></a>

**Note**  
We now primarily support the APPSYNC\$1JS runtime and its documentation. Please consider using the APPSYNC\$1JS runtime and its guides [here](https://docs.aws.amazon.com/appsync/latest/devguide/resolver-reference-js-version.html).

 `$util.map` contains methods to help with common Map operations such as removing or retaining items from a Map for filtering use cases.

## Map utils
<a name="utility-helpers-in-map-list"></a>

** `$util.map.copyAndRetainAllKeys(Map, List) : Map` **  
Makes a shallow copy of the first map while 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 while 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 \$1util.dynamodb
<a name="dynamodb-helpers-in-util-dynamodb"></a>

**Note**  
We now primarily support the APPSYNC\$1JS runtime and its documentation. Please consider using the APPSYNC\$1JS runtime and its guides [here](https://docs.aws.amazon.com/appsync/latest/devguide/resolver-reference-js-version.html).

`$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!"))
```

## toDynamoDB
<a name="utility-helpers-in-toDynamoDB"></a>

### toDynamoDB utils list
<a name="utility-helpers-in-toDynamoDB-list"></a>

** `$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.

## toString utils
<a name="utility-helpers-in-toString"></a>

### toString utils list
<a name="utility-helpers-in-toString-list"></a>

****`$util.dynamodb.toString(String) : String`** **  
Converts 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 list 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.

## toNumber utils
<a name="utility-helpers-in-toNumber"></a>

### toNumber utils list
<a name="utility-helpers-in-toNumber-list"></a>

** `$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.

## toBinary utils
<a name="utility-helpers-in-toBinary"></a>

### toBinary utils list
<a name="utility-helpers-in-toBinary-list"></a>

** `$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.

## toBoolean utils
<a name="utility-helpers-in-toBoolean"></a>

### toBoolean utils list
<a name="utility-helpers-in-toBoolean-list"></a>

** `$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.

## toNull utils
<a name="utility-helpers-in-toNull"></a>

### toNull utils list
<a name="utility-helpers-in-toNull-list"></a>

** `$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.

## toList utils
<a name="utility-helpers-in-toList"></a>

### toList utils list
<a name="utility-helpers-in-toList-list"></a>

****`$util.dynamodb.toList(List) : Map`** **  
Converts a list of objects to the 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.

## toMap utils
<a name="utility-helpers-in-toMap"></a>

### toMap utils list
<a name="utility-helpers-in-toMap-list"></a>

** `$util.dynamodb.toMap(Map) : Map` **  
Converts a map to the 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" }
                   ]
               }
           }
```
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.

## S3Object utils
<a name="utility-helpers-in-S3Object"></a>

### S3Object utils list
<a name="utility-helpers-in-S3Object-list"></a>

** `$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" }
```

# Amazon RDS helpers in \$1util.rds
<a name="rds-helpers-in-util-rds"></a>

**Note**  
We now primarily support the APPSYNC\$1JS runtime and its documentation. Please consider using the APPSYNC\$1JS runtime and its guides [here](https://docs.aws.amazon.com/appsync/latest/devguide/resolver-reference-js-version.html).

`$util.rds` contains helper methods that format Amazon RDS operations by getting rid of extraneous data in result outputs.

## \$1util.rds utils list
<a name="rds-helpers-in-util-rds-list"></a>

****`$util.rds.toJsonString(String serializedSQLResult): String`****  
Returns a `String` by transforming the stringified raw Amazon Relational Database Service (Amazon RDS) Data API operation result format to a more concise string. The returned string is a serialized list 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.  
If the corresponding statement in the input was a SQL query that causes a mutation (for example INSERT, UPDATE, DELETE), then an empty list is returned. For example, the query `select * from Books limit 2` provides the raw result from the Amazon RDS Data operation:  

```
{
    "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` is:  

```
[
  {
    "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`****  
This is the same as `util.rds.toJsonString`, but with the result being a JSON `Object`.

# HTTP helpers in \$1util.http
<a name="http-helpers-in-utils-http"></a>

**Note**  
We now primarily support the APPSYNC\$1JS runtime and its documentation. Please consider using the APPSYNC\$1JS runtime and its guides [here](https://docs.aws.amazon.com/appsync/latest/devguide/resolver-reference-js-version.html).

The `$util.http` utility provides helper methods that you can use to manage HTTP request parameters and to add response headers.

## \$1util.http utils list
<a name="http-helpers-in-utils-http-list"></a>

** `$util.http.copyHeaders(Map) : Map` **  
Copies the headers from the map, excluding the following restricted HTTP headers:  
+ transfer-encoding
+ connection
+ host
+ expect
+ keep-alive
+ upgrade
+ proxy-authenticate
+ proxy-authorization
+ te
+ content-length
You can use this utility to forward request headers to your downstream HTTP endpoint.  

```
{
    ...
    "params": {
        ...
        "headers": $util.http.copyHeaders($ctx.request.headers),
        ...
    },
    ...
}
```

**\$1util.http.addResponseHeader(String, Object)**  
Adds a single custom header with the name (`String`) and value (`Object`) of the response. The following limitations apply:  
+ In addition to the list of restricted headers for `copyHeaders(Map)`, header names cannot match any of the following:
  + Access-Control-Allow-Credentials
  + Access-Control-Allow-Origin
  + Access-Control-Expose-Headers
  + Access-Control-Max-Age
  + Access-Control-Allow-Methods
  + Access-Control-Allow-Headers
  + Vary
  + Content-Type
+ Header names can't start with the restricted prefixes `x-amzn-` or `x-amz-`.
+ The size of custom response headers can't exceed 4 KB. This includes header names and values.
+ You should define each response header once per GraphQL operation. However, if you define a custom header with the same name multiple times, the most recent definition appears in the response. All headers count towards the header size limit regardless of naming.
+ Headers with an empty or restricted name `(String)` or a null value `(Object)` will be ignored and yield a `ResponseHeaderError` error that is added to the operation's `errors` output.

```
export function request(ctx) {
  util.http.addResponseHeader('itemsCount', 7)
  util.http.addResponseHeader('render', ctx.args.render)
  return {}
}
```

****`$util.http.addResponseHeaders(Map)`****  
Adds multiple response headers to the response from the specified map of names `(String)` and values `(Object)`. The same limitations listed for the `addResponseHeader(String, Object)` method also apply to this method.  

```
export function request(ctx) {
  const headers = {
    headerInt: 12,
    headerString: 'stringValue',
    headerObject: {
      field1: 7,
      field2: 'string'
    }
  }
  util.http.addResponseHeaders(headers)
  return {}
}
```

# XML helpers in \$1util.xml
<a name="xml-helpers-in-utils-xml"></a>

**Note**  
We now primarily support the APPSYNC\$1JS runtime and its documentation. Please consider using the APPSYNC\$1JS runtime and its guides [here](https://docs.aws.amazon.com/appsync/latest/devguide/resolver-reference-js-version.html).

`$util.xml` contains helper methods that can make it easier to translate XML responses to JSON or a Dictionary.

## \$1util.xml utils list
<a name="xml-helpers-in-utils-xml-list"></a>

****`$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 \$1util.transform
<a name="transformation-helpers-in-utils-transform"></a>

**Note**  
We now primarily support the APPSYNC\$1JS runtime and its documentation. Please consider using the APPSYNC\$1JS runtime and its guides [here](https://docs.aws.amazon.com/appsync/latest/devguide/resolver-reference-js-version.html).

`$util.transform` contains helper methods that make it easier to perform complex operations against data sources, such as Amazon DynamoDB filter operations.

## Transformation helpers
<a name="transformation-helpers-conversions"></a>

### Transformation helpers utils list
<a name="transformation-helpers-in-utils-transform-list"></a>

****`$util.transform.toDynamoDBFilterExpression(Map) : Map`****  
Converts an input string to a filter expression for use with 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 OpenSearch 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.

## Transformation helpers subscription filters
<a name="transformation-helpers-conversions-subscription-filters"></a>

### Transformation helpers subscription filters utils list
<a name="transformation-helpers-in-utils-transform-list"></a>

****`$util.transform.toSubscriptionFilter(Map) : Map`****  
Converts a `Map` input object to a `SubscriptionFilter` expression object. The `$util.transform.toSubscriptionFilter` method is used as an input to the `$extensions.setSubscriptionFilter()` extension. For more information, see [Extensions](https://docs.aws.amazon.com/appsync/latest/devguide/extensions).

****`$util.transform.toSubscriptionFilter(Map, List) : Map`****  
Converts a `Map` input object to a `SubscriptionFilter` expression object. The `$util.transform.toSubscriptionFilter` method is used as an input to the `$extensions.setSubscriptionFilter()` extension. For more information, see [Extensions](https://docs.aws.amazon.com/appsync/latest/devguide/extensions).  
The first argument is the `Map` input object that's converted to the `SubscriptionFilter` expression object. The second argument is a `List` of field names that are ignored in the first `Map` input object while constructing the `SubscriptionFilter` expression object.

****`$util.transform.toSubscriptionFilter(Map, List, Map) : Map`****  
Converts a `Map` input object to a `SubscriptionFilter` expression object. The `$util.transform.toSubscriptionFilter` method is used as an input to the `$extensions.setSubscriptionFilter()` extension. For more information, see [Extensions](https://docs.aws.amazon.com/appsync/latest/devguide/extensions).   
The first argument is the `Map` input object that's converted to the `SubscriptionFilter` expression object, the second argument is a `List` of field names that will be ignored in the first `Map` input object, and the third argument is a `Map` input object of strict rules that's included while constructing the `SubscriptionFilter` expression object. These strict rules are included in the `SubscriptionFilter` expression object in such a way that at least one of the rules will be satisfied to pass the subscription filter.

## Subscription filter arguments
<a name="subscription-filter-arguments"></a>

The following table explains the how the arguments of the following utilities are defined:
+ `$util.transform.toSubscriptionFilter(Map) : Map`
+ `$util.transform.toSubscriptionFilter(Map, List) : Map`
+ `$util.transform.toSubscriptionFilter(Map, List, Map) : Map`

------
#### [ Argument 1: Map ]

Argument 1 is a `Map` object with the following key values:
+ field names
+ "and"
+ "or"

For field names as keys, the conditions on these fields' entries are in the form of `"operator" : "value"`. 

The following example shows how entries can be added to the `Map`:

```
"field_name" : {
                    "operator1" : value             
               }

## We can have multiple conditions for the same field_name: 

"field_name" : {
                    "operator1" : value             
                    "operator2" : value
                    .
                    .
                    .                  
               }
```

When a field has two or more conditions on it, all of these conditions are considered to use the OR operation.

The input `Map` can also have "and" and "or" as keys, implying that all entries within these should be joined using AND or OR logic depending on the key. The key values "and" and "or" expect an array of conditions.

```
"and" : [
            
            {
                "field_name1" : {
                    "operator1" : value             
                }
             },
             
             {
                "field_name2" : {
                    "operator1" : value             
                }
             },
             .
             .
        ].
```

Note that you can nest "and" and "or". That is, you can have nested "and"/"or" within another "and"/"or" block. However, this doesn't work for simple fields.

```
"and" : [
            
            {
                "field_name1" : {
                    "operator" : value             
                }
             },
             
             {
                "or" : [
                            {
                                "field_name2" : {
                                    "operator" : value             
                                }
                            },
                            
                            {
                                "field_name3" : {
                                    "operator" : value             
                                }
                            }
              
                        ].
```

The following example shows an input of *argument 1* using `$util.transform.toSubscriptionFilter(Map) : Map`.

**Input(s)**

Argument 1: Map:

```
{
  "percentageUp": {
    "lte": 50,
    "gte": 20
  },
  "and": [
    {
      "title": {
        "ne": "Book1"
      }
    },
    {
      "downvotes": {
        "gt": 2000
      }
    }
  ],
  "or": [
    {
      "author": {
        "eq": "Admin"
      }
    },
    {
      "isPublished": {
        "eq": false
      }
    }
  ]
}
```

**Output**

The result is a `Map` object:

```
{
  "filterGroup": [
    {
      "filters": [
        {
          "fieldName": "percentageUp",
          "operator": "lte",
          "value": 50
        },
        {
          "fieldName": "title",
          "operator": "ne",
          "value": "Book1"
        },
        {
          "fieldName": "downvotes",
          "operator": "gt",
          "value": 2000
        },
        {
          "fieldName": "author",
          "operator": "eq",
          "value": "Admin"
        }
      ]
    },
    {
      "filters": [
        {
          "fieldName": "percentageUp",
          "operator": "lte",
          "value": 50
        },
        {
          "fieldName": "title",
          "operator": "ne",
          "value": "Book1"
        },
        {
          "fieldName": "downvotes",
          "operator": "gt",
          "value": 2000
        },
        {
          "fieldName": "isPublished",
          "operator": "eq",
          "value": false
        }
      ]
    },
    {
      "filters": [
        {
          "fieldName": "percentageUp",
          "operator": "gte",
          "value": 20
        },
        {
          "fieldName": "title",
          "operator": "ne",
          "value": "Book1"
        },
        {
          "fieldName": "downvotes",
          "operator": "gt",
          "value": 2000
        },
        {
          "fieldName": "author",
          "operator": "eq",
          "value": "Admin"
        }
      ]
    },
    {
      "filters": [
        {
          "fieldName": "percentageUp",
          "operator": "gte",
          "value": 20
        },
        {
          "fieldName": "title",
          "operator": "ne",
          "value": "Book1"
        },
        {
          "fieldName": "downvotes",
          "operator": "gt",
          "value": 2000
        },
        {
          "fieldName": "isPublished",
          "operator": "eq",
          "value": false
        }
      ]
    }
  ]
}
```

------
#### [ Argument 2: List ]

Argument 2 contains a `List` of field names that shouldn't be considered in the input `Map` (argument 1) while constructing the `SubscriptionFilter` expression object. The `List` can also be empty.

The following example shows the inputs of argument 1 and argument 2 using `$util.transform.toSubscriptionFilter(Map, List) : Map`.

**Input(s)**

Argument 1: Map:

```
{

  "percentageUp": {
    "lte": 50,
    "gte": 20
  },
  "and": [
    {
      "title": {
        "ne": "Book1"
      }
    },
    {
      "downvotes": {
        "gt": 20
      }
    }
  ],
  "or": [
    {
      "author": {
        "eq": "Admin"
      }
    },
    {
      "isPublished": {
        "eq": false
      }
    }
  ]
}
```

Argument 2: List:

```
["percentageUp", "author"]
```

**Output**

The result is a `Map` object:

```
{
  "filterGroup": [
    {
      "filters": [
        {
          "fieldName": "title",
          "operator": "ne",
          "value": "Book1"
        },
        {
          "fieldName": "downvotes",
          "operator": "gt",
          "value": 20
        },
        {
          "fieldName": "isPublished",
          "operator": "eq",
          "value": false
        }
      ]
    }
  ]
}
```

------
#### [ Argument 3: Map ]

Argument 3 is a `Map` object that has field names as key values (cannot have "and" or "or"). For field names as keys, the conditions on these fields are entries in the form of `"operator" : "value"`. Unlike argument 1, argument 3 cannot have multiple conditions in the same key. In addition, argument 3 doesn't have an "and" or "or" clause, so there's no nesting involved either.

Argument 3 represents a list of strict rules, which are added to the `SubscriptionFilter` expression object so that **at least one** of these conditions is met to pass the filter.

```
{
  "fieldname1": {
    "operator": value
  },
  "fieldname2": {
    "operator": value
  }
}
.
.
.
```

The following example shows the inputs of *argument 1*, *argument 2*, and *argument 3* using `$util.transform.toSubscriptionFilter(Map, List, Map) : Map`.

**Input(s)**

Argument 1: Map:

```
{
  "percentageUp": {
    "lte": 50,
    "gte": 20
  },
  "and": [
    {
      "title": {
        "ne": "Book1"
      }
    },
    {
      "downvotes": {
        "lt": 20
      }
    }
  ],
  "or": [
    {
      "author": {
        "eq": "Admin"
      }
    },
    {
      "isPublished": {
        "eq": false
      }
    }
  ]
}
```

Argument 2: List:

```
["percentageUp", "author"]
```

Argument 3: Map:

```
{
  "upvotes": {
    "gte": 250
  },
  "author": {
    "eq": "Person1"
  }
}
```

**Output**

The result is a `Map` object:

```
{
  "filterGroup": [
    {
      "filters": [
        {
          "fieldName": "title",
          "operator": "ne",
          "value": "Book1"
        },
        {
          "fieldName": "downvotes",
          "operator": "gt",
          "value": 20
        },
        {
          "fieldName": "isPublished",
          "operator": "eq",
          "value": false
        },
        {
          "fieldName": "upvotes",
          "operator": "gte",
          "value": 250
        }
      ]
    },
    {
      "filters": [
        {
          "fieldName": "title",
          "operator": "ne",
          "value": "Book1"
        },
        {
          "fieldName": "downvotes",
          "operator": "gt",
          "value": 20
        },
        {
          "fieldName": "isPublished",
          "operator": "eq",
          "value": false
        },
        {
          "fieldName": "author",
          "operator": "eq",
          "value": "Person1"
        }
      ]
    }
  ]
}
```

------

# Math helpers in \$1util.math
<a name="math-helpers-in-util-math"></a>

**Note**  
We now primarily support the APPSYNC\$1JS runtime and its documentation. Please consider using the APPSYNC\$1JS runtime and its guides [here](https://docs.aws.amazon.com/appsync/latest/devguide/resolver-reference-js-version.html).

 `$util.math` contains methods to help with common Math operations. 

## \$1util.math utils list
<a name="math-helpers-in-util-math-list"></a>

** `$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.  
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.   
This function shouldn't be used for anything that needs high entropy randomness (for example, cryptography).

# String helpers in \$1util.str
<a name="str-helpers-in-util-str"></a>

**Note**  
We now primarily support the APPSYNC\$1JS runtime and its documentation. Please consider using the APPSYNC\$1JS runtime and its guides [here](https://docs.aws.amazon.com/appsync/latest/devguide/resolver-reference-js-version.html).

 `$util.str` contains methods to help with common String operations. 

## \$1util.str utils list
<a name="str-helpers-in-util-str-list"></a>

** `$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.

# Extensions
<a name="extensions"></a>

**Note**  
We now primarily support the APPSYNC\$1JS runtime and its documentation. Please consider using the APPSYNC\$1JS runtime and its guides [here](https://docs.aws.amazon.com/appsync/latest/devguide/resolver-reference-js-version.html).

`$extensions` contains a set of methods to make additional actions within your resolvers.

## Caching extensions
<a name="caching-extensions-list"></a>

**`$extensions.evictFromApiCache(String, String, Object) : Object`**  
Evicts an item from the AWS AppSync server-side cache. The first argument is the type name. The second argument is the field name. The third argument is an object containing key-value pair items that specify the caching key value. You must put the items in the object in the same order as the caching keys in the cached resolver's `cachingKey`.  
This utility works only for mutations, not queries.

## Subscription extensions
<a name="subscription-extensions-list"></a>

**`$extensions.setSubscriptionFilter(filterJsonObject)`**  
Defines enhanced subscription filters. Each subscription notification event is evaluated against provided subscription filters and delivers notifications to clients if all filters evaluate to `true`. The argument is `filterJsonObject` as described in the following section.  
You can use this extension method only in the response mapping templates of a subscription resolver.

**`$extensions.setSubscriptionInvalidationFilter(filterJsonObject)`**  
Defines subscription invalidation filters. Subscription filters are evaluated against the invalidation payload, then invalidate a given subscription if the filters evaluate to `true`. The argument is `filterJsonObject` as described in the following section.  
You can use this extension method only in the response mapping templates of a subscription resolver.

**`$extensions.invalidateSubscriptions(invalidationJsonObject)`**  
Used to initiate a subscription invalidation from a mutation. The argument is `invalidationJsonObject` as described in the following section.  
This extension can be used only in the response mapping templates of the mutation resolvers.  
You can only use at most five unique `$extensions.invalidateSubscriptions()` method calls in any single request. If you exceed this limit, you will receive a GraphQL error.

## Argument: filterJsonObject
<a name="extensions-setSubscriptionInvalidationFilter"></a>

The JSON object defines either subscription or invalidation filters. It's an array of filters in a `filterGroup`. Each filter is a collection of individual filters.

```
{
    "filterGroup": [
        {
           "filters" : [
                 {
                    "fieldName" : "userId",
                    "operator" : "eq",
                    "value" : 1
                }
           ]
           
        },
        {
           "filters" : [
                {
                    "fieldName" : "group",
                    "operator" : "in",
                    "value" : ["Admin", "Developer"]
                }
           ]
           
        }
    ]
}
```

Each filter has three attributes: 
+ `fieldName` – The GraphQL schema field.
+ `operator` – The operator type.
+ `value` – The values to compare to the subscription notification `fieldName` value.

The following is an example assignment of these attributes:

```
{
 "fieldName" : "severity",
 "operator" : "le",
 "value" : $context.result.severity
}
```

### Field: fieldName
<a name="extensions-fieldName"></a>

The string type `fieldName` refers to a field defined in the GraphQL schema that matches the `fieldName` in the subscription notification payload. When a match is found, the `value` of the GraphQL schema field is compared to the `value` of the subscription notification filter. In the following example, the `fieldName` filter matches the `service` field defined in a given GraphQL type. If the notification payload contains a `service` field with a `value` equivalent to `AWS AppSync`, the filter evaluates to `true`:

```
{
 "fieldName" : "service",
 "operator" : "eq",
 "value" : "AWS AppSync"
}
```

### Field: value
<a name="extensions-value"></a>

The value can be a different type based on the operator:
+ A single number or Boolean
  + String examples: `"test"`, `"service"`
  + Number examples: `1`, `2`, `45.75`
  + Boolean examples: `true`, `false`
+ Pairs of numbers or strings
  + String pair example: `["test1","test2"]`, `["start","end"]`
  + Number pair example: `[1,4]`, `[67,89]`, `[12.45, 95.45]`
+ Arrays of numbers or strings
  + String array example: `["test1","test2","test3","test4","test5"]`
  + Number array example: `[1,2,3,4,5]`, `[12.11,46.13,45.09,12.54,13.89]`

### Field: operator
<a name="extensions-operator"></a>

A case-sensitive string with the following possible values: 


| 
| 
| Operator | Description | Possible value types | 
| --- |--- |--- |
| eq | Equal | integer, float, string, Boolean | 
| ne | Not equal | integer, float, string, Boolean | 
| le | Less than or equal | integer, float, string | 
| lt | Less than | integer, float, string | 
| ge | Greater than or equal | integer, float, string | 
| gt | Greater than | integer, float, string | 
| contains | Checks for a subsequence or value in the set. | integer, float, string | 
| notContains | Checks for the absence of a subsequence or absence of a value in the set. | integer, float, string | 
| beginsWith | Checks for a prefix. | string | 
| in | Checks for matching elements that are in the list. | Array of integer, float, or string | 
| notIn | Checks for matching elements that aren't in the list. | Array of integer, float, or string | 
| between | Between two values | integer, float, string | 
| containsAny | Contains common elements | integer, float, string | 

The following table describes how each operator is used in the subscription notification.

------
#### [ eq (equal) ]

The `eq` operator evaluates to `true` if the subscription notification field value matches and is strictly equal to the filter's value. In the following example, the filter evaluates to `true` if the subscription notification has a `service` field with the value equivalent to `AWS AppSync`.

**Possible value types:** integer, float, string, Boolean

```
{
 "fieldName" : "service",
 "operator" : "eq",
 "value" : "AWS AppSync"
}
```

------
#### [ ne (not equal) ]

The `ne` operator evaluates to `true` if the subscription notification field value is different from the filter's value. In the following example, the filter evaluates to `true` if the subscription notification has a `service` field with a value different from `AWS AppSync`.

**Possible value types:** integer, float, string, Boolean

```
{
 "fieldName" : "service",
 "operator" : "ne",
 "value" : "AWS AppSync"
}
```

------
#### [ le (less or equal) ]

The `le` operator evaluates to `true` if the subscription notification field value is less than or equal to the filter's value. In the following example, the filter evaluates to `true` if the subscription notification has a `size` field with a value less than or equal to `5`.

**Possible value types:** integer, float, string

```
{
 "fieldName" : "size",
 "operator" : "le",
 "value" : 5
}
```

------
#### [ lt (less than) ]

The `lt` operator evaluates to `true` if the subscription notification field value is lower than the filter's value. In the following example, the filter evaluates to `true` if the subscription notification has a `size` field with a value lower than `5`.

**Possible value types:** integer, float, string

```
{
 "fieldName" : "size",
 "operator" : "lt",
 "value" : 5
}
```

------
#### [ ge (greater or equal) ]

The `ge` operator evaluates to `true` if the subscription notification field value is greater than or equal to the filter's value. In the following example, the filter evaluates to `true` if the subscription notification has a `size`field with a value greater than or equal to `5`.

**Possible value types:** integer, float, string

```
{
 "fieldName" : "size",
 "operator" : "ge",
 "value" : 5
}
```

------
#### [ gt (greater than) ]

The `gt` operator evaluates to `true` if the subscription notification field value is greater than the filter's value. In the following example, the filter evaluates to `true` if the subscription notification has a `size` field with a value greater than `5`.

**Possible value types:** integer, float, string

```
{
 "fieldName" : "size",
 "operator" : "gt",
 "value" : 5
}
```

------
#### [ contains ]

The `contains` operator checks for a substring, subsequence, or value in a set or single item. A filter with the `contains` operator evaluates to `true` if the subscription notification field value contains the filter value. In the following example, the filter evaluates to `true` if the subscription notification has a `seats` field with the array value containing the value `10`.

**Possible value types:** integer, float, string

```
{
 "fieldName" : "seats",
 "operator" : "contains",
 "value" : 10
}
```

In another example, the filter evaluates to `true` if the subscription notification has an `event` field with `launch` as substring.

```
{
 "fieldName" : "event",
 "operator" : "contains",
 "value" : "launch"
}
```

------
#### [ notContains ]

The `notContains` operator checks for the absence of a substring, subsequence, or value in a set or single item. The filter with the `notContains` operator evaluates to `true` if the subscription notification field value doesn't contain the filter value. In the following example, the filter evaluates to `true` if the subscription notification has a `seats` field with the array value not containing the value `10`.

**Possible value types:** integer, float, string

```
{
 "fieldName" : "seats",
 "operator" : "notContains",
 "value" : 10
}
```

In another example, filter evaluates to `true` if the subscription notification has an `event` field value without `launch` as its subsequence.

```
{
 "fieldName" : "event",
 "operator" : "notContains",
 "value" : "launch"
}
```

------
#### [ beginsWith ]

The `beginsWith` operator checks for a prefix in a string. The filter containing the `beginsWith` operator evaluates to `true` if the subscription notification field value begins with the filter's value. In the following example, the filter evaluates to `true` if the subscription notification has a `service` field with a value that begins with `AWS`.

**Possible value type:** string

```
{
 "fieldName" : "service",
 "operator" : "beginsWith",
 "value" : "AWS"
}
```

------
#### [ in ]

The `in` operator checks for matching elements in an array. The filter containing the `in` operator evaluates to `true` if the subscription notification field value exists in an array. In the following example, the filter evaluates to `true` if the subscription notification has a `severity` field with one of the values present in the array: `[1,2,3]`.

**Possible value type:** Array of integer, float, or string

```
{
 "fieldName" : "severity",
 "operator" : "in",
 "value" : [1,2,3]
}
```

------
#### [ notIn ]

The `notIn` operator checks for missing elements in an array. The filter containing the `notIn` operator evaluates to `true` if the subscription notification field value doesn't exist in the array. In the following example, the filter evaluates to `true` if the subscription notification has a `severity` field with one of the values not present in the array: `[1,2,3]`.

**Possible value type:** Array of integer, float, or string

```
{
 "fieldName" : "severity",
 "operator" : "notIn",
 "value" : [1,2,3]
}
```

------
#### [ between ]

The `between` operator checks for values between two numbers or strings. The filter containing the `between` operator evaluates to `true` if the subscription notification field value is between the filter's value pair. In the following example, the filter evaluates to `true` if the subscription notification has a `severity` field with values `2`,`3`,`4`.

**Possible value types:** Pair of integer, float, or string

```
{
 "fieldName" : "severity",
 "operator" : "between",
 "value" : [1,5]
}
```

------
#### [ containsAny ]

The `containsAny` operator checks for common elements in arrays. A filter with the `containsAny` operator evaluates to `true` if the intersection of the subscription notification field set value and filter set value is non empty. In the following example, the filter evaluates to `true` if the subscription notification has a `seats` field with an array value containing either `10` or `15`. This means that filter would evaluate to `true` if the subscription notification had a `seats` field value of `[10,11]` or `[15,20,30]`.

**Possible value types:** integer, float, or string

```
{
 "fieldName" : "seats",
 "operator" : "containsAny",
 "value" : [10, 15]
}
```

------

### AND logic
<a name="extensions-AND-logic"></a>

You can combine multiple filters using AND logic by defining multiple entries within the `filters` object in the `filterGroup` array. In the following example, filters evaluate to `true` if the subscription notification has a `userId` field with a value equivalent to `1` AND a `group` field value of either `Admin` or `Developer`.

```
{
    "filterGroup": [
        {
           "filters" : [
                 {
                    "fieldName" : "userId",
                    "operator" : "eq",
                    "value" : 1
                },
                {
                    "fieldName" : "group",
                    "operator" : "in",
                    "value" : ["Admin", "Developer"]
                }
           ]
           
        }
    ]
}
```

### OR logic
<a name="extensions-OR-logic"></a>

You can combine multiple filters using OR logic by defining multiple filter objects within the `filterGroup` array. In the following example, filters evaluate to `true` if the subscription notification has a `userId` field with a value equivalent to `1` OR a `group` field value of either `Admin` or `Developer`.

```
{
    "filterGroup": [
        {
           "filters" : [
                 {
                    "fieldName" : "userId",
                    "operator" : "eq",
                    "value" : 1
                }
           ]
           
        },
        {
           "filters" : [
                {
                    "fieldName" : "group",
                    "operator" : "in",
                    "value" : ["Admin", "Developer"]
                }
           ]
           
        }
    ]
}
```

### Exceptions
<a name="extensions-exceptions"></a>

Note that there are several restrictions for using filters:
+ In the `filters` object, there can be a maximum of five unique `fieldName` items per filter. This means that you can combine a maximum of five individual `fieldName` objects using AND logic.
+ There can be a maximum of twenty values for the `containsAny` operator.
+ There can be a maximum of five values for the `in` and `notIn` operators.
+ Each string can be a maximum of 256 characters.
+ Each string comparison is case sensitive.
+ Nested object filtering allows up to five nested levels of filtering.
+ Each `filterGroup` can have a maximum of 10 `filters`. This means that you can combine a maximum of 10 `filters` using OR logic.
  + The `in` operator is a special case of OR logic. In the following example, there are two `filters`:

    ```
    {
        "filterGroup": [
            {
               "filters" : [
                     {
                        "fieldName" : "userId",
                        "operator" : "eq",
                        "value" : 1
                    },
                    {
                        "fieldName" : "group",
                        "operator" : "in",
                        "value" : ["Admin", "Developer"]
                    }
               ]  
            }
        ]
    }
    ```

    The preceding filter group is evaluated as follows and counts towards the maximum filters limit:

    ```
    {
        "filterGroup": [
            {
               "filters" : [
                     {
                        "fieldName" : "userId",
                        "operator" : "eq",
                        "value" : 1
                    },
                    {
                        "fieldName" : "group",
                        "operator" : "eq",
                        "value" : "Admin"
                    }
               ]  
            },
            {
               "filters" : [
                     {
                        "fieldName" : "userId",
                        "operator" : "eq",
                        "value" : 1
                    },
                    {
                        "fieldName" : "group",
                        "operator" : "eq",
                        "value" : "Developer"
                    }
               ]  
            }
        ]
    }
    ```

## Argument: invalidationJsonObject
<a name="extensions-invalidationJsonObject"></a>

The `invalidationJsonObject` defines the following:
+ `subscriptionField` – The GraphQL schema subscription to invalidate. A single subscription, defined as a string in the `subscriptionField`, is considered for invalidation.
+ `payload` – A key-value pair list that's used as the input for invalidating subscriptions if the invalidation filter evaluates to `true` against their values.

  The following example invalidates subscribed and connected clients using the `onUserDelete` subscription when the invalidation filter defined in the subscription resolver evaluates to `true` against the `payload` value.

  ```
  $extensions.invalidateSubscriptions({
          "subscriptionField": "onUserDelete",
          "payload": {
                  "group": "Developer"
                  "type" : "Full-Time"
        }
      })
  ```