Giter Site home page Giter Site logo

tedis's Introduction

tedis logo

travis issues license package Coverage Status tag
pr release languages size commit

Supporting Tedis

Introduction

What is tedis

Tedis write with typescript, it's the client of redis for nodejs, support async with ts and commonjs

Installation

yarn add tedis

Getting started

commonjs

const { Tedis, TedisPool } = require("tedis");

typescript

import { Tedis, TedisPool } from "tedis";
// no auth
const tedis = new Tedis({
  port: 6379,
  host: "127.0.0.1"
});

// auth
const tedis = new Tedis({
  port: 6379,
  host: "127.0.0.1",
  password: "your_password"
});

tls

const tedis = new Tedis({
  port: 6379,
  host: "127.0.0.1",
  tls: {
    key: fs.readFileSync(__dirname + "/client_server/client_key.pem"),
    cert: fs.readFileSync(__dirname + "/client_server/client_cert.pem")
  }
});

TedisPool

// no auth
const pool = new TedisPool({
  port: 6379,
  host: "127.0.0.1"
});

// auth
const pool = new TedisPool({
  port: 6379,
  host: "127.0.0.1",
  password: "your_password"
});
const tedis = await pool.getTedis();
// ... do some commands
pool.putTedis(tedis);

tls

const tedis = new TedisPool({
  port: 6379,
  host: "127.0.0.1",
  tls: {
    key: fs.readFileSync(__dirname + "/client_server/client_key.pem"),
    cert: fs.readFileSync(__dirname + "/client_server/client_cert.pem")
  }
});

Example

/**
 * core
 */
await tedis.command("SET", "key1", "Hello");
// "OK"
await tedis.command("SET", "key2", "World");
// "OK"

/**
 * key
 */
await tedis.keys("*");
// []
await tedis.exists("a");
// 0

/**
 * string
 */
await tedis.set("mystring", "hello");
// "OK"
await tedis.get("mystring");
// "hello"

/**
 * hash
 */
await tedis.hmset("myhash", {
  name: "tedis",
  age: 18
});
// "OK"
await tedis.hgetall("myhash");
// {
//   "name": "tedis",
//   "age": "18"
// }

/**
 * list
 */
await tedis.lpush("mylist", "hello", "a", "b", "c", "d", 1, 2, 3, 4);
// 9
await tedis.llen("mylist");
// 9

Type interface

base

pool

key

string

hash

list

set

zset

tedis's People

Contributors

dasoncheng avatar janopae avatar meteorlxy 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

tedis's Issues

GEOPOS Command returns inappropriate information

I am using tedis in one of my application. On redis-cli the GEOPOS command returns correct data, whereas when we are using tedis client to run the command it returns incorrect data.

Tedis Client
const resp = await client.command("GEOPOS", "USRPOS", "4567VBN");
console.log(resp); // Returns ["$19"]

redis-cli
127.0.0.1:6379> GEOPOS USRPOS 4567VBN

    1. "77.5943407416343689"
    2. "12.97018211330378534"

Run info stats command problems

Hello
I am trying to run the info stats command using tedis, but I does not work how I was expecting

I am running it like this:

const data = await tedis.command("INFO", "STATS");

the result I get is this:

# Stats

Am I doing something wrong?

I tried to run the command like this

const data = await tedis.command("INFO STATS");

but I don't get any output this way

Why does `mget` has two parameters?

The mget method has two parameters:

  /**
   * Returns the values of all specified keys. For every key that does not hold a string value or does not
   * exist, the special value nil is returned. Because of this, the operation never fails.
   *
   * @param key The key.
   * @param keys The other key.
   * @returns List of values at the specified keys.
   */
  public mget(key: string, ...keys: string[]) {
    return this.command<Array<string | number | null>>("MGET", key, ...keys);
  }

But shouldn't it be only one? this just seems weird and is very bad to use this method, having to do something like this:

  public async getManyObjects (keys: string[]) {
    return tedisClient.mget('_', ...keys).then(list => list.slice(1))
  }

Suggested behaviour

I would suggest to remove or concat the first key parameter, so we could use it like this:

  public async getManyObjects (keys: string[]) {
    return tedisClient.mget(...keys)
  }

A note on refining tedis

