1
0
mirror of https://github.com/redis/node-redis.git synced 2025-08-09 00:22:08 +03:00
Files
node-redis/docs/programmability.md
Bobby I. 49d6b2d465 Update README.MD (#2924)
* Update README.MD

* docs: update programmability.md examples

+ add Programmability section to README and

* fix imports according to the new v5 exports

* more v5 docs updates

---------

Co-authored-by: Nikolay Karadzhov <nkaradzhov89@gmail.com>
2025-04-30 16:28:22 +03:00

88 lines
2.5 KiB
Markdown

# [Programmability](https://redis.io/docs/manual/programmability/)
Redis provides a programming interface allowing code execution on the redis server.
## [Functions](https://redis.io/docs/manual/programmability/functions-intro/)
The following example retrieves a key in redis, returning the value of the key, incremented by an integer. For example, if your key _foo_ has the value _17_ and we run `add('foo', 25)`, it returns the answer to Life, the Universe and Everything.
```lua
#!lua name=library
redis.register_function {
function_name = 'add',
callback = function(keys, args) return redis.call('GET', keys[1]) + args[1] end,
flags = { 'no-writes' }
}
```
Here is the same example, but in a format that can be pasted into the `redis-cli`.
```
FUNCTION LOAD "#!lua name=library\nredis.register_function{function_name='add', callback=function(keys, args) return redis.call('GET', keys[1])+args[1] end, flags={'no-writes'}}"
```
Load the prior redis function on the _redis server_ before running the example below.
```typescript
import { CommandParser } from '@redis/client/lib/client/parser';
import { NumberReply } from '@redis/client/lib/RESP/types';
import { createClient, RedisArgument } from 'redis';
const client = createClient({
functions: {
library: {
add: {
NUMBER_OF_KEYS: 1,
parseCommand(
parser: CommandParser,
key: RedisArgument,
toAdd: RedisArgument
) {
parser.pushKey(key)
parser.push(toAdd)
},
transformReply: undefined as unknown as () => NumberReply
}
}
}
});
await client.connect();
await client.set('key', '1');
await client.library.add('key', '2'); // 3
```
## [Lua Scripts](https://redis.io/docs/manual/programmability/eval-intro/)
The following is an end-to-end example of the prior concept.
```typescript
import { CommandParser } from '@redis/client/lib/client/parser';
import { NumberReply } from '@redis/client/lib/RESP/types';
import { createClient, defineScript, RedisArgument } from 'redis';
const client = createClient({
scripts: {
add: defineScript({
SCRIPT: 'return redis.call("GET", KEYS[1]) + ARGV[1];',
NUMBER_OF_KEYS: 1,
FIRST_KEY_INDEX: 1,
parseCommand(
parser: CommandParser,
key: RedisArgument,
toAdd: RedisArgument
) {
parser.pushKey(key)
parser.push(toAdd)
},
transformReply: undefined as unknown as () => NumberReply
})
}
});
await client.connect();
await client.set('key', '1');
await client.add('key', '2'); // 3
```