🚨 Active Supply Chain Attack:node-ipc Package Compromised.Learn More
Socket
Book a DemoSign in
Socket

@cacheable/node-cache

Package Overview
Dependencies
Maintainers
1
Versions
33
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@cacheable/node-cache - npm Package Compare versions

Comparing version
0.8.0
to
1.0.0
+121
-76
dist/index.cjs

@@ -34,2 +34,3 @@ "use strict";

NodeCacheErrors: () => NodeCacheErrors,
NodeCacheStore: () => NodeCacheStore,
default: () => NodeCache

@@ -39,2 +40,96 @@ });

var import_eventemitter3 = __toESM(require("eventemitter3"), 1);
var import_cacheable2 = require("cacheable");
// src/store.ts
var import_cacheable = require("cacheable");
var import_keyv = require("keyv");
var NodeCacheStore = class {
_maxKeys = 0;
_cache = new import_cacheable.Cacheable({ primary: new import_keyv.Keyv({ store: new import_cacheable.CacheableMemory() }) });
constructor(options) {
if (options) {
const cacheOptions = {
ttl: options.ttl,
primary: options.primary,
secondary: options.secondary
};
this._cache = new import_cacheable.Cacheable(cacheOptions);
if (options.maxKeys) {
this._maxKeys = options.maxKeys;
if (this._maxKeys > 0) {
this._cache.stats.enabled = true;
}
}
}
}
get cache() {
return this._cache;
}
get ttl() {
return this._cache.ttl;
}
set ttl(ttl) {
this._cache.ttl = ttl;
}
get primary() {
return this._cache.primary;
}
set primary(primary) {
this._cache.primary = primary;
}
get secondary() {
return this._cache.secondary;
}
set secondary(secondary) {
this._cache.secondary = secondary;
}
get maxKeys() {
return this._maxKeys;
}
set maxKeys(maxKeys) {
this._maxKeys = maxKeys;
if (this._maxKeys > 0) {
this._cache.stats.enabled = true;
}
}
async set(key, value, ttl) {
if (this._maxKeys > 0) {
console.log(this._cache.stats.count, this._maxKeys);
if (this._cache.stats.count >= this._maxKeys) {
return false;
}
}
const finalTtl = ttl ?? this._cache.ttl;
await this._cache.set(key.toString(), value, finalTtl);
return true;
}
async mset(list) {
const items = new Array();
for (const item of list) {
items.push({ key: item.key.toString(), value: item.value, ttl: item.ttl });
}
await this._cache.setMany(items);
}
async get(key) {
return this._cache.get(key.toString());
}
async mget(keys) {
const result = {};
for (const key of keys) {
result[key.toString()] = await this._cache.get(key.toString());
}
return result;
}
async del(key) {
return this._cache.delete(key.toString());
}
async mdel(keys) {
return this._cache.deleteMany(keys.map((key) => key.toString()));
}
async clear() {
return this._cache.clear();
}
};
// src/index.ts
var NodeCacheErrors = /* @__PURE__ */ ((NodeCacheErrors2) => {

@@ -57,9 +152,4 @@ NodeCacheErrors2["ECACHEFULL"] = "Cache max keys amount exceeded";

store = /* @__PURE__ */ new Map();
_stats = {
keys: 0,
hits: 0,
misses: 0,
ksize: 0,
vsize: 0
};
_stats = new import_cacheable2.CacheableStats({ enabled: true });
_cacheable = new import_cacheable2.CacheableMemory();
intervalId = 0;

@@ -95,5 +185,5 @@ constructor(options) {

this.emit("set", keyValue, value, ttlValue);
this._stats.ksize += this.roughSizeOfKey(keyValue);
this._stats.vsize += this.roughSizeOfObject(value);
this._stats.keys = this.store.size;
this._stats.incrementKSize(keyValue);
this._stats.incrementVSize(value);
this._stats.setCount(this.store.size);
return true;

@@ -120,19 +210,19 @@ }

}
this.addMiss();
this._stats.incrementMisses();
this.emit("expired", this.formatKey(key), result.value);
return void 0;
}
this.addHit();
this._stats.incrementHits();
if (this.options.useClones) {
return this.clone(result.value);
return this._cacheable.clone(result.value);
}
return result.value;
}
this.addHit();
this._stats.incrementHits();
if (this.options.useClones) {
return this.clone(result.value);
return this._cacheable.clone(result.value);
}
return result.value;
}
this.addMiss();
this._stats.incrementMisses();
return void 0;

@@ -164,3 +254,3 @@ }

if (this.options.useClones) {
return this.clone(result);
return this._cacheable.clone(result);
}

@@ -181,5 +271,5 @@ return result;

this.emit("del", keyValue, result.value);
this._stats.ksize -= this.roughSizeOfKey(keyValue);
this._stats.vsize -= this.roughSizeOfObject(result.value);
this._stats.keys = this.store.size;
this._stats.decreaseKSize(keyValue);
this._stats.decreaseVSize(result.value);
this._stats.setCount(this.store.size);
return 1;

@@ -243,3 +333,10 @@ }

getStats() {
return this._stats;
const stats = {
keys: this._stats.count,
hits: this._stats.hits,
misses: this._stats.misses,
ksize: this._stats.ksize,
vsize: this._stats.vsize
};
return stats;
}

@@ -254,9 +351,3 @@ // Flush the whole data.

flushStats() {
this._stats = {
keys: 0,
hits: 0,
misses: 0,
ksize: 0,
vsize: 0
};
this._stats = new import_cacheable2.CacheableStats({ enabled: true });
this.emit("flush_stats");

@@ -281,33 +372,2 @@ }

}
addHit() {
this._stats.hits++;
}
addMiss() {
this._stats.misses++;
}
roughSizeOfKey(key) {
return this.formatKey(key).toString().length * 2;
}
roughSizeOfObject(object) {
const objectList = [];
const stack = [object];
let bytes = 0;
while (stack.length > 0) {
const value = stack.pop();
if (typeof value === "boolean") {
bytes += 4;
} else if (typeof value === "string") {
bytes += value.length * 2;
} else if (typeof value === "number") {
bytes += 8;
} else if (typeof value === "object" && value !== null && !objectList.includes(value)) {
objectList.push(value);
for (const key in value) {
bytes += key.length * 2;
stack.push(value[key]);
}
}
}
return bytes;
}
startInterval() {

@@ -343,22 +403,7 @@ if (this.options.checkperiod && this.options.checkperiod > 0) {

}
isPrimitive(value) {
const result = false;
if (value === null || value === void 0) {
return true;
}
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
return true;
}
return result;
}
clone(value) {
if (this.isPrimitive(value)) {
return value;
}
return structuredClone(value);
}
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
NodeCacheErrors
NodeCacheErrors,
NodeCacheStore
});
import eventemitter from 'eventemitter3';
import { Cacheable } from 'cacheable';
import { Keyv } from 'keyv';
type NodeCacheStoreOptions = {
ttl?: number;
maxKeys?: number;
primary?: Keyv;
secondary?: Keyv;
};
declare class NodeCacheStore {
private _maxKeys;
private readonly _cache;
constructor(options?: NodeCacheStoreOptions);
get cache(): Cacheable;
get ttl(): number | undefined;
set ttl(ttl: number | undefined);
get primary(): Keyv;
set primary(primary: Keyv);
get secondary(): Keyv | undefined;
set secondary(secondary: Keyv | undefined);
get maxKeys(): number;
set maxKeys(maxKeys: number);
set(key: string | number, value: any, ttl?: number): Promise<boolean>;
mset(list: NodeCacheItem[]): Promise<void>;
get<T>(key: string | number): Promise<T | undefined>;
mget<T>(keys: Array<string | number>): Promise<Record<string, T | undefined>>;
del(key: string | number): Promise<boolean>;
mdel(keys: Array<string | number>): Promise<boolean>;
clear(): Promise<void>;
}
type NodeCacheOptions = {

@@ -32,2 +62,3 @@ stdTTL?: number;

private _stats;
private readonly _cacheable;
private intervalId;

@@ -53,6 +84,2 @@ constructor(options?: NodeCacheOptions);

private getExpirationTimestamp;
private addHit;
private addMiss;
private roughSizeOfKey;
private roughSizeOfObject;
private startInterval;

@@ -62,6 +89,4 @@ private checkData;

private createError;
private isPrimitive;
private clone;
}
export { NodeCacheErrors, type NodeCacheItem, type NodeCacheOptions, type NodeCacheStats, NodeCache as default };
export { NodeCacheErrors, type NodeCacheItem, type NodeCacheOptions, type NodeCacheStats, NodeCacheStore, type NodeCacheStoreOptions, NodeCache as default };
import eventemitter from 'eventemitter3';
import { Cacheable } from 'cacheable';
import { Keyv } from 'keyv';
type NodeCacheStoreOptions = {
ttl?: number;
maxKeys?: number;
primary?: Keyv;
secondary?: Keyv;
};
declare class NodeCacheStore {
private _maxKeys;
private readonly _cache;
constructor(options?: NodeCacheStoreOptions);
get cache(): Cacheable;
get ttl(): number | undefined;
set ttl(ttl: number | undefined);
get primary(): Keyv;
set primary(primary: Keyv);
get secondary(): Keyv | undefined;
set secondary(secondary: Keyv | undefined);
get maxKeys(): number;
set maxKeys(maxKeys: number);
set(key: string | number, value: any, ttl?: number): Promise<boolean>;
mset(list: NodeCacheItem[]): Promise<void>;
get<T>(key: string | number): Promise<T | undefined>;
mget<T>(keys: Array<string | number>): Promise<Record<string, T | undefined>>;
del(key: string | number): Promise<boolean>;
mdel(keys: Array<string | number>): Promise<boolean>;
clear(): Promise<void>;
}
type NodeCacheOptions = {

@@ -32,2 +62,3 @@ stdTTL?: number;

private _stats;
private readonly _cacheable;
private intervalId;

@@ -53,6 +84,2 @@ constructor(options?: NodeCacheOptions);

private getExpirationTimestamp;
private addHit;
private addMiss;
private roughSizeOfKey;
private roughSizeOfObject;
private startInterval;

@@ -62,6 +89,4 @@ private checkData;

private createError;
private isPrimitive;
private clone;
}
export { NodeCacheErrors, type NodeCacheItem, type NodeCacheOptions, type NodeCacheStats, NodeCache as default };
export { NodeCacheErrors, type NodeCacheItem, type NodeCacheOptions, type NodeCacheStats, NodeCacheStore, type NodeCacheStoreOptions, NodeCache as default };
// src/index.ts
import eventemitter from "eventemitter3";
import { CacheableMemory as CacheableMemory2, CacheableStats } from "cacheable";
// src/store.ts
import { Cacheable, CacheableMemory } from "cacheable";
import { Keyv } from "keyv";
var NodeCacheStore = class {
_maxKeys = 0;
_cache = new Cacheable({ primary: new Keyv({ store: new CacheableMemory() }) });
constructor(options) {
if (options) {
const cacheOptions = {
ttl: options.ttl,
primary: options.primary,
secondary: options.secondary
};
this._cache = new Cacheable(cacheOptions);
if (options.maxKeys) {
this._maxKeys = options.maxKeys;
if (this._maxKeys > 0) {
this._cache.stats.enabled = true;
}
}
}
}
get cache() {
return this._cache;
}
get ttl() {
return this._cache.ttl;
}
set ttl(ttl) {
this._cache.ttl = ttl;
}
get primary() {
return this._cache.primary;
}
set primary(primary) {
this._cache.primary = primary;
}
get secondary() {
return this._cache.secondary;
}
set secondary(secondary) {
this._cache.secondary = secondary;
}
get maxKeys() {
return this._maxKeys;
}
set maxKeys(maxKeys) {
this._maxKeys = maxKeys;
if (this._maxKeys > 0) {
this._cache.stats.enabled = true;
}
}
async set(key, value, ttl) {
if (this._maxKeys > 0) {
console.log(this._cache.stats.count, this._maxKeys);
if (this._cache.stats.count >= this._maxKeys) {
return false;
}
}
const finalTtl = ttl ?? this._cache.ttl;
await this._cache.set(key.toString(), value, finalTtl);
return true;
}
async mset(list) {
const items = new Array();
for (const item of list) {
items.push({ key: item.key.toString(), value: item.value, ttl: item.ttl });
}
await this._cache.setMany(items);
}
async get(key) {
return this._cache.get(key.toString());
}
async mget(keys) {
const result = {};
for (const key of keys) {
result[key.toString()] = await this._cache.get(key.toString());
}
return result;
}
async del(key) {
return this._cache.delete(key.toString());
}
async mdel(keys) {
return this._cache.deleteMany(keys.map((key) => key.toString()));
}
async clear() {
return this._cache.clear();
}
};
// src/index.ts
var NodeCacheErrors = /* @__PURE__ */ ((NodeCacheErrors2) => {

@@ -20,9 +114,4 @@ NodeCacheErrors2["ECACHEFULL"] = "Cache max keys amount exceeded";

store = /* @__PURE__ */ new Map();
_stats = {
keys: 0,
hits: 0,
misses: 0,
ksize: 0,
vsize: 0
};
_stats = new CacheableStats({ enabled: true });
_cacheable = new CacheableMemory2();
intervalId = 0;

@@ -58,5 +147,5 @@ constructor(options) {

this.emit("set", keyValue, value, ttlValue);
this._stats.ksize += this.roughSizeOfKey(keyValue);
this._stats.vsize += this.roughSizeOfObject(value);
this._stats.keys = this.store.size;
this._stats.incrementKSize(keyValue);
this._stats.incrementVSize(value);
this._stats.setCount(this.store.size);
return true;

@@ -83,19 +172,19 @@ }

}
this.addMiss();
this._stats.incrementMisses();
this.emit("expired", this.formatKey(key), result.value);
return void 0;
}
this.addHit();
this._stats.incrementHits();
if (this.options.useClones) {
return this.clone(result.value);
return this._cacheable.clone(result.value);
}
return result.value;
}
this.addHit();
this._stats.incrementHits();
if (this.options.useClones) {
return this.clone(result.value);
return this._cacheable.clone(result.value);
}
return result.value;
}
this.addMiss();
this._stats.incrementMisses();
return void 0;

@@ -127,3 +216,3 @@ }

if (this.options.useClones) {
return this.clone(result);
return this._cacheable.clone(result);
}

@@ -144,5 +233,5 @@ return result;

this.emit("del", keyValue, result.value);
this._stats.ksize -= this.roughSizeOfKey(keyValue);
this._stats.vsize -= this.roughSizeOfObject(result.value);
this._stats.keys = this.store.size;
this._stats.decreaseKSize(keyValue);
this._stats.decreaseVSize(result.value);
this._stats.setCount(this.store.size);
return 1;

@@ -206,3 +295,10 @@ }

getStats() {
return this._stats;
const stats = {
keys: this._stats.count,
hits: this._stats.hits,
misses: this._stats.misses,
ksize: this._stats.ksize,
vsize: this._stats.vsize
};
return stats;
}

@@ -217,9 +313,3 @@ // Flush the whole data.

flushStats() {
this._stats = {
keys: 0,
hits: 0,
misses: 0,
ksize: 0,
vsize: 0
};
this._stats = new CacheableStats({ enabled: true });
this.emit("flush_stats");

@@ -244,33 +334,2 @@ }

}
addHit() {
this._stats.hits++;
}
addMiss() {
this._stats.misses++;
}
roughSizeOfKey(key) {
return this.formatKey(key).toString().length * 2;
}
roughSizeOfObject(object) {
const objectList = [];
const stack = [object];
let bytes = 0;
while (stack.length > 0) {
const value = stack.pop();
if (typeof value === "boolean") {
bytes += 4;
} else if (typeof value === "string") {
bytes += value.length * 2;
} else if (typeof value === "number") {
bytes += 8;
} else if (typeof value === "object" && value !== null && !objectList.includes(value)) {
objectList.push(value);
for (const key in value) {
bytes += key.length * 2;
stack.push(value[key]);
}
}
}
return bytes;
}
startInterval() {

@@ -306,22 +365,7 @@ if (this.options.checkperiod && this.options.checkperiod > 0) {

}
isPrimitive(value) {
const result = false;
if (value === null || value === void 0) {
return true;
}
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
return true;
}
return result;
}
clone(value) {
if (this.isPrimitive(value)) {
return value;
}
return structuredClone(value);
}
};
export {
NodeCacheErrors,
NodeCacheStore,
NodeCache as default
};
{
"name": "@cacheable/node-cache",
"version": "0.8.0",
"version": "1.0.0",
"description": "Simple and Maintained fast NodeJS internal caching",

@@ -33,3 +33,3 @@ "type": "module",

"rimraf": "^6.0.1",
"tsup": "^8.2.4",
"tsup": "^8.3.0",
"typescript": "^5.6.2",

@@ -40,4 +40,5 @@ "vitest": "^2.1.1",

"dependencies": {
"cacheable": "^0.8.0",
"eventemitter3": "^5.0.1"
"cacheable": "^1.2.0",
"eventemitter3": "^5.0.1",
"keyv": "^5.0.1"
},

@@ -44,0 +45,0 @@ "files": [

@@ -25,2 +25,3 @@ [<img align="center" src="https://cacheable.org/logo.svg" alt="Cacheable" />](https://github.com/jaredwray/cacheable)

* [Advanced Usage](#advanced-usage)
* [NodeCacheStore](#nodecachestore)
* [API](#api)

@@ -64,2 +65,42 @@ * [How to Contribute](#how-to-contribute)

## NodeCacheStore
The `NodeCacheStore` is a class that extends the `NodeCache` and adds the ability to use storage adapters. This is based on the `cacheable` engine and allows you to do layer 1 and layer 2 caching. The storage adapters are based on the [Keyv](https://keyv.org) package. This allows you to use any of the storage adapters that are available.
```javascript
import {NodeCacheStore} from '@cacheable/node-cache';
const cache = new NodeCacheStore();
cache.set('foo', 'bar');
cache.get('foo'); // 'bar'
```
### NodeCacheStoreOptions
When initializing the cache you can pass in the options below:
```javascript
export type NodeCacheStoreOptions = {
ttl?: number; // The standard ttl as number in seconds for every generated cache element. 0 = unlimited
primary?: Keyv; // The primary storage adapter
secondary?: Keyv; // The secondary storage adapter
maxKeys?: number; // Default is 0 (unlimited). If this is set it will throw and error if you try to set more keys than the max.
};
```
### Node Cache Store API
* `set(key: string | number, value: any, ttl?: number): Promise<boolean>` - Set a key value pair with an optional ttl (in milliseconds). Will return true on success. If the ttl is not set it will default to 0 (no ttl)
* `mset(data: Array<NodeCacheItem>): Promise<boolean>` - Set multiple key value pairs at once
* `get(key: string | number): Promise<any>` - Get a value from the cache by key
* `mget(keys: Array<string | number>): Promise<Record<string, unknown>>` - Get multiple values from the cache by keys
* `del(key: string | number): Promise<boolean>` - Delete a key
* `mdel(keys: Array<string | number>): Promise<boolean>` - Delete multiple keys
* `clear(): Promise<void>` - Clear the cache
* `stats`: `NodeCacheStats` - Get the stats of the cache
* `ttl`: `number` - The standard ttl as number in seconds for every generated cache element. 0 = unlimited
* `primary`: `Keyv` - The primary storage adapter
* `secondary`: `Keyv` - The secondary storage adapter
* `maxKeys`: `number` - If this is set it will throw and error if you try to set more keys than the max
## API

@@ -66,0 +107,0 @@