Giter VIP home page Giter VIP logo

handy-redis's Introduction

Note: since I wrote this, node_redis has now added built-in promise and typescript support, as well as many other high-level features - so you shouldn't need this anymore! Just install redis.

handy-redis

A wrapper around node_redis with Promise and TypeScript support.

Node CI codecov npm npm

Motivation

node_redis doesn't support Promises out-of-the-box - you have to use util.promisify on each command, or bluebird's promisifyAll, which has the side effect of removing all TypeScript/intellisense support from the package.

This package is a wrapper around node_redis and exclusively uses Promises. It publishes TypeScript types generated from the official redis documentation and examples, so it's much easier to know what parameters a command expects, and how to use the return values.

Usage

npm install handy-redis redis

ES6/TypeScript:

import { createNodeRedisClient } from 'handy-redis';

(async function() {
    const client = createNodeRedisClient();
    // or, call createNodeRedisClient(opts) using opts for https://www.npmjs.com/package/redis#rediscreateclient
    // or, call createNodeRedisClient(oldClient) where oldClient is an existing node_redis client.

    await client.set('foo', 'bar');
    const foo = await client.get('foo');
    console.log(foo);
})();

Vanilla JS, no async/await:

const { createNodeRedisClient } = require('handy-redis');

const client = createNodeRedisClient();

client
    .set('foo', 'bar')
    .then(() => client.get('foo'))
    .then(foo => console.log(foo));

The package is published with TypeScript types, with the redis documentation and response type attached to each command:

Adding new commands

Note that the redis package should be installed separately. If you need to use recent redis commands (e.g. lpos (recent at time of writing, at least)), which is not included in the redis package by default, you can use addNodeRedisCommand:

import { addNodeRedisCommand, createNodeRedisClient } from 'handy-redis'

addNodeRedisCommand('lpos')

const client = createNodeRedisClient(...)

If there's a command without a type, a new version of this library will need to be released - raise an issue if you come across one.

Accessing the underlying client

Some features of node_redis are not duplicated in this library, such as watch, pubsub and events generally. To use them, get the underlying client via .nodeRedis:

import { createNodeRedisClient } from 'handy-redis'

const client = createNodeRedisClient(...)

client.nodeRedis.on('error', err => console.error(err))
client.nodeRedis.publish('a_channel', 'a message')

v1.x compatibility

Some aliases exist for backwards-compatibility with v1.x:

  • createNodeRedisClient (preferred) is aliased to createHandyClient
  • WrappedNodeRedisClient (preferred) is aliased to IHandyRedis
  • client.nodeRedis (preferred) is aliased to client.redis

Examples

See the snapshot tests for tons of usage examples.

Multi

Most members of node_redis's multi type don't need to be promisified, because they execute synchronously. Only exec is async. Usage example:

import { createNodeRedisClient } from 'handy-redis';

(async function() {
    const client = createNodeRedisClient();

    const result = await client.multi().set("z:foo", "987").keys("z:*").get("z:foo").exec();

    console.log(result); // ["OK", ["z:foo"], "987"]
})();

The resolved value returned by exec is a tuple type, which keeps track of the commands that have been queued. In the above example, the type will be [string, string[], string].

Note: multi results are strongly-typed only when using typescript 4.0 and above - for lower typescript versions they will gracefully fall back to a union type (for the example above, it'll be Array<string | string[]>).

client.batch() also works, with the same API. See node_redis docs for details.

Migrating from v1.x

The client no longer has an execMulti function. Use the .exec() method on the multi instance.

Wrong types? Raise an issue!

Since the types are autogenerated from redis-doc, which doesn't adhere to a formal schema, they might be incomplete, or in some cases, wrong. The errors are easy enough to fix, but not easy to find, so if you think you've come across a case like this, please raise an issue.


Development

Most of the package is generated by running sample commands from the redis documentation repo.

How it works

The client is generated from the redis-doc repo.

  • pnpm codegen generates code:
    • generate-schema:
      • commands.json is used to output a commands file with json-schema arguments and return types.
      • Argument lists are modeled as arrays, which are flattened when sent to the underlying client. e.g. SET might have args ['foo', 'bar', ['EX', 60]] corresponding to the CLI command SET foo bar EX 60
      • the markdown documentation for each command is parsed for the return type
    • generate-client:
      • the json-schema from the previous step is parsed and used to generate a typescript interface of commands.
        • Commands use a basic higher-kinded types implementation. The Multi interface requires a key pointing to a property on a ResultTypes<Result, Context> interface, with properties defined via module augmentation. By default, each command returns a promisified result type. See the node_redis multi implementation for an example which configures each command to return a chainable multi instance, using previous commands as the Context.
    • generate-tests:
      • the markdown docs for each command are parsed and transformed into typescript calls. e.g. SET FOO BAR EX 60 is decoded into client.set('foo', 'bar', ['EX', 60])
      • these typescript calls are put into jest tests and their outputs are snapshotted
      • these tests are internal only and are not included in the published package

At each stage, there are some patches to plug gaps and inconsistencies in redis-doc and node_redis.

From all the code-generation only the interface file is exported. When a client is created, each command on the node_redis client prototype is added as a method on handy-redis's client, a wrapped and promisified version of the equivalent node_redis method.

git clone https://github.com/mmkal/handy-redis
cd handy-redis
pnpm install

Make sure you have docker installed and docker-compose is on your path, and start up a redis server in the background with pnpm redis:up -d.

To fully test the package as it is on your machine, the same way CI does:

pnpm test

pnpm test runs the build, test and lint scripts. It removes all generated code before, and after checks that your git status is clean. This is to allow tracking changes to the generated client over time, to make what the published package contains more visible, and to make sure that generated code hasn't been modified without auditing first. You should not manually edit any files under a */generated/* path. If pnpm test fails for you because you deliberately changed the way the codegen works, take a look at the git changes, check them in and run pnpm test again.

The build script generates the client before using TypeScript to compile it. If you want to run the tests without rebuilding, linting etc., use pnpm jest.

There are some more scripts in package.json which can be useful for local development.

Redis doc was added via git subtree add --prefix docs/redis-doc https://github.com/redis/redis-doc master --squash following this guide. Here's how they say it can be updated:

git subtree pull --prefix docs/redis-doc https://github.com/redis/redis-doc master --squash

Testing

If a snapshot test fails, it's possible it just needs to be updated. Make sure your git status is clean and run pnpm jest -u.

Types are tested using expect-type.

handy-redis's People

Contributors

canthealmighty avatar dependabot-preview[bot] avatar dependabot[bot] avatar liam-betsworth avatar mmkal avatar nl-brett-stime avatar renovate[bot] avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

handy-redis's Issues

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this πŸ’ͺ.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


Invalid npm token.

The npm token configured in the NPM_TOKEN environment variable must be a valid token allowing to publish to the registry https://registry.npmjs.org/.

If you are using Two-Factor Authentication, make configure the auth-only level is supported. semantic-release cannot publish with the default auth-and-writes level.

Please make sure to set the NPM_TOKEN environment variable in your CI with the exact value of the npm token.


Good luck with your project ✨

Your semantic-release bot πŸ“¦πŸš€

Missing Event Emitters/Listeners

Hey

I just wanted to ask if its possible to add event emitters so I can use them to track errors.
I'm using generic-pool to keep multiple redis connections open and I need to listen to error events to remove broken clients from the pool.

With the official redis module I can use client.on("error", cb) but there is no current solution on handy-redis.

Thanks in advance

Need support for `client.duplicate()`

Because node-redis can't process another messages when calling blocking commands at the same time, I had to use client.duplicate(), and because handy-redis is just a wrapper for node-redis, I was able to handle this situation by doing like this:

const blockingClient = createHandyClient(await client.duplicate());

This workaround is a bit ugly and bad because there is no need to use await keyword to do this, and also I needed to wrap its result in order to work with handy-redis. So, it would be great if handy-redis supports this as just like shortcut for the code above.

Multi commands pass an array to the underlying redis function

When setting up the commands for the WrappedNodeRedisClientImpl.prototype, the flattened array of parameters are passed using the spread operator in src/node_redis/index.ts#58,

return this.nodeRedis[method](...flattenedArgs);

however, the flattened array of parameters is passed without using the spread operator in src/node_redis/multi.ts#L61

(this as any).nodeRedisMulti[method](flattenDeep(args));

The result appears to be that for multi commands, the wrapped nodeRedis instance receives its parameters as a single array whereas non-multi functions receive their arguments as separate arguments. This seems to cause an issue when mocking the underlying redis instance with redis-mock since it does not correctly handle the parameters received from the multi functions.

Set command can return null

Using set with NX or XX can make the command return null. Right now the type definitions for all the set overloads are Promise<string>. I would guess the fix would be to change the overloads with the "condition" parameter to Promise<string | null>.

The easiest way to test is to make a random set call with XX. You'll get back null from the library.

https://redis.io/commands/set
Simple string reply: OK if SET was executed correctly. Null reply: a Null Bulk Reply is returned if the SET operation was not performed because the user specified the NX or XX option but the condition was not met.

Allow string objects for hmset

Currently the types generated for hmset only allow sending [string, string] as values but the original redis also allows to use { [key: string]: string } objects. It would be nice if handy-redis supported this too!

TypeError: net.isIP is not a function

I'm trying this in my react typescript project.

npm install handy-redis redis

then

import { createNodeRedisClient } from 'handy-redis'; const client = createNodeRedisClient();

And it gives me error:
TypeError: net.isIP is not a function.

What am I missing?

REDIS version: 6.0.10
Handy-redis version: ^2.2.1

Documentation on the options work?

This maybe obvious to others, but as a new user of this -- I find it hard to see what options I can pass, etc. in to get Redis configured correctly. Maybe a section in the documentation and a sample or two? Otherwise I am loving the cleanliness of the package!

Scan has `unknown` return type

I'm trying to use SCAN (and its variants) in handy-redis, but I'm a bit confused that it has an unknown return type. I'll experiment with casting, assuming that I may have to cast it to a tuple of [cursor, results] where cursor is number.

EDIT: In fact, it turned out to be a bit more subtle. What I had to do is:

type ScanReturnType = [string, string[]];

export async function scanTest(redis: RedisClient) {
  let prevCursor = "0";
  while (true) {
    let [cursor, data] = (await redis.scan((prevCursor as unknown) as number)) as ScanReturnType;
    console.log(data.length);
    if (cursor === "0") {
      break;
    } else {
      prevCursor = cursor;
    }
  }
}

The problem is that the returned cursor is actually a string whereas on input side it is a number. Initially I was using cursor === 0 as a termination condition, which caused an infinite loop due to the type mismatch. Perhaps the input argument to scan should be number | string so that reusing the cursor is more straightforward and avoids the (prevCursor as unknown) as number) cast.

Would it make sense to adjust the types to make that more convenient?

SPOP return was string[] in 1.x, now it is string, but it can return an Array

Hi,

thank you for releasing 2.0, great!

I just updated my code and saw that the Typescript definition for SPOP says it returns a string, in the previous version of handy-redis it was returning an array (because you can add the "count" parameter to get more than one), is this on purpose or a bug?

Keep up the great work, handy-redis makes it so much easier!

@types/redis 2.8.6 is incompatible

Using @types/redis 2.8.6

I can't create client with neither opts nor RedisClient

const opts: Redis.ClientOpts = {
    host: process.env.REDISHOST,
    port: parseInt(process.env.REDISPORT, 10),
    password: process.env.REDISPASSWORD
};
this.testRedisClient = Redis.createClient(opts);
this.handyRedisClient = createHandyClient(opts); // infers opts as RedisClient type. Not working
this.handyRedisClient = createHandyClient(this.testRedisClient); // Error:   Property 'substr' is missing in type 'RedisClient'.
this.handyRedisClient = createHandyClient(1234,'host',opts); // Error:  Types of property 'db' are incompatible. Type 'string | number' is not assignable to type 'string'. Type 'number' is not assignable to type 'string'.

None of these initialisation works. Its all fine with 0.12.36 version of @types/redis

