1
0
mirror of https://github.com/redis/node-redis.git synced 2025-07-31 05:44:24 +03:00
Files
node-redis/docs/programmability.md
Shaya Potter b2d35c5286 V5 bringing RESP3, Sentinel and TypeMapping to node-redis
RESP3 Support
   - Some commands responses in RESP3 aren't stable yet and therefore return an "untyped" ReplyUnion.
 
Sentinel

TypeMapping

Correctly types Multi commands

Note: some API changes to be further documented in v4-to-v5.md
2024-10-15 17:46:52 +03:00

2.2 KiB

Programmability

Redis provides a programming interface allowing code execution on the redis server.

Functions

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

import { createClient } from 'redis';

const client = createClient({
  functions: {
    library: {
      add: {
        NUMBER_OF_KEYS: 1,
        FIRST_KEY_INDEX: 1,
        transformArguments(key: string, toAdd: number): Array<string> {
          return [key, toAdd.toString()];
        },
        transformReply: undefined as unknown as () => NumberReply
      }
    }
  }
});

await client.connect();

await client.set('key', '1');
await client.library.add('key', 2); // 3

Lua Scripts

The following is an end-to-end example of the prior concept.

import { createClient, defineScript, NumberReply } 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,
      transformArguments(key: string, toAdd: number): Array<string> {
        return [key, toAdd.toString()];
      },
      transformReply: undefined as unknown as () => NumberReply
    })
  }
});

await client.connect();

await client.set('key', '1');
await client.add('key', 2); // 3