There is not enough energy to improve tedis, welcome everyone to participate in the construction of the project. The most urgent thing is to refactor the parser to facilitate the subsequent expansion of the interface, welcome suggestions or submit the implementation

How to use mget with a variable of type array

I'm assuming this is just a syntax issue, but I can't seem to use mget with a variable.

If I have a variable
const keys = ["record1", "record2", "record3"]

The following will return 0 records
const records = await tedis.mget(keys)

But if I do the following, I will get 3 records.
const records = await tedis.mget("record1", "record2", "record3")

I'm not sure of the syntax when using a variable.
I even tried the following, but I still get no results.
const keyString = '"record1", "record2", "record3"'
const records = await tedis.mget(keyString)

Any help on how to execute an mget request with a variable (preferably an array) would be appreciated.

Thanks!

docs down?

Im trying to figure out how to use this library. Are the links still valid in the README?
image

uncaught exception: protocol tries to read unavailable data

    at Function.byteLength (buffer.js:515:11)
    at Protocol.parse (/home/gipsy/o/qdice/node_modules/tedis/src/core/protocol.ts:74:29)
    at Socket.<anonymous> (/home/gipsy/o/qdice/node_modules/tedis/src/core/base.ts:133:23)
    at Socket.emit (events.js:189:13)
    at Socket.EventEmitter.emit (domain.js:441:20)
    at addChunk (_stream_readable.js:284:12)
    at readableAddChunk (_stream_readable.js:265:11)
    at Socket.Readable.push (_stream_readable.js:220:10)
    at TCP.onStreamRead [as onread] (internal/stream_base_commons.js:94:17)

My guess is that, on larger values, the socket stream's data event might not always send $<size> together with whatever is expected next, it might send it in two (or more) events. But base/protocol only knows to parse this at once. I tried to fix it but couldn't figure it out.

当redis断连,写入命令会永远卡住

try{
  //如果此处redis断连
  await redis.set(xxx,xxxx)
 //永远无法进入到这里
} catch(e){
 //也无法进入到这
}

查了base.ts发现command方法里,如果异常后就没法回调callback了,这样导致Promise永远无法resolve了

EPIPE error

getting following error: This socket has been ended by the other party

ADD ACL Support

the newest version is using acl instead of default auth please update your library.. : ) thanks
so username included in options for connect client

Tedis fork

Hi, I created a fork of this project... It's a "proof of concept" code of Tedis... testing it in production in the next few days.

Didn't want to spend more time as already did .... so... let me know your thoughts! Maybe can be incorporated.

It's available here: https://github.com/danielfroz/tedis

PS: you will notice that changed the code a lot. TedisPool specially has been removed... not exactly sure about it PROS (one connection may suffice due to non blocking nature?)... Anyways also wanted to keep this code as simple as possible. if problems detected later down in the road, a fix shall be easier.

Cheers

pool best practices

Hi,
Im just new to Tedis and have some doubts.

1. timeour?
What this parameter means?
Is it a timeout ?
If so, what units? seconds? milliseconds?
What is it for?
could you provide some reasonable initial value or tiop on it ?

2. Pool
Does it creates a pool of TCP connections to be reused in a round robin manner?
But what is a best practice to use it?

Should I pick a tedis for every operation I want to do ?

  • getTedis()
  • do one insert
  • putTedis()

Or pooling is better designed for a more continuous use:

  • getTedis()
  • do one insert
  • do one reading
  • do another insert
  • do another reading
  • .....
  • putTedis()

I'm working on a plattform in which we expect even hundreds of thousands of concurrent users at time.
Any advice or tip will be highly appreciated.

Thanks in advanced !!

Connect with a function instead of immediately

Due to the way our project is structured, we're registering events in an async way, which leads to the first connection events not being listened to. If possible, could you add a .connect() function that allows us to connect after creating the client?

This would allow us to create the client, wait for the events to be registered and then connect.

Thank you so much!

do we have support for modules?

A beginner with redis and stumbled across rejson module.
wanted to know if tedis supports rejson modules? if so, an example will be nice

SET should accept more parameters

Current implementation only has key and value as parameters for the SET method:

public set(key: string, value: string) { return this.command<string>("SET", key, value); }

Redis docs specify some extra options that might make commands such as setex deprecated in the future (https://redis.io/commands/set#options):

The SET command supports a set of options that modify its behavior:

EX seconds -- Set the specified expire time, in seconds.
PX milliseconds -- Set the specified expire time, in milliseconds.
NX -- Only set the key if it does not already exist.
XX -- Only set the key if it already exist.
KEEPTTL -- Retain the time to live associated with the key.
GET -- Return the old value stored at key, or nil when key did not exist.
Note: Since the SET command options can replace SETNX, SETEX, PSETEX, GETSET, it is possible that in future versions of > Redis these three commands will be deprecated and finally removed.

Command example:

redis> SET anotherkey "will expire in a minute" EX 60
"OK"

Transaction will never complete

I've found a bug in Tedis: transactions are hanging.

Scenario:

  1. Run "MULTI" command.
  2. Run any number of Redis commands: GET/SET/INCR/whatever. Example: SET foo 1, GET foo
  3. Run "EXEC" command.

Expected result:

  1. An array with two elements: ['OK', '1'].

Actual result:

  1. Infinite loop.

Minimal reproduction example:

const  { TedisPool } = require("tedis");

(async() => {
    const pool = new TedisPool({
        host: "127.0.0.1",
        port: 6379
    });

    const db = await pool.getTedis();
    await db.command("MULTI");
    await db.set("foo", "1");
    await db.get("foo");
    const res = await db.command("EXEC");
    console.log('Will not ever get here', res);
    process.exit(0);
})();

Version of tedis: 0.1.12
Version of Redis: 5.0.8
Version of node: 10.19.0

SCAN command returns invalid result

const tedis = new Tedis()
await tedis.rpush('a', 1)
await tedis.rpush('b', 2)

// expected out: [ '0', [ 'b', 'a' ] ]
// actual out: [ '0', '$1' ]
console.log(await tedis.command('scan', 0))

Use Tedis with SSL

Hey
I try to use Tedis to load data from a Azure Redis cache from my node application.
Seems there is a problem with my code, a bug or missing support for SSL encrypted connections, because when using SSL Port 6380 instead of Port 6379 (no ssl) I running into following error:

errno: 'ECONNRESET',
code: 'ECONNRESET',
syscall: 'read'

ERR_INVALID_ARG_TYPE The "string" argument must be of type string or an instance of Buffer or ArrayBuffer. Received undefined

get by key the issue got it
const tediss = new Tedis({
port: 6379,
host: "127.0.0.1"
});

          let response_all = await tediss.get("d751713988987e9331980363e24189ce");

TypeError [ERR_INVALID_ARG_TYPE]: The "string" argument must be of type string or an instance of Buffer or ArrayBuffer. Received undefined
at Function.byteLength (buffer.js:725:11)
at Protocol.parse (/home/lap53_claysol/Public/cms/serverless/cmsContentpartners/cp/node_modules/tedis/src/core/protocol.ts:74:29)
at Socket. (/home/lap53_claysol/Public/cms/serverless/cmsContentpartners/cp/node_modules/tedis/src/core/base.ts:133:23)
at Socket.emit (events.js:314:20)
at Socket.EventEmitter.emit (domain.js:483:12)
at addChunk (_stream_readable.js:297:12)
at readableAddChunk (_stream_readable.js:272:9)
at Socket.Readable.push (_stream_readable.js:213:10)
at TCP.onStreamRead (internal/stream_base_commons.js:188:23)

Still maintained?

Hi 👋

I'm just checking to see if this repo is still maintained.

Module '"net"' has no default export.

After running npm install --save redis with the minimal code od

import {Redis} from 'tedis'; // https://github.com/myour-cc/tedis

The error is:

ERROR in node_modules/tedis/src/common/base.ts(1,8): error TS1192: Module '"net"' has no default export.

tedis.get has invalid return type?

I'm sure there's a reason for this, but I can't find it anywhere in the docs or code.
As far as I know redis can only return strings (at least for GET) but the return types in the docs and and in the code (see screenshot) both show number as well. This is causing us to have to add normalization functions or overwrite the types using as string | null neither of which is ideal.

image

I don't mind updating this, is this something you would accept a pull request for?

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.