Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Release 2.0.0 (#32) #55

Merged
merged 1 commit into from
May 25, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
REDIS_HOST=localhost
REDIS_PORT=6379
2 changes: 1 addition & 1 deletion .eslintignore
Original file line number Diff line number Diff line change
@@ -1 +1 @@
test/
node_modules/
12 changes: 8 additions & 4 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
{
"root": true,
"extends": [
"airbnb"
],
"extends": ["eslint:recommended"],
"parserOptions": {
"ecmaVersion": 8,
"sourceType": "script"
},
"env": {
"node": true
"es6": true,
"node": true,
"mocha": true
}
}
File renamed without changes.
7 changes: 0 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,6 @@ To install the stable version:
npm install --save async-redis
```

## Typescript Support
```
npm install --save-dev @types/async-redis
```

[types](https://www.npmjs.com/package/@types/async-redis)

## Usage Example

### Creating Connection
Expand Down
24 changes: 11 additions & 13 deletions examples/create-redis.js
Original file line number Diff line number Diff line change
@@ -1,29 +1,27 @@
const asyncRedis = require("../src");
/* eslint no-console: 0 */
const asyncRedis = require('../src');

const client = asyncRedis.createClient();

client.on("error", function (err) {
console.log("Error " + err);
client.on('error', (err) => {
console.log(`Error ${err}`);
});

let addToSet = async () => {
let key = 'exampleSet';
let values = [
const addToSet = async () => {
const key = 'exampleSet';
const values = [
'item_1',
'item_2',
'item_3',
'item_4',
'item_5',
];
let promises = values.map((value) => {
return client.sadd(key, value);
});
const promises = values.map(value => client.sadd(key, value));
await Promise.all(promises);
return await client.smembers(key);
return client.smembers(key);
};

let flush = async () => {
return await client.flushall();
};
const flush = async () => client.flushall();

addToSet()
.then((results) => {
Expand Down
52 changes: 26 additions & 26 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,25 +1,37 @@
{
"private": false,
"version": "1.1.7",
"author": "Matthew Oaxaca",
"license": "MIT",
"version": "2.0.0",
"name": "async-redis",
"keywords": [
"redis",
"async",
"promise",
"es6"
],
"author": "Matthew Oaxaca",
"license": "MIT",
"description": "Light wrapper over redis_node with first class async & promise support.",
"repository": {
"type": "git",
"url": "git://github.com/moaxaca/async-redis.git"
},
"bugs": {
"url": "https://github.com/moaxaca/async-redis/issues"
},
"main": "src/index.js",
"typings": "./index.d.ts",
"typings": "src/index.d.ts",
"engines": {
"node": ">=7.6.0"
},
"directories": {
"example": "examples",
"test": "test"
},
"scripts": {
"coveralls": "nyc yarn test && nyc report --reporter=text-lcov | coveralls",
"lint": "eslint --fix --ext .js, src",
"test": "mocha",
"lint": "eslint --fix --ext .js, .",
"test": "mocha test/**/*.spec.js --config test/setup.js --exit",
"test:unit": "mocha test/unit/*.spec.js --config test/setup.js --exit",
"version:patch": "npm version patch",
"version:minor": "npm version minor",
"version:major": "npm version major"
Expand All @@ -29,26 +41,14 @@
"redis-commands": "^1.3.1"
},
"devDependencies": {
"chai": "^3.5.0",
"@types/node": "^14.0.27",
"@types/redis": "^2.8.25",
"chai": "^4.2.0",
"chai-as-promised": "^7.1.1",
"coveralls": "^3.0.0",
"eslint": "^4.17.0",
"eslint-config-airbnb": "^16.1.0",
"eslint-plugin-import": "^2.8.0",
"eslint-plugin-jsx-a11y": "^6.0.3",
"eslint-plugin-react": "^7.6.1",
"mocha": "^3.2.0",
"nyc": "^11.4.1"
},
"repository": {
"type": "git",
"url": "git://github.com/moaxaca/async-redis.git"
},
"bugs": {
"url": "https://github.com/moaxaca/async-redis/issues"
},
"directories": {
"example": "examples",
"test": "test"
"coveralls": "^3.1.0",
"dotenv": "^8.2.0",
"eslint": "^7.6.0",
"mocha": "^8.1.0",
"nyc": "^15.1.0"
}
}
162 changes: 162 additions & 0 deletions src/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
import { Commands, RedisClient, ClientOpts, ServerInfo } from 'redis';
import {EventEmitter} from "events";

type Callback<T> = (err: Error | null, reply: T) => void;

type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
type Omitted = Omit<RedisClient, keyof Commands<boolean>>;
type OkOrError = 'OK'|Error

interface OverloadedCommand<T, R> {
(arg1: T, arg2: T, arg3: T, arg4: T, arg5: T, arg6: T): R;
(arg1: T, arg2: T, arg3: T, arg4: T, arg5: T): R;
(arg1: T, arg2: T, arg3: T, arg4: T): R;
(arg1: T, arg2: T, arg3: T): R;
(arg1: T, arg2: T | T[]): R;
(arg1: T | T[]): R;
(...args: Array<T>): R;
}

interface Promisified<T = RedisClient> extends Omitted, Commands<Promise<boolean>> {}

interface AsyncRedisConstructor {
new (port: number, host?: string, options?: ClientOpts): Promisified;
new (unix_socket: string, options?: ClientOpts): Promisified;
new (redis_url: string, options?: ClientOpts): Promisified;
new (options?: ClientOpts): Promisified;

createClient(port: number, host?: string, options?: ClientOpts): Promisified;
createClient(unix_socket: string, options?: ClientOpts): Promisified;
createClient(redis_url: string, options?: ClientOpts): Promisified;
createClient(options?: ClientOpts): Promisified;

decorate: (client: RedisClient) => Promisified;
}

interface AsyncRedisEventHandlers extends EventEmitter {
on(event: 'message' | 'message_buffer', listener: (channel: string, message: string) => void): this;
on(event: 'pmessage' | 'pmessage_buffer', listener: (pattern: string, channel: string, message: string) => void): this;
on(event: 'subscribe' | 'unsubscribe', listener: (channel: string, count: number) => void): this;
on(event: 'psubscribe' | 'punsubscribe', listener: (pattern: string, count: number) => void): this;
on(event: string, listener: (...args: any[]) => void): this;
}

interface AsyncRedisCommands<R> {
/**
* Listen for all requests received by the server in real time.
*/
monitor(cb?: Callback<undefined>): any;
MONITOR(cb?: Callback<undefined>): any;

/**
* Get information and statistics about the server.
*/
info(): Promise<ServerInfo|boolean>;
info(section?: string | string[]): Promise<ServerInfo|boolean>;
INFO(): Promise<ServerInfo|boolean>;
INFO(section?: string | string[]): Promise<ServerInfo|boolean>;

/**
* Ping the server.
*/
ping(): Promise<string|boolean>;
ping(message: string): Promise<string|boolean>;
PING(): Promise<string|boolean>;
PING(message: string): Promise<string|boolean>;

/**
* Authenticate to the server.
*/
auth(password: string): Promise<string>;
AUTH(password: string): Promise<string>;

/**
* Get array of Redis command details.
*
* COUNT - Get total number of Redis commands.
* GETKEYS - Extract keys given a full Redis command.
* INFO - Get array of specific REdis command details.
*/
command(cb?: Callback<Array<[string, number, string[], number, number, number]>>): R;
COMMAND(cb?: Callback<Array<[string, number, string[], number, number, number]>>): R;

/**
* Get array of Redis command details.
*
* COUNT - Get array of Redis command details.
* GETKEYS - Extract keys given a full Redis command.
* INFO - Get array of specific Redis command details.
* GET - Get the value of a configuration parameter.
* REWRITE - Rewrite the configuration file with the in memory configuration.
* SET - Set a configuration parameter to the given value.
* RESETSTAT - Reset the stats returned by INFO.
*/
config: OverloadedCommand<string, boolean>;
CONFIG: OverloadedCommand<string, boolean>;

/**
* Return the number of keys in the selected database.
*/
dbsize(): Promise<number>;
DBSIZE(): Promise<number>;

/**
* OBJECT - Get debugging information about a key.
* SEGFAULT - Make the server crash.
*/
debug: OverloadedCommand<string, boolean>;
DEBUG: OverloadedCommand<string, boolean>;

/**
* PubSub Commands
*/
/**
* Post a message to a channel.
*/
publish(channel: string, value: string): Promise<number|boolean>;
PUBLISH(channel: string, value: string): Promise<number|boolean>;

/**
* CRUD Commands
*/

/**
* Append a value to a key.
*/
append(key: string, value: string): Promise<number>;
APPEND(key: string, value: string): Promise<number>;

/**
* Asynchronously rewrite the append-only file.
*/
bgrewriteaof(): Promise<OkOrError>;
BGREWRITEAOF(): Promise<OkOrError>;

/**
* Asynchronously save the dataset to disk.
*/
bgsave(): Promise<OkOrError>;
BGSAVE(): Promise<OkOrError>;

/**
* Determine if a key exists.
*/
exists: OverloadedCommand<string, R>;
EXISTS: OverloadedCommand<string, R>;

/**
* Set the string value of a key.
*/
set(key: string, value: string): Promise<string|boolean>;
set(key: string, value: string, flag: string): Promise<string|boolean>;
set(key: string, value: string, mode: string, duration: number): Promise<string|undefined>;
set(key: string, value: string, mode: string, duration: number, flag: string): Promise<string|undefined>;
SET(key: string, value: string): Promise<string|boolean>;
SET(key: string, value: string, flag: string): Promise<string|boolean>;
SET(key: string, value: string, mode: string, duration: number): Promise<string|undefined>;
SET(key: string, value: string, mode: string, duration: number, flag: string): Promise<string|undefined>;
}

interface AsyncRedisInterface extends AsyncRedisConstructor, AsyncRedisEventHandlers, AsyncRedisCommands<boolean> {}
declare const AsyncRedis: AsyncRedisInterface;
export = AsyncRedis;
66 changes: 40 additions & 26 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,35 +1,49 @@
/* eslint func-names: ["error", "as-needed"] */

const redis = require('redis');
const commands = require('redis-commands').list;
const objectDecorator = require('./object-decorator');
const objectPromisify = require('./object-promisify');
const redisCommands = require('./redis-commands');

const redisClients = new Map();

const AsyncRedis = function (args) {
const client = Array.isArray(args) ? redis.createClient(...args) : redis.createClient(args);
return AsyncRedis.decorate(client);
/**
* @return RedisClient
*/
const AsyncRedis = function (args=null) {
if (args) {
const serializedArgs = JSON.stringify(args);
if (!redisClients.has(serializedArgs)) {
redisClients.set(serializedArgs, Array.isArray(args) ? redis.createClient(...args) : redis.createClient(args));
}
this.setup(redisClients.get(serializedArgs));
}
};

AsyncRedis.createClient = (...args) => new AsyncRedis(args);
AsyncRedis.prototype.setup = function(redisClient) {
this.__redisClient = redisClient;
const commandConfigs = redisCommands(redisClient);
objectDecorator(redisClient, (name, method) => {
if (commandConfigs.commands.has(name)) {
objectPromisify(this, redisClient, name);
} else if (commandConfigs.queueCommands.has(name)) {
return (...args) => {
const multi = method.apply(redisClient, args);
return objectDecorator(multi, (multiName, multiMethod) => {
if (commandConfigs.multiCommands.has(multiName)) {
return objectPromisify(multi, multiMethod);
}
return multiMethod;
});
}
}
});
};

// this is the set of commands to NOT promisify
const commandsToSkipSet = new Set(['multi']);
// this is the set of commands to promisify
const commandSet = new Set(commands.filter(c => !commandsToSkipSet.has(c)));
AsyncRedis.createClient = (...args) => new AsyncRedis(args);

AsyncRedis.decorate = redisClient => objectDecorator(redisClient, (name, method) => {
if (commandSet.has(name)) {
return (...args) => new Promise((resolve, reject) => {
args.push((error, ...results) => {
if (error) {
reject(error, ...results);
} else {
resolve(...results);
}
});
method.apply(redisClient, args);
});
}
return method;
});
AsyncRedis.decorate = (redisClient) => {
const asyncClient = new AsyncRedis();
asyncClient.setup(redisClient);
return asyncClient;
};

module.exports = AsyncRedis;
Loading