### Basic KV.JS Usage Example Source: https://github.com/heyputer/kv.js/blob/main/README.md Demonstrates the basic usage of KV.JS, including creating an instance, setting and getting keys, deleting keys, and setting expiration times. Ensure the kvjs module is required before use. ```javascript const kvjs = require('@heyputer/kv.js'); // Create a new kv.js instance const kv = new kvjs(); // Set a key kv.set('foo', 'bar'); // Get the key's value kv.get('foo'); // "bar" // Delete the key kv.del('foo'); // Set another key kv.set('username', 'heyputer'); // Automatically delete the key after 60 seconds kv.expire('username', 60); ``` -------------------------------- ### Install KV.JS with npm Source: https://github.com/heyputer/kv.js/blob/main/README.md Install the KV.JS package using npm. This command is used to add the library to your project's dependencies. ```bash npm install @heyputer/kv.js ``` -------------------------------- ### Set and Get Multiple Keys Source: https://context7.com/heyputer/kv.js/llms.txt Atomically set multiple key-value pairs using `mset` and retrieve multiple values using `mget`. ```javascript const kv = new kvjs(); kvsisted.mset('first', 'Alice', 'last', 'Smith', 'age', '30'); const [first, last, age, missing] = kv.mget('first', 'last', 'age', 'nonexistent'); console.log(first, last, age); // 'Alice' 'Smith' '30' console.log(missing); // undefined ``` -------------------------------- ### set / get Source: https://context7.com/heyputer/kv.js/llms.txt Set and retrieve a string value. `set(key, value, options)` stores any value under a key with optional expiration and conditional flags. `get(key)` retrieves it, returning `undefined` if the key is missing or expired. ```APIDOC ## set / get — Set and retrieve a string value `set(key, value, options)` stores any value under a key with optional expiration and conditional flags. `get(key)` retrieves it, returning `undefined` if the key is missing or expired. ```javascript const kv = new kvjs(); // Basic set/get kv.set('username', 'alice'); console.log(kv.get('username')); // 'alice' // Set only if key does NOT exist (NX) kv.set('username', 'bob', { NX: true }); console.log(kv.get('username')); // 'alice' — not overwritten // Set only if key ALREADY exists (XX) kv.set('username', 'charlie', { XX: true }); console.log(kv.get('username')); // 'charlie' // Set with TTL in seconds (EX) and get old value (GET) const old = kv.set('session', 'tok_abc123', { EX: 3600, GET: true }); console.log(old); // undefined (key didn't exist before) console.log(kv.ttl('session')); // ~3600 // Set with millisecond TTL (PX) kv.set('temp', 'value', { PX: 500 }); // Set with UNIX timestamp expiry (EXAT) kv.set('event', 'launch', { EXAT: Math.floor(Date.now() / 1000) + 60 }); // Keep existing TTL when updating value kv.set('session', 'tok_xyz789', { KEEPTTL: true }); console.log(kv.ttl('session')); // still ~3600 ``` ``` -------------------------------- ### set Source: https://github.com/heyputer/kv.js/blob/main/README.md Set the string value of a key with optional options like NX, XX, GET, EX, PX, EXAT, PXAT, KEEPTTL. ```APIDOC ## set ### Description Set the string value of a key with optional options. ### Method APICALL ### Endpoint set(key, value, [options]) ### Parameters #### Path Parameters - **key** (string) - Required - The key to set. - **value** (string) - Required - The value to set for the key. #### Query Parameters - **options** (object) - Optional - An object containing options: - **NX** (boolean) - Set only if the key does not already exist. - **XX** (boolean) - Set only if the key already exists. - **GET** (boolean) - Return the old value of the key before setting the new value. - **EX** (integer) - Set the specified expire time in seconds. - **PX** (integer) - Set the specified expire time in milliseconds. - **EXAT** (integer) - Set the specified Unix time at which the key will expire, in seconds. - **PXAT** (integer) - Set the specified Unix time at which the key will expire, in milliseconds. - **KEEPTTL** (boolean) - Retain the time to live associated with the key. ### Request Example ```javascript kv.set('username', 'john_doe'); kv.set('username', 'jane_doe', {NX: true}); kv.set('session_token', 'abc123', {EX: 3600}); kv.set('username', 'mary_smith', {GET: true}); kv.set('new_user', 'carol_baker', {NX: true, EX: 7200, GET: true}); ``` ### Response #### Success Response (boolean or string) - **true** - If the key was set successfully. - **string** - If the GET option is used, returns the old value of the key. ### Response Example ```json true ``` ```json "old_username" ``` ``` -------------------------------- ### Sorted Set Basics Source: https://context7.com/heyputer/kv.js/llms.txt Basic operations for sorted sets including adding elements, getting the size, score, rank, and count of elements, and removing elements. ```APIDOC ## zadd / zrem / zscore / zrank / zcard / zcount ### Description Provides basic operations for managing sorted sets, including adding and removing members, retrieving scores and ranks, and counting elements within a range. ### Method kv.zadd(key, score, member) kv.zrem(key, member) kv.zscore(key, member) kv.zrank(key, member) kv.zcard(key) kv.zcount(key, minScore, maxScore) ### Parameters #### zadd - **key** (string) - The key of the sorted set. - **score** (number) - The score of the member. - **member** (string) - The member to add. #### zrem - **key** (string) - The key of the sorted set. - **member** (string) - The member to remove. #### zscore - **key** (string) - The key of the sorted set. - **member** (string) - The member whose score to retrieve. #### zrank - **key** (string) - The key of the sorted set. - **member** (string) - The member whose rank to retrieve. #### zcard - **key** (string) - The key of the sorted set. #### zcount - **key** (string) - The key of the sorted set. - **minScore** (number) - The minimum score. - **maxScore** (number) - The maximum score. ### Request Example ```javascript const kv = new kvjs(); kv.zadd('leaderboard', 1500, 'Alice'); kv.zadd('leaderboard', 2300, 'Bob'); kv.zadd('leaderboard', 1800, 'Carol'); console.log(kv.zcard('leaderboard')); console.log(kv.zscore('leaderboard', 'Bob')); console.log(kv.zrank('leaderboard', 'Alice')); kv.zrem('leaderboard', 'Alice'); ``` ### Response #### Success Response (zcard) - **count** (number) - The number of elements in the sorted set. #### Success Response (zscore) - **score** (number) - The score of the member. #### Success Response (zrank) - **rank** (number) - The rank of the member (0-based index). #### Success Response (zcount) - **count** (number) - The number of elements within the score range. ``` -------------------------------- ### Set key-value pairs with various options using set Source: https://github.com/heyputer/kv.js/blob/main/README.md The `set` command allows setting string values with options like NX (set if not exists), XX (set if exists), EX (expire seconds), PX (expire milliseconds), GET (return old value), EXAT (expire at timestamp seconds), PXAT (expire at timestamp milliseconds), and KEEPTTL (keep existing TTL). ```javascript // Set a basic key-value pair kv.set('username', 'john_doe'); // Output: true // Set a key-value pair only if the key does not already exist (NX option) kv.set('username', 'jane_doe', {NX: true}); // Set a key-value pair only if the key already exists (XX option) kv.set('email', 'jane@example.com', {XX: true}); // Set a key-value pair with an expiration time in seconds (EX option) kv.set('session_token', 'abc123', {EX: 3600}); // Get the existing value and set a new value for a key (GET option) kv.set('username', 'mary_smith', {GET: true}); // Set a key-value pair with an expiration time in milliseconds (PX option) kv.set('temp_data', '42', {PX: 1000}); // Set a key-value pair with an expiration time at a specific Unix timestamp in seconds (EXAT option) kv.set('event_data', 'event1', {EXAT: 1677649420}); // Set a key-value pair with an expiration time at a specific Unix timestamp in milliseconds (PXAT option) kv.set('event_data2', 'event2', {PXAT: 1677649420000}); // Set a key-value pair and keep the original TTL if the key already exists (KEEPTTL option) kv.set('username', 'alice_wonder', {KEEPTTL: true}); // Set a key-value pair with multiple options (NX, EX, and GET options) kv.set('new_user', 'carol_baker', {NX: true, EX: 7200, GET: true}); ``` -------------------------------- ### List Basics: rpush, lpush, rpop, lpop, lrange, llen Source: https://context7.com/heyputer/kv.js/llms.txt Manage lists with rpush/lpush for adding elements to the right/left, rpop/lpop for removing from right/left, lrange for retrieving a range, and llen for getting the list length. rpushx/lpushx add only if the key exists. ```javascript const kv = new kvjs(); vk.rpush('tasks', 'task1', 'task2', 'task3'); vk.lpush('tasks', 'task0'); console.log(kv.lrange('tasks', 0, -1)); // ['task0', 'task1', 'task2', 'task3'] console.log(kv.llen('tasks')); // 4 console.log(kv.lpop('tasks')); // 'task0' console.log(kv.rpop('tasks')); // 'task3' console.log(kv.lrange('tasks', 0, -1)); // ['task1', 'task2'] // Push only if key exists vk.rpushx('tasks', 'task4'); // 3 vk.lpushx('tasks', 'task0'); // 4 vk.rpushx('missing', 'x'); // 0 — key doesn't exist ``` -------------------------------- ### mset / mget Source: https://context7.com/heyputer/kv.js/llms.txt Set and get multiple keys atomically. `mset` sets multiple key-value pairs in one call; `mget` retrieves multiple values as an array. ```APIDOC ## mset / mget — Set and get multiple keys atomically `mset` sets multiple key-value pairs in one call; `mget` retrieves multiple values as an array. ```javascript const kv = new kvjs(); kv.mset('first', 'Alice', 'last', 'Smith', 'age', '30'); const [first, last, age, missing] = kv.mget('first', 'last', 'age', 'nonexistent'); console.log(first, last, age); // 'Alice' 'Smith' '30' console.log(missing); // undefined ``` ``` -------------------------------- ### get Source: https://github.com/heyputer/kv.js/blob/main/README.md Retrieves the value associated with a given key. Returns null if the key does not exist, has expired, or has been deleted. ```APIDOC ## get ### Description Retrieves the value associated with a given key. Returns null if the key does not exist, has expired, or has been deleted. ### Method `kv.get(key)` ### Parameters #### Path Parameters - **key** (string) - Required - The key whose value is to be retrieved. ``` -------------------------------- ### Set and Get String Values Source: https://context7.com/heyputer/kv.js/llms.txt Store and retrieve string values. Supports conditional flags like NX (set if not exists) and XX (set if exists), and expiration options (EX, PX, EXAT). ```javascript const kv = new kvjs(); // Basic set/get kvsisted.set('username', 'alice'); console.log(kv.get('username')); // 'alice' // Set only if key does NOT exist (NX) kvsisted.set('username', 'bob', { NX: true }); console.log(kv.get('username')); // 'alice' — not overwritten // Set only if key ALREADY exists (XX) kvsisted.set('username', 'charlie', { XX: true }); console.log(kv.get('username')); // 'charlie' // Set with TTL in seconds (EX) and get old value (GET) const old = kv.set('session', 'tok_abc123', { EX: 3600, GET: true }); console.log(old); // undefined (key didn't exist before) console.log(kv.ttl('session')); // ~3600 // Set with millisecond TTL (PX) kvsisted.set('temp', 'value', { PX: 500 }); // Set with UNIX timestamp expiry (EXAT) kvsisted.set('event', 'launch', { EXAT: Math.floor(Date.now() / 1000) + 60 }); // Keep existing TTL when updating value kvsisted.set('session', 'tok_xyz789', { KEEPTTL: true }); console.log(kv.ttl('session')); // still ~3600 ``` -------------------------------- ### sadd / srem / smembers / scard / sismember Source: https://context7.com/heyputer/kv.js/llms.txt Manage set members, including adding, removing, retrieving all members, getting the cardinailty, and checking for membership. ```APIDOC ## sadd / srem / smembers / scard / sismember ### Description Manage set members, including adding, removing, retrieving all members, getting the cardinailty, and checking for membership. ### Method Not applicable (JavaScript API) ### Endpoint Not applicable (JavaScript API) ### Parameters Not applicable (JavaScript API) ### Request Example ```javascript const kv = new kvjs(); v.sadd('tags', 'javascript', 'nodejs', 'cache'); v.smembers('tags'); v.scard('tags'); v.sismember('tags', 'nodejs'); v.srem('tags', 'cache'); v.smembers('tags'); v.smismember('tags', 'javascript', 'python', 'nodejs'); ``` ### Response Not applicable (JavaScript API) ``` -------------------------------- ### Geospatial Data Storage and Querying Source: https://context7.com/heyputer/kv.js/llms.txt Commands for adding, retrieving, and querying geospatial data, including adding coordinates, calculating distances, and getting geohashes. ```APIDOC ## geoadd / geodist / geopos / geohash ### Description Enables storing and querying of geospatial data. Allows adding locations with coordinates, calculating distances between them, retrieving coordinates, and generating geohashes. ### Method kv.geoadd(key, longitude, latitude, member) kv.geodist(key, member1, member2, unit) kv.geopos(key, member) kv.geohash(key, ...members) ### Parameters #### geoadd - **key** (string) - The key for the geospatial set. - **longitude** (number) - The longitude of the location. - **latitude** (number) - The latitude of the location. - **member** (string) - The name of the location. #### geodist - **key** (string) - The key for the geospatial set. - **member1** (string) - The first member. - **member2** (string) - The second member. - **unit** (string) - The unit for distance ('km', 'mi', 'm', 'ft'). #### geopos - **key** (string) - The key for the geospatial set. - **member** (string) - The member whose coordinates to retrieve. #### geohash - **key** (string) - The key for the geospatial set. - **...members** (string) - One or more members to get geohashes for. ### Request Example ```javascript const kv = new kvjs(); kv.geoadd('cities', -73.9857, 40.7484, 'New York'); kv.geoadd('cities', -0.1276, 51.5074, 'London'); const distKm = kv.geodist('cities', 'London', 'Paris', 'km'); console.log(kv.geopos('cities', 'New York')); console.log(kv.geohash('cities', 'London', 'Paris')); ``` ### Response #### Success Response (geodist) - **distance** (number) - The distance between the two members. #### Success Response (geopos) - **coordinates** (Array>) - An array containing the latitude and longitude of the member. #### Success Response (geohash) - **geohashes** (Array) - An array of geohash strings for the specified members. ``` -------------------------------- ### rpush / lpush / rpop / lpop / lrange / llen Source: https://context7.com/heyputer/kv.js/llms.txt Basic list operations including pushing and popping elements from either end, retrieving a range of elements, and getting the list length. ```APIDOC ## rpush / lpush / rpop / lpop / lrange / llen ### Description Basic list operations including pushing and popping elements from either end, retrieving a range of elements, and getting the list length. ### Method Not applicable (JavaScript API) ### Endpoint Not applicable (JavaScript API) ### Parameters Not applicable (JavaScript API) ### Request Example ```javascript const kv = new kvjs(); v.rpush('tasks', 'task1', 'task2', 'task3'); v.lpush('tasks', 'task0'); v.lrange('tasks', 0, -1); v.llen('tasks'); v.lpop('tasks'); v.rpop('tasks'); v.lrange('tasks', 0, -1); v.rpushx('tasks', 'task4'); v.lpushx('tasks', 'task0'); v.rpushx('missing', 'x'); ``` ### Response Not applicable (JavaScript API) ``` -------------------------------- ### Sorted Set Operations: zcard Source: https://github.com/heyputer/kv.js/blob/main/README.md Demonstrates how to get the total number of members in a sorted set using `zcard`. This operation requires the sorted set to have members already added. ```javascript // Add two members to the sorted set 'students'. kv.zadd('students', 10, 'Alice'); kv.zadd('students', 25, 'Bob'); // Get the number of members in the sorted set 'students'. kv.zcard('students'); // Output: 2 ``` -------------------------------- ### Sorted Set Operations: zrank Source: https://github.com/heyputer/kv.js/blob/main/README.md Shows how to get the rank (index) of a specific member within a sorted set using `zrank`. The rank is 0-based. ```javascript // Add three members to the sorted set 'students'. kv.zadd('students', 10, 'Alice'); kv.zadd('students', 25, 'Bob'); kv.zadd('students', 30, 'Carol'); // Get the rank of member 'Bob' in the sorted set 'students'. kv.zrank('students', 'Bob'); // Output: 1 ``` -------------------------------- ### Set and Get Bits in KV.JS Source: https://context7.com/heyputer/kv.js/llms.txt Use setbit to set individual bits and getbit to retrieve them. Bits are treated as a compact boolean array. Accessing an out-of-range bit returns 0. ```javascript const kv = new kvjs(); // Use bits as a compact boolean array (e.g., daily activity flags) kv.setbit('activity:user1', 0, 1); // day 0 active kv.setbit('activity:user1', 1, 0); // day 1 inactive kv.setbit('activity:user1', 2, 1); // day 2 active console.log(kv.getbit('activity:user1', 0)); // 1 console.log(kv.getbit('activity:user1', 1)); // 0 console.log(kv.getbit('activity:user1', 2)); // 1 console.log(kv.getbit('activity:user1', 5)); // 0 (out of range → 0) ``` -------------------------------- ### Sorted Set Manipulation: zincrby, zpopmax, zpopmin, zrandmember, zscan Source: https://context7.com/heyputer/kv.js/llms.txt Shows how to modify sorted set members' scores, remove members from the ends, get random members, and iterate through the set using a cursor. `zincrby` increments a member's score, `zpopmax`/`zpopmin` remove and return members with the highest/lowest scores, `zrandmember` returns a random member, and `zscan` allows for paginated iteration. ```javascript const kv = new kvjs(); kv.zadd('ratings', 4, 'itemA'); kv.zadd('ratings', 3, 'itemB'); kv.zadd('ratings', 5, 'itemC'); kv.zincrby('ratings', 1, 'itemB'); // itemB score => 4 console.log(kv.zscore('ratings', 'itemB')); // 4 console.log(kv.zpopmax('ratings', 1)); // [['itemC', 5]] console.log(kv.zpopmin('ratings', 1)); // [['itemA', 4]] console.log(kv.zrandmember('ratings', 1)); // ['itemB'] // Paginated iteration const [cursor, entries] = kv.zscan('ratings', 0, { count: 10 }); console.log(entries); // [['itemB', 4]] ``` -------------------------------- ### Get and Set Value of a Key Source: https://github.com/heyputer/kv.js/blob/main/README.md Atomically replaces the value of a key with a new value and returns the old value. If the key does not exist, it is set to the new value and `null` is returned. ```javascript kv.set("username", "John"); ``` ```javascript kv.getset("username", "Alice"); // Returns "John" ``` ```javascript kv.getset("nonExistentKey", "Bob"); // Returns null ``` -------------------------------- ### Instantiate KV.JS Source: https://context7.com/heyputer/kv.js/llms.txt Create a new KV.JS instance. Use `dbName` for browser persistence. Wait for initialization before use. ```javascript const kvjs = require('@heyputer/kv.js'); // Pure in-memory (Node.js or browser) const kv = new kvjs(); // Browser with IndexedDB persistence const kvPersisted = new kvjs({ dbName: 'my-app-cache', dbVersion: 1 }); // Wait for IndexedDB initialization before performing operations await kvPersisted.waitForInitialization(); kvsisted.set('user:1', JSON.stringify({ name: 'Alice', role: 'admin' })); console.log(kvPersisted.get('user:1')); // '{"name":"Alice","role":"admin"}' ``` -------------------------------- ### Constructor Source: https://context7.com/heyputer/kv.js/llms.txt Instantiate kvjs with no arguments for a purely in-memory store, or pass a dbName option in browser environments to enable IndexedDB-backed persistence. ```APIDOC ## Constructor **Create a new KV.JS instance, optionally with IndexedDB persistence** Instantiate `kvjs` with no arguments for a purely in-memory store, or pass a `dbName` option in browser environments to enable IndexedDB-backed persistence that survives page reloads. ```javascript const kvjs = require('@heyputer/kv.js'); // Pure in-memory (Node.js or browser) const kv = new kvjs(); // Browser with IndexedDB persistence const kvPersisted = new kvjs({ dbName: 'my-app-cache', dbVersion: 1 }); // Wait for IndexedDB initialization before performing operations await kvPersisted.waitForInitialization(); kvPersisted.set('user:1', JSON.stringify({ name: 'Alice', role: 'admin' })); console.log(kvPersisted.get('user:1')); // '{"name":"Alice","role":"admin"}' ``` ``` -------------------------------- ### Basic Set Management with sadd / srem / smembers / scard / sismember Source: https://context7.com/heyputer/kv.js/llms.txt Manage set members using sadd to add, srem to remove, smembers to retrieve all, scard for count, and sismember to check existence. smismember checks multiple members efficiently. ```javascript const kv = new kvjs(); vk.sadd('tags', 'javascript', 'nodejs', 'cache'); console.log(kv.smembers('tags')); // ['javascript', 'nodejs', 'cache'] console.log(kv.scard('tags')); // 3 console.log(kv.sismember('tags', 'nodejs')); // true vk.srem('tags', 'cache'); console.log(kv.smembers('tags')); // ['javascript', 'nodejs'] // Check multiple members at once console.log(kv.smismember('tags', 'javascript', 'python', 'nodejs')); // [1, 0, 1] ``` -------------------------------- ### Get and Set Value Atomically Source: https://context7.com/heyputer/kv.js/llms.txt Atomically replace a value associated with a key and return its previous value using `getset`. ```javascript const kv = new kvjs(); kvsisted.set('status', 'inactive'); const prev = kv.getset('status', 'active'); console.log(prev); // 'inactive' console.log(kv.get('status')); // 'active' ``` -------------------------------- ### Get Value of a Key Source: https://github.com/heyputer/kv.js/blob/main/README.md Retrieve the value associated with a given key. Returns `null` if the key does not exist, has expired, or has been deleted. ```javascript kv.get('username'); // Returns the value associated with the key 'username' ``` ```javascript kv.get('nonexistent'); // Returns null ``` ```javascript kv.get('expiredKey'); // Returns null ``` ```javascript kv.set('color', 'red'); // Sets the key 'color' to the value 'red' ``` ```javascript kv.get('color'); // Returns 'red' ``` ```javascript kv.delete('deletedKey'); // Deletes the key 'deletedKey' ``` ```javascript kv.get('deletedKey'); // Returns null ``` -------------------------------- ### Key Expiration: set, expire, ttl Source: https://github.com/heyputer/kv.js/blob/main/README.md Illustrates setting a key-value pair, setting an expiration time for the key using `expire`, and then checking the remaining time-to-live (TTL) with `ttl`. `ttl` returns the time in seconds. ```javascript // Set key 'username' to 'heyputer' and set its expiration to 60 seconds kv.set('username', 'heyputer'); kv.expire('username', 60); // Check the time-to-live of key 'username' kv.ttl('username'); // Returns 60 ``` -------------------------------- ### Sorted Set Manipulation Source: https://context7.com/heyputer/kv.js/llms.txt Commands for modifying sorted sets, including incrementing scores, popping elements, getting random members, and scanning elements. ```APIDOC ## zincrby / zpopmax / zpopmin / zrandmember / zscan ### Description Provides methods for manipulating sorted sets, such as incrementing a member's score, removing and returning the highest or lowest scoring members, retrieving a random member, and iterating through elements with a cursor. ### Method kv.zincrby(key, increment, member) kv.zpopmax(key, count) kv.zpopmin(key, count) kv.zrandmember(key, count) kv.zscan(key, cursor, options) ### Parameters #### zincrby - **key** (string) - The key of the sorted set. - **increment** (number) - The amount to increment the score by. - **member** (string) - The member whose score to increment. #### zpopmax / zpopmin - **key** (string) - The key of the sorted set. - **count** (number) - The number of members to pop. #### zrandmember - **key** (string) - The key of the sorted set. - **count** (number) - The number of random members to return. #### zscan - **key** (string) - The key of the sorted set. - **cursor** (number) - The cursor for pagination. - **options** (object) - Optional parameters like `count` (number). ### Request Example ```javascript const kv = new kvjs(); kv.zadd('ratings', 4, 'itemA'); kv.zincrby('ratings', 1, 'itemB'); console.log(kv.zpopmax('ratings', 1)); console.log(kv.zpopmin('ratings', 1)); console.log(kv.zrandmember('ratings', 1)); const [cursor, entries] = kv.zscan('ratings', 0, { count: 10 }); ``` ### Response #### Success Response (zincrby) - **score** (number) - The new score of the member. #### Success Response (zpopmax / zpopmin) - **Array** - An array of [member, score] pairs that were popped. #### Success Response (zrandmember) - **Array** - An array of random members. #### Success Response (zscan) - **[cursor, entries]** - A tuple containing the next cursor and an array of [member, score] pairs. ``` -------------------------------- ### msetnx — Set multiple keys only if none exist Source: https://context7.com/heyputer/kv.js/llms.txt Atomically sets multiple key-value pairs only if none of the specified keys already exist in the store. Returns 1 if all keys were set, and 0 if any key already existed (in which case no keys are set). ```javascript const kv = new kvjs(); console.log(kv.msetnx('a', '1', 'b', '2')); // 1 — all set console.log(kv.msetnx('b', '3', 'c', '4')); // 0 — 'b' exists, nothing set console.log(kv.get('c')); // undefined ``` -------------------------------- ### mset Source: https://github.com/heyputer/kv.js/blob/main/README.md Sets the values for multiple keys simultaneously. Accepts key-value pairs as arguments. ```APIDOC ## mset ### Description Sets the values for multiple keys simultaneously. Accepts key-value pairs as arguments. ### Method `kv.mset(key1, value1, key2, value2, ..., keyN, valueN)` ### Parameters #### Path Parameters - **key1, value1, key2, value2, ..., keyN, valueN** (string, any) - Required - Pairs of keys and their corresponding values to set. ``` -------------------------------- ### Retrieve Sorted Set Elements Source: https://github.com/heyputer/kv.js/blob/main/README.md Use `kv.zrange` to get all elements from a sorted set within a specified range. The output includes the element and its score. ```javascript kv.zrange('students', 0, -1); ``` -------------------------------- ### msetnx — Set multiple keys only if none exist Source: https://context7.com/heyputer/kv.js/llms.txt Sets multiple key-value pairs atomically. The operation only succeeds if none of the specified keys already exist in the store. Returns 1 if all keys were set, and 0 if any key already existed (in which case no keys are set). ```APIDOC ## msetnx ### Description Sets all key-value pairs atomically only if none of the keys currently exist. ### Method `msetnx(key1, value1, key2, value2, ...)` ### Parameters - `key1`, `value1`, `key2`, `value2`, ...: Pairs of keys and their corresponding values to set. ### Request Example ```javascript const kv = new kvjs(); console.log(kv.msetnx('a', '1', 'b', '2')); // 1 — all set console.log(kv.msetnx('b', '3', 'c', '4')); // 0 — 'b' exists, nothing set ``` ### Response - `1`: If all key-value pairs were successfully set. - `0`: If at least one of the keys already existed, and no keys were set. ``` -------------------------------- ### Sorted Set Basics: zadd, zrem, zscore, zrank, zcard, zcount Source: https://context7.com/heyputer/kv.js/llms.txt Demonstrates basic sorted set operations including adding members, checking cardinatlity, retrieving scores and ranks, and counting members within a score range. Note that duplicate members with the same score are ignored, but updating a member's score is supported. ```javascript const kv = new kvjs(); kv.zadd('leaderboard', 1500, 'Alice'); kv.zadd('leaderboard', 2300, 'Bob'); kv.zadd('leaderboard', 1800, 'Carol'); kv.zadd('leaderboard', 2300, 'Bob'); // update score console.log(kv.zcard('leaderboard')); // 3 console.log(kv.zscore('leaderboard', 'Bob')); // 2300 console.log(kv.zrank('leaderboard', 'Alice')); // 0 (lowest score) console.log(kv.zrevrank('leaderboard', 'Bob')); // 0 (highest score) console.log(kv.zcount('leaderboard', 1500, 2000)); // 2 kv.zrem('leaderboard', 'Alice'); console.log(kv.zcard('leaderboard')); // 2 ``` -------------------------------- ### lindex / lset / linsert / lrem / ltrim Source: https://context7.com/heyputer/kv.js/llms.txt Mutate lists by getting an element at an index, setting an element at an index, inserting an element before or after another, removing elements, and trimming the list. ```APIDOC ## lindex / lset / linsert / lrem / ltrim ### Description Mutate lists by getting an element at an index, setting an element at an index, inserting an element before or after another, removing elements, and trimming the list. ### Method Not applicable (JavaScript API) ### Endpoint Not applicable (JavaScript API) ### Parameters Not applicable (JavaScript API) ### Request Example ```javascript const kv = new kvjs(); v.rpush('items', 'a', 'b', 'c', 'd', 'b'); v.lindex('items', 0); v.lindex('items', -1); v.lset('items', 1, 'B'); v.lrange('items', 0, -1); v.linsert('items', 'BEFORE', 'c', 'x'); v.lrem('items', 0, 'b'); v.ltrim('items', 0, 2); v.lrange('items', 0, -1); ``` ### Response Not applicable (JavaScript API) ``` -------------------------------- ### keys, scan, type, randomkey, touch, unlink — Search and inspect keys Source: https://context7.com/heyputer/kv.js/llms.txt Provides utilities for searching keys using glob patterns (`keys`), iterating through large datasets with a cursor (`scan`), inspecting key types (`type`), retrieving a random key (`randomkey`), and managing key existence for caching (`touch`, `unlink`). ```javascript const kv = new kvjs(); kv.mset('user:1', 'Alice', 'user:2', 'Bob', 'session:abc', 'tok'); console.log(kv.keys('user:*')); // ['user:1', 'user:2'] console.log(kv.keys('*:*')); // ['user:1', 'user:2', 'session:abc'] // Cursor-based scan (safe for large datasets) let [cursor, batch] = kv.scan(0, 'user:*', 1); console.log(batch); // ['user:1'] [cursor, batch] = kv.scan(cursor, 'user:*', 1); console.log(batch); // ['user:2'] // Type inspection kvsadd('myset', 'a'); console.log(kv.type('user:1')); // 'string' console.log(kv.type('myset')); // 'object' console.log(kv.randomkey()); // a random key console.log(kv.touch('user:1', 'user:2', 'missing')); // 2 // Async delete (alias for del) k.unlink('user:1', 'user:2'); ``` -------------------------------- ### Get the number of members in a set using scard Source: https://github.com/heyputer/kv.js/blob/main/README.md Use `scard` to retrieve the number of members in a set. Ensure the set has members added using `sadd` before calling `scard`. ```javascript // add a few members to a set kv.sadd('set1', 'member1', 'member2', 'member3'); // Output: true // print the number of members in a set kv.scard('set1'); // Output: 3 ``` -------------------------------- ### del, exists, rename, renamenx, copy — Key lifecycle Source: https://context7.com/heyputer/kv.js/llms.txt Manage the lifecycle of keys. `del` removes keys, `exists` checks for key presence, `rename` changes a key's name, `renamenx` renames only if the target key does not exist, and `copy` duplicates a key. ```javascript const kv = new kvjs(); kv.mset('a', '1', 'b', '2', 'c', '3'); console.log(kv.exists('a', 'b', 'z')); // 2 console.log(kv.del('a', 'b', 'z')); // 2 kv.set('src', 'hello'); kv.rename('src', 'dst'); console.log(kv.get('dst')); // 'hello' // kv.get('src') => undefined kv.set('x', 'data'); kv.copy('x', 'y'); console.log(kv.get('y')); // 'data' kv.set('p', 'v1'); kv.set('q', 'v2'); console.log(kv.renamenx('p', 'q')); // 0 — 'q' already exists console.log(kv.renamenx('p', 'r')); // 1 — success ``` -------------------------------- ### ttl Source: https://github.com/heyputer/kv.js/blob/main/README.md Returns the time-to-live for a key. ```APIDOC ## ttl ### Description Returns the time-to-live for a key in seconds. ### Method kv.ttl ### Parameters #### Path Parameters - **key** (string) - Required - The key to check. ### Request Example ```javascript kv.ttl('username'); ``` ### Response #### Success Response (Integer) - Returns the remaining time in seconds. ### Response Example ```javascript 60 ``` ``` -------------------------------- ### expire Source: https://github.com/heyputer/kv.js/blob/main/README.md Sets a key's time to live in seconds with optional conditions. ```APIDOC ## expire ### Description Sets a key's time to live in seconds. Supports conditional updates. ### Method `kv.expire(key, seconds, [options])` ### Parameters #### Path Parameters - **key** (string) - Required - The key to set the expiration time for. - **seconds** (number) - Required - The time to live in seconds. - **options** (object) - Optional - Conditions for setting the expiration. - **NX** (boolean) - Set only if the key does not have an expiry time. - **XX** (boolean) - Set only if the key already has an expiry time. - **GT** (boolean) - Set only if the new expiry time is greater than the current expiry time. - **LT** (boolean) - Set only if the new expiry time is less than the current expiry time. ### Request Example ```javascript // Set expiration to 60 seconds kv.expire('username', 60); // Set expiration only if key does not exist kv.expire('username', 120, {NX: true}); // Set expiration only if key already exists kv.expire('username', 180, {XX: true}); // Set expiration only if new expiry is greater than current kv.expire('username', 240, {GT: true}); // Set expiration only if new expiry is less than current kv.expire('username', 300, {LT: true}); ``` ``` -------------------------------- ### hdel / hexists / hsetnx / hstrlen — Hash field management Source: https://context7.com/heyputer/kv.js/llms.txt Functions for deleting, checking existence, setting fields conditionally, and getting the length of string values within a hash. ```APIDOC ## hdel ### Description Deletes one or more hash fields from a hash stored at `key`. Returns the number of fields that were removed. ### Method `hdel(key, field1, field2, ...)` ### Parameters - `key` (string): The hash key. - `field1`, `field2`, ...: The fields to delete from the hash. ### Request Example ```javascript const kv = new kvjs(); vk.hmset('user:1', 'name', 'Alice', 'role', 'admin', 'temp', 'x'); vk.hdel('user:1', 'temp'); console.log(kv.hexists('user:1', 'temp')); // 0 ``` ### Response - The number of fields that were removed from the hash. ``` ```APIDOC ## hexists ### Description Determines if a hash field exists. ### Method `hexists(key, field)` ### Parameters - `key` (string): The hash key. - `field` (string): The field to check for existence. ### Request Example ```javascript const kv = new kvjs(); vk.hmset('user:1', 'name', 'Alice', 'role', 'admin'); console.log(kv.hexists('user:1', 'role')); // 1 ``` ### Response - `1`: If the field exists in the hash. - `0`: If the field does not exist in the hash. ``` ```APIDOC ## hsetnx ### Description Sets the value of a field in a hash stored at `key`, only if the field does not yet exist. This operation is atomic. ### Method `hsetnx(key, field, value)` ### Parameters - `key` (string): The hash key. - `field` (string): The field to set. - `value` (string): The value to set for the field. ### Request Example ```javascript const kv = new kvjs(); vk.hmset('user:1', 'name', 'Alice'); vk.hsetnx('user:1', 'name', 'Bob'); // 0 — 'name' already exists vk.hsetnx('user:1', 'avatar', 'img.png'); // 1 — new field ``` ### Response - `1`: If the field was set successfully (i.e., it did not exist before). - `0`: If the field already existed and was not set. ``` ```APIDOC ## hstrlen ### Description Returns the length of the string value associated with a hash field. ### Method `hstrlen(key, field)` ### Parameters - `key` (string): The hash key. - `field` (string): The field whose string value length is to be measured. ### Request Example ```javascript const kv = new kvjs(); vk.hmset('user:1', 'name', 'Alice'); console.log(kv.hstrlen('user:1', 'name')); // 5 ``` ### Response - The length of the string value of the field, or `0` if the field does not exist. ``` -------------------------------- ### Set Operations: sadd, sort, smembers Source: https://github.com/heyputer/kv.js/blob/main/README.md Demonstrates adding members to a set using `sadd`, sorting them using `sort`, and retrieving all members using `smembers`. `sadd` returns true on success, while `sort` and `smembers` return arrays of members. ```javascript kv.sadd('set1', 'member1', 'member2', 'member3'); // Output: true // sort the members of a set kv.sort('set1'); // Output: ['member1', 'member2', 'member3'] ``` ```javascript // add a few members to a set kv.sadd('set1', 'member1', 'member2', 'member3'); // Output: true // print the members of a set kv.smembers('set1'); // Output: ['member1', 'member2', 'member3'] ```