JavaScript request filter - Redis

The JavaScript request filter is the most flexible of all request filters. It can potentially be called for any request, and can modify it in any way it sees fit.

Parameters

  • Command patterns : optional. If specified, a comma-separated (or line break separated) list of strings or regular expressions for which this filter should be called, for instance: SCAN,0,MATCH,*,COUNT,regex:\d+. Spaces are ignored. All specified patterns must match in the given order for the filter to execute.

  • Client IPs: optional. If specified, a comma-separated (or line break separated) list of IP4 or IP6 addresses or regular expressions for IP addresses.

  • Users: optional. If specified, a comma-separated (or line break separated) list of user names or regular expressions for user names.


Example

If we wanted to catch the following query:

SCAN 50 MATCH foo* COUNT 100

we could specify the command patterns to:

SCAN

regex:\d+

MATCH

[a-zA-Z]+\*

COUNT

regex:\d+

A few things to notice:

  • \d means a digit (0-9) (see the documentation for all special characters)

  • we're using line breaks to separate the patterns, but we could have used commas

  • regular expressions are prefixed with regex:

  • in the fourth pattern, the asterisk is escaped because it has a special meaning in regular expressions

Code

The code has access to the request in the context.packet object, which is always an array of BulkString objects.

Example

if (parseInt(context.packet[1].string) >= 100) {

context.packet[1].string = "50";

}

The code also has access to the context.result object, which can be useful to return an error to the client instead of forwarding the request to the Redis server:

if (context.packet[1].string ==="BAD") {

context.result.errorMessage = "BAD You sent me a bad message";

}