Consider exporting ClientOpts ??

I am trying to figure out the best way to use this in my code .. and I want to declare a variable of : ClientOps w/o having to import "redis" again (and maybe have a conflict) ..

I am not sure how to access ClientOps within my program .. but if you did a

export { ClientOps } from 'redis';

I think that would do the trick?

How to add command ?

Thanks for the project, I am trying to use this package & add command to be able to store json data, it seems that I something like

const redis = createHandyClient({ host: 'localhost', port: 6379, db: 0 });
redis.redis.add_command('json.set');
redis.json_set('test', 42)

Should work but I have an error 'redis.redis.add_command is not a function'

GEOSEARCH support

Hi, I searched in the repo but I couldn't find any reference to the geosearch command.

It's possibile to support it?

I tried using addNodeRedisCommand but I can't get it to work(I'm not even sure I got how it works)

TypeError: _.flattenDeep is not a function

generated client.js
line 1282
it cause TypeError: _.flattenDeep is not a function

may be type too quick.

[email protected]

     * since: 1.0.0
     *
     * group: generic
     */
    keys(...args) {
        const flattenedArgs = _.flattenDeep(args);
                                                ^^^^^^^^^^^^
        return new Promise((resolve, reject) => {
            this.redis.keys.apply(this.redis, [
                ...flattenedArgs,
                (err, data) => err ? reject(err) : resolve(data),
            ]);
        });
    }

Having trouble using the constructor w/ ClientOps

I am sure just is this a user error -- but I have some pretty simple TS code and it's throwing me a TS error. The code and error follow:

import { createHandyClient, IHandyRedis } from 'handy-redis';
import { BaseStore } from 'koa-session-ts';
import { ClientOpts } from '../../node_modules/@types/redis';

/**
 * RedisStore for koa-session
 *
 * @param {object} options the options pass to node_redis
 * @returns RedisStore instance
 */
export class RedisSessionStore extends BaseStore {
  // Class members
  readonly client: IHandyRedis;

