The inject
predicate allows you to inject JavaScript to determine if
the predicate should match or not. The JavaScript should be a function that accepts
the request object (and optionally a logger) and returns true or false.
See the injection page for details.
The execution will have access to a node.js environment. The following example uses
node's Buffer
object to decode base64 to a byte array.
POST /imposters HTTP/1.1
Host: localhost:<%= port %>
Accept: application/json
Content-Type: application/json
{
"port": 4555,
"protocol": "tcp",
"mode": "binary",
"stubs": [
{
"responses": [{ "is": { "data": "Zmlyc3QgcmVzcG9uc2U=" } }],
"predicates": [{
"inject": "function (request, logger) { logger.info('Inside injection'); return Buffer.from(request.data, 'base64')[2] > 100; }"
}]
},
{
"responses": [{ "is": { "data": "c2Vjb25kIHJlc3BvbnNl" } }],
"predicates": [{
"inject": "request => { return Buffer.from(request.data, 'base64')[2] <= 100; }"
}]
}
]
}
The first stub matches if the third byte is greater than 100. The request we're
sending is an encoding [99, 100, 101]:
echo 'Y2Rl' | base64 --decode | nc localhost 4555
first response
The logs will also show the injected log output. The second predicate has to
match a request originating from localhost with the third byte less than or equal
to 100. We're sending [98, 99, 100]
:
echo 'YmNk' | base64 --decode | nc localhost 4555
...giving the response:
second response
DELETE /imposters/4555 HTTP/1.1
Host: localhost:<%= port %>
Accept: application/json