Simple key-value storage with support for multiple backends
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
Primary key-value storage functionality including get, set, delete operations with TTL support and type safety for all JavaScript data types including Buffer.
Creates a new Keyv instance with optional storage adapter and configuration options.
/**
* Create a Keyv instance
* @param options - Configuration options for the instance
*/
constructor(options?: KeyvOptions);
/**
* Create a Keyv instance with storage adapter and options
* @param store - Storage adapter instance or options object
* @param options - Additional options (merged with store options)
*/
constructor(store?: KeyvStoreAdapter | KeyvOptions | Map<any, any>, options?: Omit<KeyvOptions, 'store'>);Usage Examples:
import Keyv from "keyv";
import KeyvRedis from "@keyv/redis";
// In-memory storage (default)
const keyv = new Keyv();
// With options
const keyvWithTTL = new Keyv({ ttl: 60000, namespace: 'my-cache' });
// With storage adapter
const keyvRedis = new Keyv(new KeyvRedis('redis://localhost:6379'));
// Storage adapter with options
const keyvWithStore = new Keyv(new KeyvRedis('redis://localhost:6379'), {
ttl: 30000,
namespace: 'sessions'
});
// Type-safe instance
const keyvTyped = new Keyv<{ name: string; age: number }>();Retrieves values by key with support for single keys, arrays, and raw data access.
/**
* Get value by key
* @param key - Key to retrieve
* @param options - Options including raw data access
* @returns Promise resolving to stored value or undefined
*/
async get<Value = GenericValue>(key: string, options?: {raw?: false}): Promise<StoredDataNoRaw<Value>>;
async get<Value = GenericValue>(key: string, options?: {raw?: true}): Promise<StoredDataRaw<Value>>;
/**
* Get multiple values by keys array
* @param key - Array of keys to retrieve
* @param options - Options including raw data access
* @returns Promise resolving to array of stored values
*/
async get<Value = GenericValue>(key: string[], options?: {raw?: false}): Promise<Array<StoredDataNoRaw<Value>>>;
async get<Value = GenericValue>(key: string[], options?: {raw?: true}): Promise<Array<StoredDataRaw<Value>>>;Usage Examples:
const keyv = new Keyv();
// Basic get
await keyv.set('user', { name: 'Alice', age: 30 });
const user = await keyv.get('user'); // { name: 'Alice', age: 30 }
// Get with type
const message = await keyv.get<string>('message'); // string | undefined
// Get raw data (includes TTL info)
const raw = await keyv.get('user', { raw: true });
// { value: { name: 'Alice', age: 30 }, expires: 1625097600000 }
// Get multiple keys
const users = await keyv.get(['user:1', 'user:2', 'user:3']);
// [{ name: 'Alice' }, { name: 'Bob' }, undefined]
// Expired keys return undefined
await keyv.set('temp', 'data', 1000); // expires in 1 second
// ... wait 2 seconds
const expired = await keyv.get('temp'); // undefinedStores values by key with optional TTL (time-to-live) expiration.
/**
* Set value for key with optional TTL
* @param key - Key to store value under
* @param value - Value to store (any JSON-serializable type plus Buffer)
* @param ttl - Time to live in milliseconds (optional)
* @returns Promise resolving to true if successful, false if failed
*/
async set<Value = GenericValue>(key: string, value: Value, ttl?: number): Promise<boolean>;Usage Examples:
const keyv = new Keyv();
// Basic set
await keyv.set('user', { name: 'Alice', age: 30 }); // true
// Set with TTL (expires in 5 minutes)
await keyv.set('session', 'abc123', 5 * 60 * 1000); // true
// Set with type
await keyv.set<string>('message', 'hello world'); // true
// Overwrite existing key
await keyv.set('counter', 1); // true
await keyv.set('counter', 2); // true (overwrites)
// Different data types
await keyv.set('buffer', Buffer.from('data')); // true
await keyv.set('date', new Date()); // true
await keyv.set('array', [1, 2, 3]); // true
await keyv.set('null', null); // true
// TTL of 0 means no expiration
await keyv.set('permanent', 'never expires', 0); // trueRemoves keys from storage with support for single keys and arrays.
/**
* Delete key(s) from storage
* @param key - Key or array of keys to delete
* @returns Promise resolving to true if key existed and was deleted
*/
async delete(key: string | string[]): Promise<boolean>;Usage Examples:
const keyv = new Keyv();
// Delete single key
await keyv.set('user', { name: 'Alice' });
await keyv.delete('user'); // true (existed and deleted)
await keyv.delete('nonexistent'); // false (didn't exist)
// Delete multiple keys
await keyv.set('a', 1);
await keyv.set('b', 2);
await keyv.delete(['a', 'b', 'c']); // true (at least one existed)Removes all entries in the current namespace.
/**
* Clear all entries in current namespace
* @returns Promise that resolves when entries are cleared
*/
async clear(): Promise<void>;Usage Examples:
const keyv = new Keyv({ namespace: 'cache' });
await keyv.set('key1', 'value1');
await keyv.set('key2', 'value2');
await keyv.clear(); // Removes all entries in 'cache' namespace
const key1 = await keyv.get('key1'); // undefined
const key2 = await keyv.get('key2'); // undefinedChecks if keys exist and are not expired.
/**
* Check if key exists and is not expired
* @param key - Key or array of keys to check
* @returns Promise resolving to boolean or array of booleans
*/
async has(key: string): Promise<boolean>;
async has(key: string[]): Promise<boolean[]>;Usage Examples:
const keyv = new Keyv();
await keyv.set('existing', 'value');
await keyv.has('existing'); // true
await keyv.has('nonexistent'); // false
// Multiple keys
await keyv.has(['existing', 'nonexistent', 'another']); // [true, false, false]
// Expired keys return false
await keyv.set('temp', 'value', 1000); // expires in 1 second
// ... wait 2 seconds
await keyv.has('temp'); // false (expired)Cleanly disconnects from the storage adapter if supported.
/**
* Disconnect from storage adapter
* @returns Promise that resolves when disconnected
*/
async disconnect(): Promise<void>;Usage Examples:
import Keyv from "keyv";
import KeyvRedis from "@keyv/redis";
const keyv = new Keyv(new KeyvRedis('redis://localhost:6379'));
// Perform operations
await keyv.set('key', 'value');
// Clean disconnect
await keyv.disconnect(); // Closes Redis connectionIterate over all entries in the current namespace using async iteration.
/**
* Async iterator for all entries in the current namespace
* Available when storage adapter supports iteration
*/
iterator?: IteratorFunction;
type IteratorFunction = (argument: any) => AsyncGenerator<any, void>;Usage Examples:
import Keyv from "keyv";
import KeyvSqlite from "@keyv/sqlite";
const keyv = new Keyv(new KeyvSqlite('sqlite://data.db'));
// Add some data
await keyv.set('user:1', { name: 'Alice', age: 30 });
await keyv.set('user:2', { name: 'Bob', age: 25 });
await keyv.set('product:1', { name: 'Widget', price: 9.99 });
// Iterate over all entries
if (keyv.iterator) {
for await (const [key, value] of keyv.iterator()) {
console.log(`${key}: ${JSON.stringify(value)}`);
}
// Output:
// user:1: {"name":"Alice","age":30}
// user:2: {"name":"Bob","age":25}
// product:1: {"name":"Widget","price":9.99}
}
// Iterator with namespace filtering
const userKeyv = new Keyv(new KeyvSqlite('sqlite://data.db'), { namespace: 'users' });
await userKeyv.set('1', { name: 'Alice' });
await userKeyv.set('2', { name: 'Bob' });
if (userKeyv.iterator) {
for await (const [key, value] of userKeyv.iterator()) {
console.log(`User ${key}: ${value.name}`);
}
// Output:
// User 1: Alice
// User 2: Bob
}
// Check if iterator is available
const memoryKeyv = new Keyv(); // Uses Map storage
if (memoryKeyv.iterator) {
// Iterator is available for Map storage
for await (const [key, value] of memoryKeyv.iterator()) {
console.log(key, value);
}
} else {
console.log('Iterator not available for this storage adapter');
}Notes:
useKeyPrefix setting