  constructor(options?: ClientOpts) {
    super();

    this.client = createHandyClient(options);   // Error is here at options

It doesn't like the options I pass in ..following problem

I also tried to set the options to type ICreateHandyClient but effectively the same error..

I am using TS 2.9.2

[ts]
Argument of type 'ClientOpts | undefined' is not assignable to parameter of type 'RedisClient'.
  Type 'undefined' is not assignable to type 'RedisClient'.
(parameter) options: ClientOpts | undefined

It looks like it's taking only the last definition in the Interface or something .. ??

Again, I am probably just doing something wrong here ...

Thanks

Cannot redeclare block-scoped variable 'addCommand'

Hi, I just moved from tedis to this library with very few issues, but I'm getting a compile time issue:

Cannot redeclare block-scoped variable 'addCommand'

To isolate the issue, I created an empty typescript project:

{
  "name": "crashy",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "dependencies": {
    "@types/node": "^15.14.0",
    "handy-redis": "^2.2.1",
    "redis": "^3.1.2",
    "typescript": "^4.3.5"
  }
}

With the above, the dependencies currently are (yarn.lock summarized):

// Format
// Package file : Installed Version
@types/redis@^2.8.27:  version "2.8.30"
redis@^3.1.2: version "3.1.2"
handy-redis@^2.2.1: version "2.2.1"

And used a very generic typescript config file.

With all of the above, I get the following conflict:


1410 export function addCommand(command: string): void;
                     ~~~~~~~~~~

  node_modules/handy-redis/dist/node_redis/index.d.ts:5:11
    5     const addCommand: (name: string) => void;
                ~~~~~~~~~~
    'addCommand' was also declared here.

node_modules/handy-redis/dist/node_redis/index.d.ts:5:11 - error TS2451: Cannot redeclare block-scoped variable 'addCommand'.

5     const addCommand: (name: string) => void;
            ~~~~~~~~~~

  node_modules/@types/redis/index.d.ts:1410:17
    1410 export function addCommand(command: string): void;
                         ~~~~~~~~~~
    'addCommand' was also declared here.

Action Required: Fix Renovate Configuration

There is an error with this repository's Renovate configuration that needs to be fixed. As a precaution, Renovate will stop PRs until it is resolved.

Error type: undefined. Note: this is a nested preset so please contact the preset author if you are unable to fix it yourself.

Support redis-mock

I'm passing the redis client to handyRedis, but it appears to still attempt to connect on 127.0.0.1:6379.

const redis = require("redis-mock");
const handyRedis = require("handy-redis");
const client = handyRedis.createHandyClient(redis.createClient());

Results:

 console.error
    Error: Redis connection to 127.0.0.1:6379 failed - connect ECONNREFUSED 127.0.0.1:6379
        at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1137:16)

subscribe arguments are wrong

subscribe in handy-redis is typed as subscribe(...channels: Array<[string]>): Promise<any>;, but it should be subscribe(...channels: Array<string>): Promise<any>;

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Warning

These dependencies are deprecated:

Datasource Name Replacement PR?
npm @types/redis Unavailable
npm npm-run-all Available

Rate-Limited

These updates are currently rate-limited. Click on a checkbox below to force their creation now.

  • chore(deps): update actions/checkout action to v2.7.0
  • chore(deps): update pnpm to v8.15.9
  • chore(deps): update actions/checkout action to v4
  • chore(deps): update actions/setup-node action to v4
  • chore(deps): update codecov/codecov-action action to v4
  • chore(deps): update pnpm to v9
  • chore(deps): update redis docker tag to v7
  • πŸ” Create all rate-limited PRs at once πŸ”

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

  • chore(deps): update devdependencies (@types/cross-spawn, @types/jest, @types/lodash, @types/node, @types/redis-mock, @typescript-eslint/eslint-plugin, @typescript-eslint/parser, downlevel-dts, eslint, eslint-config-xo, eslint-config-xo-typescript, eslint-plugin-codegen, eslint-plugin-import, eslint-plugin-prettier, expect-type, npm-run-all, prettier, string-argv, ts-jest, ts-node, typescript)
  • chore(deps): update redis docker tag to v6.2.14
  • chore(deps): update devdependencies (major) (@types/eslint, @types/glob, @types/jest, @types/node, @typescript-eslint/eslint-plugin, @typescript-eslint/parser, del-cli, eslint, eslint-config-xo-typescript, eslint-plugin-jest, eslint-plugin-prettier, eslint-plugin-unicorn, jest, prettier, redis, ts-jest, typescript)
  • fix(deps): update dependency @types/redis to v4
  • Click on this checkbox to rebase all open PRs at once

Detected dependencies

docker-compose
docker-compose.yml
  • redis 6.2.4
github-actions
.github/workflows/build.yml
  • actions/checkout v2
  • actions/setup-node v2
  • codecov/codecov-action v2
  • redis 6.2.4
docs/redis-doc/.github/workflows/deploy.yml
  • actions/checkout v2.1.1
docs/redis-doc/.github/workflows/pull_request.yml
  • ruby/setup-ruby v1
  • actions/checkout v2.1.1
npm
package.json
  • @types/redis ^2.8.30
  • @types/cross-spawn 6.0.2
  • @types/eslint 7.29.0
  • @types/glob 7.2.0
  • @types/jest 27.4.1
  • @types/json-schema ^7.0.15
  • @types/lodash 4.14.181
  • @types/node 16.11.27
  • @types/redis-mock 0.17.1
  • @typescript-eslint/eslint-plugin 5.19.0
  • @typescript-eslint/parser 5.19.0
  • del-cli 4.0.1
  • downlevel-dts 0.9.0
  • eslint 8.13.0
  • eslint-config-xo 0.40.0
  • eslint-config-xo-typescript 0.50.0
  • eslint-plugin-codegen 0.16.1
  • eslint-plugin-import 2.26.0
  • eslint-plugin-jest 25.7.0
  • eslint-plugin-prettier 4.0.0
  • eslint-plugin-unicorn 38.0.1
  • eson-parser 0.0.6
  • expect-type 0.13.0
  • jest 27.5.1
  • lodash 4.17.21
  • npm-run-all 4.1.5
  • prettier 2.6.2
  • redis 3.1.2
  • redis-mock 0.56.3
  • string-argv 0.3.1
  • ts-jest 27.1.4
  • ts-node 10.7.0
  • typescript 4.6.3
  • node >= 10.0.0
  • pnpm 8.10.2

