Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

koatty_store

Package Overview
Dependencies
Maintainers
1
Versions
29
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

koatty_store - npm Package Compare versions

Comparing version 1.5.4 to 1.5.5

.rollup.config.js

2

CHANGELOG.md

@@ -5,2 +5,4 @@ # Changelog

### [1.5.5](https://github.com/koatty/koatty_store/compare/v1.5.4...v1.5.5) (2022-05-27)
### [1.5.4](https://github.com/koatty/koatty_store/compare/v1.5.2...v1.5.4) (2021-12-02)

@@ -7,0 +9,0 @@

@@ -1,4 +0,12 @@

import { CacheStore } from "./store";
export { MemoryStore } from "./store/memory";
export { CacheStore } from "./store";
/*!
* @Author: richen
* @Date: 2022-05-27 10:34:41
* @License: BSD (3-Clause)
* @Copyright (c) - <richenlin(at)gmail.com>
* @HomePage: https://koatty.org/
*/
/// <reference types="node" />
import { EventEmitter } from 'events';
/**

@@ -8,5 +16,829 @@ *

* @export
* @class Store
*/
export declare class CacheStore {
client: any;
pool: any;
options: StoreOptions;
/**
* Creates an instance of CacheStore.
* @param {StoreOptions} options
* @memberof CacheStore
*/
constructor(options: StoreOptions);
getConnection(): void;
close(): Promise<void>;
release(conn: any): Promise<void>;
defineCommand(name: string, scripts: any): void;
getCompare(name: string, value: string | number): Promise<any>;
/**
* handler for native client
*
* @param {string} name
* @param {any[]} data
* @returns {*}
* @memberof RedisStore
*/
/**
* 字符串获取
* @param name
*/
get(name: string): Promise<any>;
/**
* 字符串写入
* @param name
* @param value
* @param timeout
* @returns {Promise}
*/
set(name: string, value: string | number, timeout?: number): Promise<any>;
/**
* 以秒为单位,返回给定 key 的剩余生存时间
* @param name
* @returns {*}
*/
ttl(name: string): Promise<any>;
/**
* 设置key超时属性
* @param name
* @param timeout
*/
expire(name: string, timeout?: number): Promise<any>;
/**
* 删除key
* @param name
*/
rm(name: string): Promise<any>;
/**
*
*
* @param {*} name
* @returns
*/
del(name: string): Promise<any>;
/**
* 判断key是否存在
* @param name
*/
exists(name: string): Promise<any>;
/**
* 自增
* @param name
*/
incr(name: string): Promise<any>;
/**
* 自减
* @param name
* @returns {*}
*/
decr(name: string): Promise<any>;
/**
* 将 key 所储存的值增加增量
* @param name
* @param incr
* @returns {*}
*/
incrby(name: string, incr?: number): Promise<any>;
/**
* 将 key 所储存的值减去减量
*
* @param {any} name
* @param {any} decr
*/
decrby(name: string, decr?: number): Promise<any>;
/**
* 哈希写入
* @param name
* @param key
* @param value
* @param timeout
*/
hset(name: string, key: string, value: string | number, timeout?: number): Promise<any[]>;
/**
* 哈希获取
* @param name
* @param key
* @returns {*}
*/
hget(name: string, key: string): Promise<any>;
/**
* 查看哈希表 hashKey 中,给定域 key 是否存在
* @param name
* @param key
* @returns {*}
*/
hexists(name: string, key: string): Promise<any>;
/**
* 哈希删除
* @param name
* @param key
* @returns {*}
*/
hdel(name: string, key: string): Promise<any[]>;
/**
* 返回哈希表 key 中域的数量
* @param name
* @returns {*}
*/
hlen(name: string): Promise<any>;
/**
* 给哈希表指定key,增加increment
* @param name
* @param key
* @param incr
* @returns {*}
*/
hincrby(name: string, key: string, incr?: number): Promise<any>;
/**
* 返回哈希表所有key-value
* @param name
* @returns {*}
*/
hgetall(name: string): Promise<any>;
/**
* 返回哈希表所有key
* @param name
* @returns {*}
*/
hkeys(name: string): Promise<any>;
/**
* 返回哈希表所有value
* @param name
* @returns {*}
*/
hvals(name: string): Promise<any>;
/**
* 判断列表长度,若不存在则表示为空
* @param name
* @returns {*}
*/
llen(name: string): Promise<any>;
/**
* 将值插入列表表尾
* @param name
* @param value
* @returns {*}
*/
rpush(name: string, value: string | number): Promise<any>;
/**
*
*
* @param {string} name
* @param {(string | number)} value
* @returns {*}
* @memberof RedisStore
*/
lpush(name: string, value: string | number): Promise<any>;
/**
* 将列表表头取出,并去除
* @param name
* @returns {*}
*/
lpop(name: string): Promise<any>;
/**
*
*
* @param {string} name
* @returns {*}
* @memberof RedisStore
*/
rpop(name: string): Promise<any>;
/**
* 返回列表 key 中指定区间内的元素,区间以偏移量 start 和 stop 指定
* @param name
* @param start
* @param stop
* @returns {*}
*/
lrange(name: string, start: number, stop: number): Promise<any>;
/**
* 集合新增
* @param name
* @param value
* @param timeout
* @returns {*}
*/
sadd(name: string, value: string | number, timeout?: number): Promise<any[]>;
/**
* 返回集合的基数(集合中元素的数量)
* @param name
* @returns {*}
*/
scard(name: string): Promise<any>;
/**
* 判断 member 元素是否集合的成员
* @param name
* @param key
* @returns {*}
*/
sismember(name: string, key: string): Promise<any>;
/**
* 返回集合中的所有成员
* @param name
* @returns {*}
*/
smembers(name: string): Promise<any>;
/**
* 移除并返回集合中的一个随机元素
* @param name
* @returns {*}
*/
spop(name: string): Promise<any>;
/**
* 移除集合 key 中的一个 member 元素
* @param name
* @param key
* @returns {*}
*/
srem(name: string, key: string): Promise<any>;
/**
* 将 member 元素从 source 集合移动到 destination 集合
* @param source
* @param destination
* @param member
* @returns {*}
*/
smove(source: string, destination: string, member: string): Promise<any>;
}
declare class MemoryCache extends EventEmitter {
options: MemoryCacheOptions;
currentDBIndex: number;
connected: boolean;
lastSave: number;
multiMode: boolean;
/**
* Creates an instance of MemoryCache.
* @param {*} options
* @memberof MemoryCache
*/
constructor(options: MemoryCacheOptions);
/**
*
*
* @returns {*}
* @memberof MemoryCache
*/
createClient(): this;
/**
*
*
* @returns {*}
* @memberof MemoryCache
*/
quit(): this;
/**
*
*
* @returns {*}
* @memberof MemoryCache
*/
end(): this;
/**
*
*
* @param {string} message
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
echo(message: string, callback?: Function): any;
/**
*
*
* @param {string} message
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
ping(message: string, callback?: Function): any;
/**
*
*
* @param {string} password
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
auth(password: string, callback?: Function): any;
/**
*
*
* @param {number} dbIndex
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
select(dbIndex: number, callback?: Function): any;
get(key: string, callback?: Function): any;
/**
* set(key, value, ttl, pttl, notexist, onlyexist, callback)
*
* @param {string} key
* @param {(string | number)} value
* @param {...any[]} params
* @returns {*}
* @memberof MemoryCache
*/
set(key: string, value: string | number, ...params: any[]): any;
/**
*
*
* @param {string} key
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
ttl(key: string, callback?: Function): any;
/**
*
*
* @param {string} key
* @param {number} seconds
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
expire(key: string, seconds: number, callback?: Function): any;
/**
*
*
* @param {...any[]} keys
* @returns {*}
* @memberof MemoryCache
*/
del(...keys: any[]): any;
/**
*
*
* @param {...any[]} keys
* @returns {*}
* @memberof MemoryCache
*/
exists(...keys: any[]): any;
/**
*
*
* @param {string} key
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
incr(key: string, callback?: Function): any;
/**
*
*
* @param {string} key
* @param {number} amount
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
incrby(key: string, amount: number, callback?: Function): any;
/**
*
*
* @param {string} key
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
decr(key: string, callback?: Function): any;
/**
*
*
* @param {string} key
* @param {number} amount
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
decrby(key: string, amount: number, callback?: Function): any;
hset(key: string, field: string, value: string | number, callback?: Function): any;
/**
*
*
* @param {string} key
* @param {string} field
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
hget(key: string, field: string, callback?: Function): any;
/**
*
*
* @param {string} key
* @param {string} field
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
hexists(key: string, field: string, callback?: Function): any;
/**
*
*
* @param {string} key
* @param {...any[]} fields
* @returns {*}
* @memberof MemoryCache
*/
hdel(key: string, ...fields: any[]): any;
/**
*
*
* @param {string} key
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
hlen(key: string, callback?: Function): any;
/**
*
*
* @param {string} key
* @param {string} field
* @param {*} value
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
hincrby(key: string, field: string, value: any, callback?: Function): any;
/**
*
*
* @param {string} key
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
hgetall(key: string, callback?: Function): any;
/**
*
*
* @param {string} key
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
hkeys(key: string, callback?: Function): any;
/**
*
*
* @param {string} key
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
hvals(key: string, callback?: Function): any;
/**
*
*
* @param {string} key
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
llen(key: string, callback?: Function): any;
/**
*
*
* @param {string} key
* @param {(string | number)} value
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
rpush(key: string, value: string | number, callback?: Function): any;
/**
*
*
* @param {string} key
* @param {(string | number)} value
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
lpush(key: string, value: string | number, callback?: Function): any;
/**
*
*
* @param {string} key
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
lpop(key: string, callback?: Function): any;
/**
*
*
* @param {string} key
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
rpop(key: string, callback?: Function): any;
/**
*
*
* @param {string} key
* @param {number} start
* @param {number} stop
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
lrange(key: string, start: number, stop: number, callback?: Function): any;
/**
*
*
* @param {string} key
* @param {...any[]} members
* @returns {*}
* @memberof MemoryCache
*/
sadd(key: string, ...members: string[]): any;
/**
*
*
* @param {string} key
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
scard(key: string, callback?: Function): any;
/**
*
*
* @param {string} key
* @param {string} member
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
sismember(key: string, member: string, callback?: Function): any;
/**
*
*
* @param {string} key
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
smembers(key: string, callback?: Function): any;
/**
*
*
* @param {string} key
* @param {number} [count]
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
spop(key: string, count?: number, callback?: Function): any;
/**
*
*
* @param {string} key
* @param {...any[]} members
* @returns {*}
* @memberof MemoryCache
*/
srem(key: string, ...members: any[]): any;
/**
*
*
* @param {string} sourcekey
* @param {string} destkey
* @param {string} member
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
smove(sourcekey: string, destkey: string, member: string, callback?: Function): any;
discard(callback?: Function, silent?: boolean): any;
/**
*
*
* @param {string} key
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
/**
*
*
* @private
* @param {string} key
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
/**
*
*
* @private
* @param {string} key
* @returns {*} {boolean}
* @memberof MemoryCache
*/
/**
*
*
* @private
* @param {*} value
* @param {string} type
* @param {number} timeout
* @returns {*}
* @memberof MemoryCache
*/
/**
*
*
* @private
* @param {string} key
* @returns {*}
* @memberof MemoryCache
*/
/**
*
*
* @private
* @param {string} key
* @param {number} amount
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
/**
*
*
* @private
* @param {string} key
* @param {string} type
* @param {boolean} [throwError]
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
/**
*
*
* @private
* @param {string} key
* @returns {*}
* @memberof MemoryCache
*/
/**
*
*
* @private
* @param {string} key
* @param {(number | string)} value
* @memberof MemoryCache
*/
/**
*
*
* @private
* @param {string} key
* @param {string} field
* @param {number} [amount]
* @param {boolean} [useFloat]
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
/**
*
*
* @private
* @param {string} key
* @param {string} field
* @returns {*}
* @memberof MemoryCache
*/
/**
*
*
* @private
* @param {string} key
* @param {string} field
* @returns {*} {boolean}
* @memberof MemoryCache
*/
/**
*
*
* @param {string} key
* @param {string} field
* @param {*} value
* @memberof MemoryCache
*/
_setField(key: string, field: string, value: any): void;
/**
*
*
* @private
* @param {Function} [callback]
* @param {(any)} [message]
* @param {*} [error]
* @param {boolean} [nolog]
* @returns {*}
* @memberof MemoryCache
*/
/**
*
*
* @private
* @param {any[]} [params]
* @returns {*}
* @memberof MemoryCache
*/
}
/**
*
*
* @interface MemoryCacheOptions
*/
declare interface MemoryCacheOptions {
database: number;
}
export declare class MemoryStore extends CacheStore {
client: any;
pool: any;
options: StoreOptions;
/**
* Creates an instance of MemoryStore.
* @param {StoreOptions} options
* @memberof MemoryStore
*/
constructor(options: StoreOptions);
/**
* getConnection
*
* @returns {*}
* @memberof MemoryStore
*/
getConnection(): MemoryCache;
/**
* close
*
* @returns {*} {Promise<void>}
* @memberof MemoryStore
*/
close(): Promise<void>;
/**
* release
*
* @param {*} conn
* @returns {*} {Promise<void>}
* @memberof MemoryStore
*/
release(conn: any): Promise<void>;
/**
* defineCommand
*
* @param {string} name
* @param {*} scripts
* @memberof MemoryStore
*/
defineCommand(name: string, scripts: any): Promise<void>;
/**
* get and compare value
*
* @param {string} name
* @param {(string | number)} value
* @returns {*} {Promise<any>}
* @memberof MemoryStore
*/
getCompare(name: string, value: string | number): Promise<any>;
}
/**
*
*
* @export
* @class Store
*/
export declare class Store {
/**
*
*
* @static
* @returns
* @memberof ValidateUtil
*/
static getInstance(options: StoreOptions): CacheStore;
}
/**
*
*
* @export
* @interface StoreOptions
*/
export interface StoreOptions {
export declare interface StoreOptions {
type?: string;

@@ -34,18 +866,3 @@ keyPrefix?: string;

}
/**
*
*
* @export
* @class Store
*/
export declare class Store {
private static instance;
/**
*
*
* @static
* @returns
* @memberof ValidateUtil
*/
static getInstance(options: StoreOptions): CacheStore;
}
export { }

@@ -1,11 +0,50 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Store = exports.CacheStore = exports.MemoryStore = void 0;
const memory_1 = require("./store/memory");
const redis_1 = require("./store/redis");
var memory_2 = require("./store/memory");
Object.defineProperty(exports, "MemoryStore", { enumerable: true, get: function () { return memory_2.MemoryStore; } });
// export
var store_1 = require("./store");
Object.defineProperty(exports, "CacheStore", { enumerable: true, get: function () { return store_1.CacheStore; } });
/*!
* @Author: richen
* @Date: 2022-05-27 10:34:28
* @License: BSD (3-Clause)
* @Copyright (c) - <richenlin(at)gmail.com>
* @HomePage: https://koatty.org/
*/
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var lodash = require('lodash');
var helper = require('koatty_lib');
var events = require('events');
var koatty_logger = require('koatty_logger');
var IORedis = require('ioredis');
var genericPool = require('generic-pool');
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
function _interopNamespace(e) {
if (e && e.__esModule) return e;
var n = Object.create(null);
if (e) {
Object.keys(e).forEach(function (k) {
if (k !== 'default') {
var d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: function () { return e[k]; }
});
}
});
}
n["default"] = e;
return Object.freeze(n);
}
var helper__namespace = /*#__PURE__*/_interopNamespace(helper);
var IORedis__default = /*#__PURE__*/_interopDefaultLegacy(IORedis);
var genericPool__default = /*#__PURE__*/_interopDefaultLegacy(genericPool);
/*
* @Description:
* @Usage:
* @Author: richen
* @Date: 2021-12-02 15:26:55
* @LastEditTime: 2021-12-02 15:33:22
*/
/**

@@ -17,2 +56,1823 @@ *

*/
class CacheStore {
/**
* Creates an instance of CacheStore.
* @param {StoreOptions} options
* @memberof CacheStore
*/
constructor(options) {
this.options = options;
this.pool = null;
this.client = null;
}
getConnection() {
throw new Error("Method not implemented.");
}
close() {
throw new Error("Method not implemented.");
}
release(conn) {
throw new Error("Method not implemented.");
}
defineCommand(name, scripts) {
throw new Error("Method not implemented.");
}
getCompare(name, value) {
throw new Error("Method not implemented.");
}
/**
* handler for native client
*
* @param {string} name
* @param {any[]} data
* @returns {*}
* @memberof RedisStore
*/
async wrap(name, data) {
let conn;
try {
conn = await this.getConnection();
const res = await conn[name](...data);
return res;
}
catch (err) {
throw err;
}
finally {
this.release(conn);
}
}
/**
* 字符串获取
* @param name
*/
get(name) {
return this.wrap('get', [`${this.options.keyPrefix}${name}`]);
}
/**
* 字符串写入
* @param name
* @param value
* @param timeout
* @returns {Promise}
*/
set(name, value, timeout) {
if (typeof timeout !== 'number') {
timeout = this.options.timeout;
}
return this.wrap('set', [`${this.options.keyPrefix}${name}`, value, 'ex', timeout]);
}
/**
* 以秒为单位,返回给定 key 的剩余生存时间
* @param name
* @returns {*}
*/
ttl(name) {
return this.wrap('ttl', [`${this.options.keyPrefix}${name}`]);
}
/**
* 设置key超时属性
* @param name
* @param timeout
*/
expire(name, timeout) {
return this.wrap('expire', [`${this.options.keyPrefix}${name}`, timeout]);
}
/**
* 删除key
* @param name
*/
rm(name) {
return this.wrap('del', [`${this.options.keyPrefix}${name}`]);
}
/**
*
*
* @param {*} name
* @returns
*/
del(name) {
return this.wrap('del', [`${this.options.keyPrefix}${name}`]);
}
/**
* 判断key是否存在
* @param name
*/
exists(name) {
return this.wrap('exists', [`${this.options.keyPrefix}${name}`]);
}
/**
* 自增
* @param name
*/
incr(name) {
return this.wrap('incr', [`${this.options.keyPrefix}${name}`]);
}
/**
* 自减
* @param name
* @returns {*}
*/
decr(name) {
return this.wrap('decr', [`${this.options.keyPrefix}${name}`]);
}
/**
* 将 key 所储存的值增加增量
* @param name
* @param incr
* @returns {*}
*/
incrby(name, incr = 1) {
return this.wrap('incrby', [`${this.options.keyPrefix}${name}`, incr]);
}
/**
* 将 key 所储存的值减去减量
*
* @param {any} name
* @param {any} decr
*/
decrby(name, decr = 1) {
return this.wrap('decrby', [`${this.options.keyPrefix}${name}`, decr]);
}
/**
* 哈希写入
* @param name
* @param key
* @param value
* @param timeout
*/
hset(name, key, value, timeout) {
const setP = [this.wrap('hset', [`${this.options.keyPrefix}${name}`, key, value])];
if (typeof timeout !== 'number') {
timeout = this.options.timeout;
}
setP.push(this.set(`${name}:${key}_ex`, 1, timeout));
return Promise.all(setP);
}
/**
* 哈希获取
* @param name
* @param key
* @returns {*}
*/
hget(name, key) {
const setP = [this.get(`${name}:${key}_ex`)];
setP.push(this.wrap('hget', [`${this.options.keyPrefix}${name}`, key]));
return Promise.all(setP).then(dataArr => {
if (dataArr[0] === null) {
this.hdel(name, key);
return null;
}
return dataArr[1] || null;
});
}
/**
* 查看哈希表 hashKey 中,给定域 key 是否存在
* @param name
* @param key
* @returns {*}
*/
hexists(name, key) {
const setP = [this.get(`${name}:${key}_ex`)];
setP.push(this.wrap('hexists', [`${this.options.keyPrefix}${name}`, key]));
return Promise.all(setP).then(dataArr => {
if (dataArr[0] === null) {
this.hdel(name, key);
return 0;
}
return dataArr[1] || 0;
});
}
/**
* 哈希删除
* @param name
* @param key
* @returns {*}
*/
hdel(name, key) {
const setP = [this.del(`${name}:${key}_ex`)];
setP.push(this.wrap('hdel', [`${this.options.keyPrefix}${name}`, key]));
return Promise.all(setP);
}
/**
* 返回哈希表 key 中域的数量
* @param name
* @returns {*}
*/
hlen(name) {
return this.wrap('hlen', [`${this.options.keyPrefix}${name}`]);
}
/**
* 给哈希表指定key,增加increment
* @param name
* @param key
* @param incr
* @returns {*}
*/
hincrby(name, key, incr = 1) {
return this.wrap('hincrby', [`${this.options.keyPrefix}${name}`, key, incr]);
}
/**
* 返回哈希表所有key-value
* @param name
* @returns {*}
*/
hgetall(name) {
return this.wrap('hgetall', [`${this.options.keyPrefix}${name}`]);
}
/**
* 返回哈希表所有key
* @param name
* @returns {*}
*/
hkeys(name) {
return this.wrap('hkeys', [`${this.options.keyPrefix}${name}`]);
}
/**
* 返回哈希表所有value
* @param name
* @returns {*}
*/
hvals(name) {
return this.wrap('hvals', [`${this.options.keyPrefix}${name}`]);
}
/**
* 判断列表长度,若不存在则表示为空
* @param name
* @returns {*}
*/
llen(name) {
return this.wrap('llen', [`${this.options.keyPrefix}${name}`]);
}
/**
* 将值插入列表表尾
* @param name
* @param value
* @returns {*}
*/
rpush(name, value) {
return this.wrap('rpush', [`${this.options.keyPrefix}${name}`, value]);
}
/**
*
*
* @param {string} name
* @param {(string | number)} value
* @returns {*}
* @memberof RedisStore
*/
lpush(name, value) {
return this.wrap('lpush', [`${this.options.keyPrefix}${name}`, value]);
}
/**
* 将列表表头取出,并去除
* @param name
* @returns {*}
*/
lpop(name) {
return this.wrap('lpop', [`${this.options.keyPrefix}${name}`]);
}
/**
*
*
* @param {string} name
* @returns {*}
* @memberof RedisStore
*/
rpop(name) {
return this.wrap('rpop', [`${this.options.keyPrefix}${name}`]);
}
/**
* 返回列表 key 中指定区间内的元素,区间以偏移量 start 和 stop 指定
* @param name
* @param start
* @param stop
* @returns {*}
*/
lrange(name, start, stop) {
return this.wrap('lrange', [`${this.options.keyPrefix}${name}`, start, stop]);
}
/**
* 集合新增
* @param name
* @param value
* @param timeout
* @returns {*}
*/
sadd(name, value, timeout) {
const setP = [this.wrap('sadd', [`${this.options.keyPrefix}${name}`, value])];
if (typeof timeout !== 'number') {
setP.push(this.wrap('expire', [`${this.options.keyPrefix}${name}`, timeout]));
}
return Promise.all(setP);
}
/**
* 返回集合的基数(集合中元素的数量)
* @param name
* @returns {*}
*/
scard(name) {
return this.wrap('scard', [`${this.options.keyPrefix}${name}`]);
}
/**
* 判断 member 元素是否集合的成员
* @param name
* @param key
* @returns {*}
*/
sismember(name, key) {
return this.wrap('sismember', [`${this.options.keyPrefix}${name}`, key]);
}
/**
* 返回集合中的所有成员
* @param name
* @returns {*}
*/
smembers(name) {
return this.wrap('smembers', [`${this.options.keyPrefix}${name}`]);
}
/**
* 移除并返回集合中的一个随机元素
* @param name
* @returns {*}
*/
spop(name) {
return this.wrap('spop', [`${this.options.keyPrefix}${name}`]);
}
/**
* 移除集合 key 中的一个 member 元素
* @param name
* @param key
* @returns {*}
*/
srem(name, key) {
return this.wrap('srem', [`${this.options.keyPrefix}${name}`, key]);
}
/**
* 将 member 元素从 source 集合移动到 destination 集合
* @param source
* @param destination
* @param member
* @returns {*}
*/
smove(source, destination, member) {
return this.wrap('smove', [`${this.options.keyPrefix}${source}`, `${this.options.keyPrefix}${destination}`, member]);
}
}
/*
* @Description:
* @Usage:
* @Author: richen
* @Date: 2021-12-02 11:03:20
* @LastEditTime: 2021-12-02 14:36:11
*/
/**
*
*
* @enum {number}
*/
var messages;
(function (messages) {
messages["ok"] = "OK";
messages["queued"] = "QUEUED";
messages["pong"] = "PONG";
messages["noint"] = "ERR value is not an integer or out of range";
messages["nofloat"] = "ERR value is not an float or out of range";
messages["nokey"] = "ERR no such key";
messages["nomultiinmulti"] = "ERR MULTI calls can not be nested";
messages["nomultiexec"] = "ERR EXEC without MULTI";
messages["nomultidiscard"] = "ERR DISCARD without MULTI";
messages["busykey"] = "ERR target key name is busy";
messages["syntax"] = "ERR syntax error";
messages["unsupported"] = "MemoryCache does not support that operation";
messages["wrongTypeOp"] = "WRONGTYPE Operation against a key holding the wrong kind of value";
messages["wrongPayload"] = "DUMP payload version or checksum are wrong";
messages["wrongArgCount"] = "ERR wrong number of arguments for '%0' command";
messages["bitopnotWrongCount"] = "ERR BITOP NOT must be called with a single source key";
messages["indexOutOfRange"] = "ERR index out of range";
messages["invalidLexRange"] = "ERR min or max not valid string range item";
messages["invalidDBIndex"] = "ERR invalid DB index";
messages["invalidDBIndexNX"] = "ERR invalid DB index, '%0' does not exist";
messages["mutuallyExclusiveNXXX"] = "ERR XX and NX options at the same time are not compatible";
})(messages || (messages = {}));
class MemoryCache extends events.EventEmitter {
/**
* Creates an instance of MemoryCache.
* @param {*} options
* @memberof MemoryCache
*/
constructor(options) {
super();
this.databases = Object.create({});
this.options = { ...{ database: "0" }, ...options };
this.currentDBIndex = 0;
this.connected = false;
this.lastSave = Date.now();
this.multiMode = false;
}
/**
*
*
* @returns {*}
* @memberof MemoryCache
*/
createClient() {
this.databases[this.options.database] = Object.create({});
this.cache = this.databases[this.options.database];
this.connected = true;
// exit multi mode if we are in it
this.discard(null, true);
this.emit('connect');
this.emit('ready');
return this;
}
/**
*
*
* @returns {*}
* @memberof MemoryCache
*/
quit() {
this.connected = false;
// exit multi mode if we are in it
this.discard(null, true);
this.emit('end');
return this;
}
/**
*
*
* @returns {*}
* @memberof MemoryCache
*/
end() {
return this.quit();
}
/**
*
*
* @param {string} message
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
echo(message, callback) {
return this._handleCallback(callback, message);
}
/**
*
*
* @param {string} message
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
ping(message, callback) {
message = message || messages.pong;
return this._handleCallback(callback, message);
}
/**
*
*
* @param {string} password
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
auth(password, callback) {
return this._handleCallback(callback, messages.ok);
}
/**
*
*
* @param {number} dbIndex
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
select(dbIndex, callback) {
if (!helper__namespace.isNumber(dbIndex)) {
return this._handleCallback(callback, null, messages.invalidDBIndex);
}
if (!this.databases.hasOwnProperty(dbIndex)) {
this.databases[dbIndex] = Object.create({});
}
this.multiMode = false;
this.currentDBIndex = dbIndex;
this.cache = this.databases[dbIndex];
return this._handleCallback(callback, messages.ok);
}
// ---------------------------------------
// Keys
// ---------------------------------------
get(key, callback) {
let retVal = null;
if (this._hasKey(key)) {
this._testType(key, 'string', true, callback);
retVal = this._getKey(key);
}
return this._handleCallback(callback, retVal);
}
/**
* set(key, value, ttl, pttl, notexist, onlyexist, callback)
*
* @param {string} key
* @param {(string | number)} value
* @param {...any[]} params
* @returns {*}
* @memberof MemoryCache
*/
set(key, value, ...params) {
const retVal = null;
params = lodash.flatten(params);
const callback = this._retrieveCallback(params);
let ttl, pttl, notexist, onlyexist;
// parse parameters
while (params.length > 0) {
const param = params.shift();
switch (param.toString().toLowerCase()) {
case 'nx':
notexist = true;
break;
case 'xx':
onlyexist = true;
break;
case 'ex':
if (params.length === 0) {
return this._handleCallback(callback, null, messages.syntax);
}
ttl = parseInt(params.shift());
if (isNaN(ttl)) {
return this._handleCallback(callback, null, messages.noint);
}
break;
case 'px':
if (params.length === 0) {
return this._handleCallback(callback, null, messages.syntax);
}
pttl = parseInt(params.shift());
if (isNaN(pttl)) {
return this._handleCallback(callback, null, messages.noint);
}
break;
default:
return this._handleCallback(callback, null, messages.syntax);
}
}
if (!lodash.isNil(ttl) && !lodash.isNil(pttl)) {
return this._handleCallback(callback, null, messages.syntax);
}
if (notexist && onlyexist) {
return this._handleCallback(callback, null, messages.syntax);
}
pttl = pttl || ttl * 1000 || null;
if (!lodash.isNil(pttl)) {
pttl = Date.now() + pttl;
}
if (this._hasKey(key)) {
this._testType(key, 'string', true, callback);
if (notexist) {
return this._handleCallback(callback, retVal);
}
}
else if (onlyexist) {
return this._handleCallback(callback, retVal);
}
this.cache[key] = this._makeKey(value.toString(), 'string', pttl);
return this._handleCallback(callback, messages.ok);
}
/**
*
*
* @param {string} key
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
ttl(key, callback) {
let retVal = this.pttl(key);
if (retVal >= 0 || retVal <= -3) {
retVal = Math.floor(retVal / 1000);
}
return this._handleCallback(callback, retVal);
}
/**
*
*
* @param {string} key
* @param {number} seconds
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
expire(key, seconds, callback) {
let retVal = 0;
if (this._hasKey(key)) {
this.cache[key].timeout = Date.now() + seconds * 1000;
retVal = 1;
}
return this._handleCallback(callback, retVal);
}
/**
*
*
* @param {...any[]} keys
* @returns {*}
* @memberof MemoryCache
*/
del(...keys) {
let retVal = 0;
const callback = this._retrieveCallback(keys);
// Flatten the array in case an array was passed
keys = lodash.flatten(keys);
for (let itr = 0; itr < keys.length; itr++) {
const key = keys[itr];
if (this._hasKey(key)) {
delete this.cache[key];
retVal++;
}
}
return this._handleCallback(callback, retVal);
}
/**
*
*
* @param {...any[]} keys
* @returns {*}
* @memberof MemoryCache
*/
exists(...keys) {
let retVal = 0;
const callback = this._retrieveCallback(keys);
for (let itr = 0; itr < keys.length; itr++) {
const key = keys[itr];
if (this._hasKey(key)) {
retVal++;
}
}
return this._handleCallback(callback, retVal);
}
/**
*
*
* @param {string} key
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
incr(key, callback) {
let retVal = null;
try {
retVal = this._addToKey(key, 1);
}
catch (err) {
return this._handleCallback(callback, null, err);
}
return this._handleCallback(callback, retVal);
}
/**
*
*
* @param {string} key
* @param {number} amount
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
incrby(key, amount, callback) {
let retVal = null;
try {
retVal = this._addToKey(key, amount);
}
catch (err) {
return this._handleCallback(callback, null, err);
}
return this._handleCallback(callback, retVal);
}
/**
*
*
* @param {string} key
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
decr(key, callback) {
let retVal = null;
try {
retVal = this._addToKey(key, -1);
}
catch (err) {
return this._handleCallback(callback, null, err);
}
return this._handleCallback(callback, retVal);
}
/**
*
*
* @param {string} key
* @param {number} amount
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
decrby(key, amount, callback) {
let retVal = null;
try {
retVal = this._addToKey(key, -amount);
}
catch (err) {
return this._handleCallback(callback, null, err);
}
return this._handleCallback(callback, retVal);
}
// ---------------------------------------
// ## Hash ##
// ---------------------------------------
hset(key, field, value, callback) {
let retVal = 0;
if (this._hasKey(key)) {
this._testType(key, 'hash', true, callback);
}
else {
this.cache[key] = this._makeKey({}, 'hash');
}
if (!this._hasField(key, field)) {
retVal = 1;
}
this._setField(key, field, value.toString());
this.persist(key);
return this._handleCallback(callback, retVal);
}
/**
*
*
* @param {string} key
* @param {string} field
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
hget(key, field, callback) {
let retVal = null;
if (this._hasKey(key)) {
this._testType(key, 'hash', true, callback);
if (this._hasField(key, field)) {
retVal = this._getKey(key)[field];
}
}
return this._handleCallback(callback, retVal);
}
/**
*
*
* @param {string} key
* @param {string} field
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
hexists(key, field, callback) {
let retVal = 0;
if (this._hasKey(key)) {
this._testType(key, 'hash', true, callback);
if (this._hasField(key, field)) {
retVal = 1;
}
}
return this._handleCallback(callback, retVal);
}
/**
*
*
* @param {string} key
* @param {...any[]} fields
* @returns {*}
* @memberof MemoryCache
*/
hdel(key, ...fields) {
let retVal = 0;
const callback = this._retrieveCallback(fields);
if (this._hasKey(key)) {
this._testType(key, 'hash', true, callback);
for (let itr = 0; itr < fields.length; itr++) {
const field = fields[itr];
if (this._hasField(key, field)) {
delete this.cache[key].value[field];
retVal++;
}
}
}
return this._handleCallback(callback, retVal);
}
/**
*
*
* @param {string} key
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
hlen(key, callback) {
const retVal = this.hkeys(key).length;
return this._handleCallback(callback, retVal);
}
/**
*
*
* @param {string} key
* @param {string} field
* @param {*} value
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
hincrby(key, field, value, callback) {
let retVal;
try {
retVal = this._addToField(key, field, value, false);
}
catch (err) {
return this._handleCallback(callback, null, err);
}
return this._handleCallback(callback, retVal);
}
/**
*
*
* @param {string} key
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
hgetall(key, callback) {
let retVals = {};
if (this._hasKey(key)) {
this._testType(key, 'hash', true, callback);
retVals = this._getKey(key);
}
return this._handleCallback(callback, retVals);
}
/**
*
*
* @param {string} key
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
hkeys(key, callback) {
let retVals = [];
if (this._hasKey(key)) {
this._testType(key, 'hash', true, callback);
retVals = Object.keys(this._getKey(key));
}
return this._handleCallback(callback, retVals);
}
/**
*
*
* @param {string} key
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
hvals(key, callback) {
let retVals = [];
if (this._hasKey(key)) {
this._testType(key, 'hash', true, callback);
retVals = Object.values(this._getKey(key));
}
return this._handleCallback(callback, retVals);
}
// ---------------------------------------
// Lists (Array / Queue / Stack)
// ---------------------------------------
/**
*
*
* @param {string} key
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
llen(key, callback) {
let retVal = 0;
if (this._hasKey(key)) {
this._testType(key, 'list', true, callback);
retVal = this._getKey(key).length || 0;
}
return this._handleCallback(callback, retVal);
}
/**
*
*
* @param {string} key
* @param {(string | number)} value
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
rpush(key, value, callback) {
let retVal = 0;
if (this._hasKey(key)) {
this._testType(key, 'list', true, callback);
}
else {
this.cache[key] = this._makeKey([], 'list');
}
const val = this._getKey(key);
val.push(value);
this._setKey(key, val);
retVal = val.length;
return this._handleCallback(callback, retVal);
}
/**
*
*
* @param {string} key
* @param {(string | number)} value
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
lpush(key, value, callback) {
let retVal = 0;
if (this._hasKey(key)) {
this._testType(key, 'list', true, callback);
}
else {
this.cache[key] = this._makeKey([], 'list');
}
const val = this._getKey(key);
val.splice(0, 0, value);
this._setKey(key, val);
retVal = val.length;
return this._handleCallback(callback, retVal);
}
/**
*
*
* @param {string} key
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
lpop(key, callback) {
let retVal = null;
if (this._hasKey(key)) {
this._testType(key, 'list', true, callback);
const val = this._getKey(key);
retVal = val.shift();
this._setKey(key, val);
}
return this._handleCallback(callback, retVal);
}
/**
*
*
* @param {string} key
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
rpop(key, callback) {
let retVal = null;
if (this._hasKey(key)) {
this._testType(key, 'list', true, callback);
const val = this._getKey(key);
retVal = val.pop();
this._setKey(key, val);
}
return this._handleCallback(callback, retVal);
}
/**
*
*
* @param {string} key
* @param {number} start
* @param {number} stop
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
lrange(key, start, stop, callback) {
const retVal = [];
if (this._hasKey(key)) {
this._testType(key, 'list', true, callback);
const val = this._getKey(key);
const length = val.length;
if (stop < 0) {
stop = length + stop;
}
if (start < 0) {
start = length + start;
}
if (start < 0) {
start = 0;
}
if (stop >= length) {
stop = length - 1;
}
if (stop >= 0 && stop >= start) {
const size = stop - start + 1;
for (let itr = start; itr < size; itr++) {
retVal.push(val[itr]);
}
}
}
return this._handleCallback(callback, retVal);
}
// ---------------------------------------
// ## Sets (Unique Lists)##
// ---------------------------------------
/**
*
*
* @param {string} key
* @param {...any[]} members
* @returns {*}
* @memberof MemoryCache
*/
sadd(key, ...members) {
let retVal = 0;
const callback = this._retrieveCallback(members);
if (this._hasKey(key)) {
this._testType(key, 'set', true, callback);
}
else {
this.cache[key] = this._makeKey([], 'set');
}
const val = this._getKey(key);
const length = val.length;
const nval = lodash.union(val, members);
const newlength = nval.length;
retVal = newlength - length;
this._setKey(key, nval);
return this._handleCallback(callback, retVal);
}
/**
*
*
* @param {string} key
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
scard(key, callback) {
let retVal = 0;
if (this._hasKey(key)) {
this._testType(key, 'set', true, callback);
retVal = this._getKey(key).length;
}
return this._handleCallback(callback, retVal);
}
/**
*
*
* @param {string} key
* @param {string} member
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
sismember(key, member, callback) {
let retVal = 0;
if (this._hasKey(key)) {
this._testType(key, 'set', true, callback);
const val = this._getKey(key);
if (val.includes(member)) {
retVal = 1;
}
}
return this._handleCallback(callback, retVal);
}
/**
*
*
* @param {string} key
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
smembers(key, callback) {
let retVal = [];
if (this._hasKey(key)) {
this._testType(key, 'set', true, callback);
retVal = this._getKey(key);
}
return this._handleCallback(callback, retVal);
}
/**
*
*
* @param {string} key
* @param {number} [count]
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
spop(key, count, callback) {
let retVal = null;
count = count || 1;
if (isNaN(count)) {
return this._handleCallback(callback, null, messages.noint);
}
if (this._hasKey(key)) {
retVal = [];
this._testType(key, 'set', true, callback);
const val = this._getKey(key);
const length = val.length;
count = count > length ? length : count;
for (let itr = 0; itr < count; itr++) {
retVal.push(val.pop());
}
}
return this._handleCallback(callback, retVal);
}
/**
*
*
* @param {string} key
* @param {...any[]} members
* @returns {*}
* @memberof MemoryCache
*/
srem(key, ...members) {
let retVal = 0;
const callback = this._retrieveCallback(members);
if (this._hasKey(key)) {
this._testType(key, 'set', true, callback);
const val = this._getKey(key);
for (const index in members) {
if (members.hasOwnProperty(index)) {
const member = members[index];
const idx = val.indexOf(member);
if (idx !== -1) {
val.splice(idx, 1);
retVal++;
}
}
}
this._setKey(key, val);
}
return this._handleCallback(callback, retVal);
}
/**
*
*
* @param {string} sourcekey
* @param {string} destkey
* @param {string} member
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
smove(sourcekey, destkey, member, callback) {
let retVal = 0;
if (this._hasKey(sourcekey)) {
this._testType(sourcekey, 'set', true, callback);
const val = this._getKey(sourcekey);
const idx = val.indexOf(member);
if (idx !== -1) {
this.sadd(destkey, member);
val.splice(idx, 1);
retVal = 1;
}
}
return this._handleCallback(callback, retVal);
}
// ---------------------------------------
// ## Transactions (Atomic) ##
// ---------------------------------------
// TODO: Transaction Queues watch and unwatch
// https://redis.io/topics/transactions
// This can be accomplished by temporarily swapping this.cache to a temporary copy of the current statement
// holding and then using __.merge on actual this.cache with the temp storage.
discard(callback, silent) {
// Clear the queue mode, drain the queue, empty the watch list
if (this.multiMode) {
this.cache = this.databases[this.currentDBIndex];
this.tempCache = {};
this.multiMode = false;
this.responseMessages = [];
}
else if (!silent) {
return this._handleCallback(callback, null, messages.nomultidiscard);
}
return this._handleCallback(callback, messages.ok);
}
// ---------------------------------------
// ## Internal - Key ##
// ---------------------------------------
/**
*
*
* @param {string} key
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
pttl(key, callback) {
let retVal = -2;
if (this._hasKey(key)) {
if (!lodash.isNil(this.cache[key].timeout)) {
retVal = this.cache[key].timeout - Date.now();
// Prevent unexpected errors if the actual ttl just happens to be -2 or -1
if (retVal < 0 && retVal > -3) {
retVal = -3;
}
}
else {
retVal = -1;
}
}
return this._handleCallback(callback, retVal);
}
/**
*
*
* @private
* @param {string} key
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
persist(key, callback) {
let retVal = 0;
if (this._hasKey(key)) {
if (!lodash.isNil(this._key(key).timeout)) {
this._key(key).timeout = null;
retVal = 1;
}
}
return this._handleCallback(callback, retVal);
}
/**
*
*
* @private
* @param {string} key
* @returns {*} {boolean}
* @memberof MemoryCache
*/
_hasKey(key) {
return this.cache.hasOwnProperty(key);
}
/**
*
*
* @private
* @param {*} value
* @param {string} type
* @param {number} timeout
* @returns {*}
* @memberof MemoryCache
*/
_makeKey(value, type, timeout) {
return { value: value, type: type, timeout: timeout || null, lastAccess: Date.now() };
}
/**
*
*
* @private
* @param {string} key
* @returns {*}
* @memberof MemoryCache
*/
_key(key) {
this.cache[key].lastAccess = Date.now();
return this.cache[key];
}
/**
*
*
* @private
* @param {string} key
* @param {number} amount
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
_addToKey(key, amount, callback) {
let keyValue = 0;
if (isNaN(amount) || lodash.isNil(amount)) {
return this._handleCallback(callback, null, messages.noint);
}
if (this._hasKey(key)) {
this._testType(key, 'string', true, callback);
keyValue = parseInt(this._getKey(key));
if (isNaN(keyValue) || lodash.isNil(keyValue)) {
return this._handleCallback(callback, null, messages.noint);
}
}
else {
this.cache[key] = this._makeKey('0', 'string');
}
const val = keyValue + amount;
this._setKey(key, val.toString());
return val;
}
/**
*
*
* @private
* @param {string} key
* @param {string} type
* @param {boolean} [throwError]
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
_testType(key, type, throwError, callback) {
throwError = !!throwError;
const keyType = this._key(key).type;
if (keyType !== type) {
if (throwError) {
return this._handleCallback(callback, null, messages.wrongTypeOp);
}
return false;
}
return true;
}
/**
*
*
* @private
* @param {string} key
* @returns {*}
* @memberof MemoryCache
*/
_getKey(key) {
const _key = this._key(key) || {};
if (_key.timeout && _key.timeout <= Date.now()) {
this.del(key);
return null;
}
return _key.value;
}
/**
*
*
* @private
* @param {string} key
* @param {(number | string)} value
* @memberof MemoryCache
*/
_setKey(key, value) {
this.cache[key].value = value;
this.cache[key].lastAccess = Date.now();
}
/**
*
*
* @private
* @param {string} key
* @param {string} field
* @param {number} [amount]
* @param {boolean} [useFloat]
* @param {Function} [callback]
* @returns {*}
* @memberof MemoryCache
*/
_addToField(key, field, amount, useFloat, callback) {
useFloat = useFloat || false;
let fieldValue = useFloat ? 0.0 : 0;
let value = 0;
if (isNaN(amount) || lodash.isNil(amount)) {
return this._handleCallback(callback, null, useFloat ? messages.nofloat : messages.noint);
}
if (this._hasKey(key)) {
this._testType(key, 'hash', true, callback);
if (this._hasField(key, field)) {
value = this._getField(key, field);
}
}
else {
this.cache[key] = this._makeKey({}, 'hash');
}
fieldValue = useFloat ? parseFloat(`${value}`) : parseInt(`${value}`);
amount = useFloat ? parseFloat(`${amount}`) : parseInt(`${amount}`);
if (isNaN(fieldValue) || lodash.isNil(fieldValue)) {
return this._handleCallback(callback, null, useFloat ? messages.nofloat : messages.noint);
}
fieldValue += amount;
this._setField(key, field, fieldValue.toString());
return fieldValue;
}
/**
*
*
* @private
* @param {string} key
* @param {string} field
* @returns {*}
* @memberof MemoryCache
*/
_getField(key, field) {
return this._getKey(key)[field];
}
/**
*
*
* @private
* @param {string} key
* @param {string} field
* @returns {*} {boolean}
* @memberof MemoryCache
*/
_hasField(key, field) {
let retVal = false;
if (key && field) {
const ky = this._getKey(key);
if (ky) {
retVal = ky.hasOwnProperty(field);
}
}
return retVal;
}
/**
*
*
* @param {string} key
* @param {string} field
* @param {*} value
* @memberof MemoryCache
*/
_setField(key, field, value) {
this._getKey(key)[field] = value;
}
/**
*
*
* @private
* @param {Function} [callback]
* @param {(any)} [message]
* @param {*} [error]
* @param {boolean} [nolog]
* @returns {*}
* @memberof MemoryCache
*/
_handleCallback(callback, message, error, nolog) {
let err = error;
let msg = message;
nolog = lodash.isNil(nolog) ? true : nolog;
if (nolog) {
err = this._logReturn(error);
msg = this._logReturn(message);
}
if (typeof callback === 'function') {
callback(err, msg);
return;
}
if (err) {
throw new Error(err);
}
return msg;
}
_logReturn(message) {
if (!lodash.isUndefined(message)) {
if (this.multiMode) {
if (!lodash.isNil(this.responseMessages)) {
this.responseMessages.push(message);
if (message === messages.ok) {
message = messages.queued;
}
}
}
return message;
}
return;
}
/**
*
*
* @private
* @param {any[]} [params]
* @returns {*}
* @memberof MemoryCache
*/
_retrieveCallback(params) {
if (Array.isArray(params) && params.length > 0 && typeof params[params.length - 1] === 'function') {
return params.pop();
}
return;
}
}
// const MemoryCache = require('@outofsync/memory-cache');
/*
* @Description:
* @Usage:
* @Author: richen
* @Date: 2021-06-29 19:07:57
* @LastEditTime: 2021-12-02 15:30:12
*/
class MemoryStore extends CacheStore {
/**
* Creates an instance of MemoryStore.
* @param {StoreOptions} options
* @memberof MemoryStore
*/
constructor(options) {
super(options);
this.options = options;
this.client = null;
}
/**
* getConnection
*
* @returns {*}
* @memberof MemoryStore
*/
getConnection() {
if (!this.pool) {
this.pool = new MemoryCache({
database: this.options.db
});
}
if (!this.client) {
this.client = this.pool.createClient();
this.client.status = "ready";
}
return this.client;
}
/**
* close
*
* @returns {*} {Promise<void>}
* @memberof MemoryStore
*/
async close() {
this.client.end();
this.client = null;
}
/**
* release
*
* @param {*} conn
* @returns {*} {Promise<void>}
* @memberof MemoryStore
*/
async release(conn) {
return;
}
/**
* defineCommand
*
* @param {string} name
* @param {*} scripts
* @memberof MemoryStore
*/
async defineCommand(name, scripts) {
throw new Error(messages.unsupported);
}
/**
* get and compare value
*
* @param {string} name
* @param {(string | number)} value
* @returns {*} {Promise<any>}
* @memberof MemoryStore
*/
async getCompare(name, value) {
const client = this.getConnection();
const val = client.get(`${this.options.keyPrefix}${name}`);
if (!val) {
return 0;
}
else if (val == value) {
return client.del(`${this.options.keyPrefix}${name}`);
}
else {
return -1;
}
}
}
/*
* @Author: richen
* @Date: 2020-11-30 15:56:08
* @LastEditors: Please set LastEditors
* @LastEditTime: 2021-12-02 15:30:11
* @License: BSD (3-Clause)
* @Copyright (c) - <richenlin(at)gmail.com>
*/
/**
*
*
* @export
* @class RedisStore
*/
class RedisStore extends CacheStore {
/**
* Creates an instance of RedisStore.
* @param {StoreOptions} options
* @memberof RedisStore
*/
constructor(options) {
super(options);
this.options = this.parseOpt(options);
this.pool = null;
this.client = null;
}
// parseOpt
parseOpt(options) {
const opt = {
host: options.host || '127.0.0.1',
port: options.port || 3306,
username: options.username || "",
password: options.password || "",
db: options.db || 0,
timeout: options.timeout,
keyPrefix: options.keyPrefix || '',
poolSize: options.poolSize || 10,
connectTimeout: options.connectTimeout || 500,
};
if (helper__namespace.isArray(options.host)) {
const hosts = [];
for (let i = 0; i < options.host.length; i++) {
const h = options.host[i];
if (!helper__namespace.isEmpty(options.host[i])) {
let p;
if (helper__namespace.isArray(options.port)) {
p = options.port[i];
}
else {
p = options.port || 6379;
}
hosts.push({
host: h,
port: helper__namespace.toNumber(p),
});
}
}
// sentinel
if (!helper__namespace.isEmpty(options.name)) {
opt.host = "";
opt.port = null;
opt.sentinels = [...hosts];
opt.sentinelUsername = options.username;
opt.sentinelPassword = options.password;
}
else {
// cluster
opt.host = "";
opt.port = null;
opt.clusters = [...hosts];
}
}
return opt;
}
/**
* create connection by native
*
* @param {number} [connNum=0]
* @returns {*} {Promise<IORedis.Redis | IORedis.Cluster>}
* @memberof RedisStore
*/
async connect(connNum = 0) {
if (this.client && this.client.status === 'ready') {
return this.client;
}
const defer = helper__namespace.getDefer();
let connection;
if (!helper__namespace.isEmpty(this.options.clusters)) {
connection = new IORedis__default["default"].Cluster([...this.options.clusters], { redisOptions: this.options });
}
else {
connection = new IORedis__default["default"](this.options);
}
connection.on('end', () => {
if (connNum < 3) {
connNum++;
defer.resolve(this.connect(connNum));
}
else {
this.close();
defer.reject('redis connection end');
}
});
connection.on('ready', () => {
this.client = connection;
defer.resolve(connection);
});
return defer.promise;
}
/**
* get connection from pool
*
* @returns {*}
* @memberof RedisStore
*/
getConnection() {
if (!this.pool || !this.pool.acquire) {
const factory = {
create: () => {
return this.connect();
},
destroy: () => {
return this.close();
},
validate: (resource) => {
return Promise.resolve(resource.status === 'ready');
}
};
this.pool = genericPool__default["default"].createPool(factory, {
max: this.options.poolSize || 10,
min: 2 // minimum size of the pool
});
this.pool.on('factoryCreateError', function (err) {
koatty_logger.DefaultLogger.Error(err);
});
this.pool.on('factoryDestroyError', function (err) {
koatty_logger.DefaultLogger.Error(err);
});
}
return this.pool.acquire();
}
/**
* close connection
*
* @returns {*}
* @memberof RedisStore
*/
async close() {
this.client.disconnect();
this.client = null;
this.pool.destroy(this.client);
this.pool = null;
return;
}
/**
*
*
* @param {*} conn
* @returns {*}
* @memberof RedisStore
*/
async release(conn) {
if (this.pool.isBorrowedResource(conn)) {
return this.pool.release(conn);
}
return Promise.resolve();
}
/**
* defineCommand
*
* @param {string} name
* @param {{ numberOfKeys?: number; lua?: string; }} scripts
* @returns {*}
* @memberof RedisStore
*/
async defineCommand(name, scripts) {
const conn = await this.getConnection();
if (!conn[name]) {
conn.defineCommand(name, scripts);
}
return conn;
}
/**
* get and compare value
*
* @param {string} name
* @param {(string | number)} value
* @returns {*} {Promise<any>}
* @memberof RedisStore
*/
async getCompare(name, value) {
let conn;
try {
conn = await this.defineCommand("getCompare", {
numberOfKeys: 1,
lua: `
local remote_value = redis.call("get",KEYS[1])
if (not remote_value) then
return 0
elseif (remote_value == ARGV[1]) then
return redis.call("del",KEYS[1])
else
return -1
end
`
});
return conn.getCompare(name, value);
}
catch (error) {
throw error;
}
finally {
this.release(conn);
}
}
}
/**
*
*
* @export
* @class Store
*/
class Store {

@@ -44,7 +1904,7 @@ /**

case "redis":
this.instance = new redis_1.RedisStore(options);
this.instance = new RedisStore(options);
break;
case "memory":
default:
this.instance = new memory_1.MemoryStore(options);
this.instance = new MemoryStore(options);
break;

@@ -55,3 +1915,5 @@ }

}
exports.CacheStore = CacheStore;
exports.MemoryStore = MemoryStore;
exports.Store = Store;
//# sourceMappingURL=index.js.map

53

package.json
{
"name": "koatty_store",
"version": "1.5.4",
"version": "1.5.5",
"description": "Cache store for koatty.",
"scripts": {
"build": "del-cli --force dist && tsc",
"build": "npm run build:js && npm run build:dts && npm run build:doc && npm run build:cp",
"build:cp": "node scripts/postBuild && copyfiles package.json LICENSE README.md dist/",
"build:js": "del-cli --force dist && npx rollup -c .rollup.config.js",
"build:doc": "del-cli --force docs/api && npx api-documenter markdown --input temp --output docs/api",
"build:dts": "del-cli --force temp && npx tsc && npx api-extractor run --local --verbose",
"eslint": "eslint --ext .ts,.js ./",
"prepublishOnly": "npm test && npm run build",
"release": "npm run prepublishOnly && standard-version",
"pub": "git push --follow-tags origin && npm publish",
"test": "npm run eslint && jest --passWithNoTests",
"test:cov": "jest --collectCoverage --detectOpenHandles",
"version": "conventional-changelog -p angular -i CHANGELOG.md -s"
"prerelease": "npm test && npm run build",
"release": "standard-version",
"test": "npm run eslint && jest --passWithNoTests"
},
"main": "./dist/index.js",
"exports": {
"require": "./dist/index.js",
"import": "./dist/index.mjs"
},
"repository": {

@@ -50,8 +56,7 @@ "type": "git",

"devDependencies": {
"@babel/core": "^7.x.x",
"@babel/plugin-proposal-decorators": "^7.x.x",
"@babel/preset-env": "^7.x.x",
"@babel/preset-typescript": "^7.x.x",
"@commitlint/cli": "^12.x.x",
"@commitlint/config-conventional": "^15.x.x",
"@commitlint/cli": "^17.x.x",
"@commitlint/config-conventional": "^17.x.x",
"@microsoft/api-documenter": "^7.x.x",
"@microsoft/api-extractor": "^7.x.x",
"@rollup/plugin-json": "^4.x.x",
"@types/jest": "^27.x.x",

@@ -63,10 +68,13 @@ "@types/koa": "^2.x.x",

"conventional-changelog-cli": "^2.x.x",
"copyfiles": "^2.x.x",
"del-cli": "^4.x.x",
"eslint": "^8.x.x",
"eslint-plugin-jest": "^25.x.x",
"husky": "^7.x.x",
"jest": "^27.x.x",
"jest-html-reporters": "^2.x.x",
"eslint-plugin-jest": "^26.x.x",
"husky": "^4.x.x",
"jest": "^28.x.x",
"jest-html-reporters": "^3.x.x",
"rollup": "^2.x.x",
"rollup-plugin-typescript2": "^0.x.x",
"standard-version": "^9.x.x",
"ts-jest": "^27.x.x",
"ts-jest": "^28.x.x",
"ts-node": "^10.x.x",

@@ -78,11 +86,10 @@ "typescript": "^4.x.x"

"generic-pool": "^3.8.2",
"ioredis": "^4.28.0",
"ioredis": "^4.28.5",
"koatty_lib": "^1.x.x",
"koatty_logger": "^1.x.x"
},
"husky": {
"hooks": {
"commit-msg": "commitlint -E HUSKY_GIT_PARAMS"
}
"peerDependencies": {
"koatty_lib": "^1.x.x",
"koatty_logger": "^1.x.x"
}
}
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc