ioredis icon indicating copy to clipboard operation
ioredis copied to clipboard

Transform event callback arguments

Open epiphone opened this issue 3 years ago • 2 comments
trafficstars

Is there a way to transform the Redis.on callback arguments?

In my use case I'm adding a prefix string to channel names with the following argument transformer:

Redis.Command.setArgumentTransformer("publish", (args) => {
  args[0] = "myPrefix:" + args[0];
  return args;
});

...and listening to messages as follows:

sub.subscribe("channelName");
sub.on("message", (channel, data) => {
  // channel equals "myPrefix:channelName"
});

await pub.publish("channelName", "some data");

The channel callback argument value here resolves to myPrefix:channelName. Is there any way to add a matching transformer that would strip the myPrefix: prefix from callback arguments? Note that in this case I can't modify the callback argument itself, that's part of another codebase.

In case there's no existing solution how about the following API?

Redis.Command.setEventTransformer("message", (args) => {
  args[0] = args[0].replace("myPrefix:", "");
  return args;
});

If the proposed API makes sense I'd be happy to open a PR. Thank you!

epiphone avatar Mar 03 '22 10:03 epiphone

Hey @epiphone 👋

There's no such API. I'd not use setArgumentTransformer for that case, and instead, I will probably create a thin wrapper:

const publish = (channel, ...args) => pub.publish(`prefix:${channel}`, ...args);
const subscribe = (channel, callback) => {
  sub.subscribe(`prefix:${channel}`);
  sub.on('message', (sourceChannel, data) => {
    if (sourceChannel === channel) {
      callback(data);
    }
  });
}

luin avatar Mar 03 '22 10:03 luin

Thanks for the quick reply!

In this case I don't have access to the sub instance. Basically I'm dealing with a system that accepts Redis constructor params as arguments but the rest is a black box.

epiphone avatar Mar 03 '22 11:03 epiphone