  • Check this box to trigger a request for Renovate to run again on this repository

Catching the error on connection fail is difficult

Currently if the TCP connection fails, it won't be caught. For example,

import { createHandyClient, IHandyRedis } from "handy-redis";
const testRedis = createHandyClient({ host: "127.0.0.1", port: 6379 });
try {
    const pingResult = await testRedis.ping();
} catch (e) {
}

won't catch the error:

Error: Redis connection to 127.0.0.1:6379 failed - connect ECONNREFUSED 127.0.0.1:6379
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1128:14)

A workaround for this is to do:

import Redis from "redis";
import { createHandyClient, IHandyRedis } from "handy-redis";
const untypedClient = Redis.createClient({ host: "127.0.0.1", port: 6379 });
untypedClient.on("error", (e: Error) => {
    // This untypedClient error catch prevents uncatchable errors on TCP connection fail.
});
const testRedis = createHandyClient({ host: "127.0.0.1", port: 6379 });
try {
    const pingResult = await testRedis.ping();
} catch (e) {
}

which works fine, but suppresses all errors, which obviously isn't ideal.

wrong direction in npm page

in npm page at top-right side
npm i handy-redis

but in documentation
npm install handy-redis redis

why don't you put redis into dependencies ?

or make all installing instructions like
npm install handy-redis redis

Multi Type definition issue

My app currently uses Typescript version 3.8.2 and I'm encountering the following error when building with tsc

node_modules/handy-redis/dist/node_redis/multi.d.ts:3:50 - error TS1256: A rest element must be last in a tuple type.

3 declare type Push_ts4<A extends unknown[], B> = [...A, B];

The README states the multi command has a fallback for Typescript < 4, but it doesn't seem to build at all.

I'm not able to upgrade to ts > 4 at this time. Are there any known workarounds?
Thanks!

How to use SCRIPT LOAD?

Hi,

i love handy-redis, makes it so much easier with Typescript!

But i have one issue: we need Lua-scripts and i am missing the SCRIPT LOAD (https://redis.io/commands/script-load ) command.
I know, i can use it with .redis.script('LOAD') but only with callbacks, or?

Thank you,
Max

Error handling for createHandyClient

Doing the following does not catch the error:

import { createHandyClient, IHandyRedis } from "handy-redis";

let client: IHandyRedis;
try {
  client = createHandyClient({
    url: "redis://This is an invalid URL"
  });
} catch (error) {
  console.log("GOT ERROR HERE");
}

Instead, it crashes the process with this message:

events.js:174
      throw er; // Unhandled 'error' event
      ^

Error: Redis connection to example:6379 failed - getaddrinfo ENOTFOUND example example:6379
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:56:26)
Emitted 'error' event at:
    at RedisClient.on_error (/Users/anandchowdhary/Projects/o15y/staart/node_modules/redis/index.
js:406:14)
    at Socket.<anonymous> (/Users/anandchowdhary/Projects/o15y/staart/node_modules/redis/index.js
:279:14)
    at Socket.emit (events.js:198:13)
    at Socket.EventEmitter.emit (domain.js:448:20)
    at emitErrorNT (internal/streams/destroy.js:91:8)
    at emitErrorAndCloseNT (internal/streams/destroy.js:59:3)
    at process._tickCallback (internal/process/next_tick.js:63:19)

.lpos is not a function

i am trying this in express/ nodejs using
handyredis.addNodeRedisCommand('lpos')
handyredis.createNodeRedisClient(Redisclient)
console.log('handy redis connected HANDY REDIS HANDY REDIS HANDY REDIS HANDY REDISH HANDY REDIS HANDY REDIS HANDY REDIS')

on calling lpos with handyredis client it says .lpos is not a function

RangeError: Maximum call stack size exceeded with large args set

When calling handyclient.hmset() with 200000 args, flattenDeep() causes stackoverflow. Is it possible to use _.flatten() instead?

(node:9360) UnhandledPromiseRejectionWarning: RangeError: Maximum call stack size exceeded
    at exports.flattenDeep (\node_modules\handy-redis\dist\flatten.js:7:15)
    at Array.map (<anonymous>)
    at Object.exports.flattenDeep (\node_modules\handy-redis\dist\flatten.js:7:30)
    at \node_modules\handy-redis\dist\index.js:18:45
    at new Promise (<anonymous>)
    at Object.handyClient.<computed> [as hmset] (\node_modules\handy-redis\dist\index.js:17:45)

Please see https://repl.it/repls/IntrepidCyanScript

Thanks

zrangebyscore doesn't allow +inf/-inf

Type definitions of some redis commands are not complete. For example here is type definition for
zrangebyscore(key: string, min: number, max: number, withscores: "WITHSCORES", offset_count: ["LIMIT", number, number]): Promise<any[]>;
Min and max arguments accept only number, where node_redis could also accept string or just "+inf" | "-inf".

ERR syntax error when using SET

os: Windows_NT 10.0.19042 x64 v0.30.6
version: 2.3.1
redis: 3.2.100
node: 12.13.0

os: mac
version: 2.3.1
redis: v=6.2.6 sha=00000000:0 malloc=libc bits=64 build=c6f3693d1aced7d9
node: 14.16.0

I have this piece of code which acts as an interceptor in the controller level which run fine on mac but not on my windows pc. Can verify why this is happening?

code:

async intercept(
        context: ExecutionContext,
        next: CallHandler,
    ): Promise<Observable<unknown>> {
        const request = context.switchToHttp().getRequest<Request>();
        const projectId = request.body['project']?.id;

        const expirySeconds = parseInt(process.env.REDIS_CACHE_SEC);
        const expiryKey = `${projectId}:expiry`;
        const dataKey = `${projectId}:data`;
        const pxAt = new Date().getTime() + expirySeconds * 1000;

        const data = await this.redisClient.set(
            dataKey,
            '1',
            ['PXAT', pxAt],
            'GET',
        );

        if (!data) {
            await this.redisClient.set(expiryKey, pxAt.toString(), [
                'PXAT',
                pxAt,
            ]);
            return next.handle();
        }

        return of([]);
    }

error:

"ReplyError: ERR syntax error\n at parseError (C:\\Users\\User\\Desktop\\project\\node_modules\\redis-parser\\lib\\parser.js:179:12)\n at parseType (C:\\Users\\User\\Desktop\\project\\node_modules\\redis-parser\\lib\\parser.js:302:14)"

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.