### Get a Key-Value Pair Source: https://deno.land/manual/runtime/kv Retrieve a value from Deno KV using `kv.get()`. The returned `KvEntry` object contains the key, value, and versionstamp. ```APIDOC ## kv.get() ### Description Retrieves a single key-value pair from the Deno KV database. ### Method `kv.get(key: readonly (string | number | boolean | bigint | null)[]): Promise` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **key** (Array) - Required - An array representing the key to retrieve. ### Request Example ```javascript const kv = await Deno.openKv(); const entry = await kv.get(["preferences", "ada"]); console.log(entry.key); console.log(entry.value); console.log(entry.versionstamp); ``` ### Response #### Success Response (200) Returns a `KvEntry` object containing the key, value, and versionstamp, or `null` if the key does not exist. #### Response Example ```json { "key": ["preferences", "ada"], "value": { "username": "ada", "theme": "dark", "language": "en-US" }, "versionstamp": "00000000000000010000" } ``` ``` -------------------------------- ### Set and Get Display Name in Deno KV Source: https://deno.land/manual/runtime/kv Helper functions to set and retrieve user display names from Deno KV. Uses a persistent store by default. ```typescript async function setDisplayName( kv: Deno.Kv, username: string, displayname: string, ) { await kv.set(["preferences", username, "displayname"], displayname); } async function getDisplayName( kv: Deno.Kv, username: string, ): Promise { return (await kv.get(["preferences", username, "displayname"])) .value as string; } ``` -------------------------------- ### Secondary Indexes: Get by Username Source: https://deno.land/manual/runtime/kv Retrieve user preferences using the primary key (username). This function demonstrates a direct lookup using the username. ```typescript async function getByUsername(username) { // Use as before... const r = await kv.get(["preferences", username]); return r; } ``` -------------------------------- ### Get a Key-Value Pair from Deno KV Source: https://deno.land/manual/runtime/kv Retrieve a stored key-value pair using `kv.get()`. The returned `KvEntry` object contains the key, value, and versionstamp. The versionstamp is used to track updates. ```typescript const entry = await kv.get(["preferences", "ada"]); console.log(entry.key); console.log(entry.value); console.log(entry.versionstamp); ``` -------------------------------- ### Get Multiple Key-Value Pairs in Deno KV Source: https://deno.land/manual/runtime/kv Efficiently retrieve multiple key-value pairs by passing an array of keys to `kv.getMany()`. If a key does not exist, its corresponding value and versionstamp in the result will be `null`. ```typescript const kv = await Deno.openKv(); const result = await kv.getMany([ ["preferences", "ada"], ["preferences", "grace"], ]); result[0].key; // ["preferences", "ada"] result[0].value; // { ... } result[0].versionstamp; // "00000000000000010000" result[1].key; // ["preferences", "grace"] result[1].value; // null result[1].versionstamp; // null ``` -------------------------------- ### Get Multiple Key-Value Pairs Source: https://deno.land/manual/runtime/kv Efficiently retrieve multiple key-value pairs using `kv.getMany()`. It returns an array of `KvEntry` objects, where values or versionstamps can be `null` if a key is not found. ```APIDOC ## kv.getMany() ### Description Retrieves multiple key-value pairs from the Deno KV database. ### Method `kv.getMany(keys: readonly (readonly (string | number | boolean | bigint | null)[])[]): Promise>` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **keys** (Array of Arrays) - Required - An array of keys to retrieve. ### Request Example ```javascript const kv = await Deno.openKv(); const result = await kv.getMany([ ["preferences", "ada"], ["preferences", "grace"], ]); console.log(result[0].key); console.log(result[0].value); console.log(result[1].value); ``` ### Response #### Success Response (200) Returns an array of `KvEntry` objects or `null` for each requested key. #### Response Example ```json [ { "key": ["preferences", "ada"], "value": { "username": "ada", "theme": "dark", "language": "en-US" }, "versionstamp": "00000000000000010000" }, null ] ``` ``` -------------------------------- ### Secondary Indexes: Get by Email Source: https://deno.land/manual/runtime/kv Retrieve user preferences using a secondary index (email). This function first looks up the primary key using the email address and then performs a second lookup to retrieve the actual preference data. ```typescript async function getByEmail(email) { // Look up the key by email, then second lookup for actual data const r1 = await kv.get(["preferencesByEmail", email]); const r2 = await kv.get(r1.value); return r2; } ``` -------------------------------- ### Atomic Transaction: Conditional Insert Source: https://deno.land/manual/runtime/kv Execute atomic transactions to conditionally perform operations. This example creates a new preferences object only if it doesn't already exist, using `null` versionstamps to check for absence. ```typescript const kv = await Deno.openKv(); const key = ["preferences", "alan"]; const value = { username: "alan", theme: "light", language: "en-GB", }; const res = await kv.atomic() .check({ key, versionstamp: null }) // `null` versionstamps mean 'no value' .set(key, value) .commit(); if (res.ok) { console.log("Preferences did not yet exist. Inserted!"); } else { console.error("Preferences already exist."); } ``` -------------------------------- ### Test Deno KV with In-Memory Datastore Source: https://deno.land/manual/runtime/kv Use `Deno.openKv(':memory:')` to create an ephemeral Deno KV datastore for testing. This ensures tests are repeatable and isolated. ```typescript Deno.test("Preferences", async (t) => { const kv = await Deno.openKv(":memory:"); await t.step("can set displayname", async () => { let displayName = await getDisplayName(kv, "example"); assertEquals(displayName, null); await setDisplayName(kv, "example", "Exemplary User"); displayName = await getDisplayName(kv, "example"); assertEquals(displayName, "Exemplary User"); }); }); ``` -------------------------------- ### List Key-Value Pairs by Prefix Source: https://deno.land/manual/runtime/kv Use `kv.list()` to retrieve all key-value pairs that share a common prefix. The results are ordered lexicographically. ```APIDOC ## kv.list() ### Description Retrieves a stream of key-value pairs from the Deno KV database that match a given prefix. ### Method `kv.list(options?: { prefix?: readonly (string | number | boolean | bigint | null)[]; limit?: number; reverse?: boolean; }): AsyncIterableIterator ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **options** (Object) - Optional - Configuration for the list operation. - **prefix** (Array) - Optional - The prefix to filter keys by. - **limit** (number) - Optional - The maximum number of entries to return. - **reverse** (boolean) - Optional - If true, returns entries in reverse lexicographical order. ### Request Example ```javascript const kv = await Deno.openKv(); const entries = kv.list({ prefix: ["preferences"] }); for await (const entry of entries) { console.log(entry.key); console.log(entry.value); } ``` ### Response #### Success Response (200) Returns an `AsyncIterableIterator` that yields `KvEntry` objects matching the prefix. #### Response Example ```json [ { "key": ["preferences", "ada"], "value": { "username": "ada", "theme": "dark", "language": "en-US" }, "versionstamp": "00000000000000010000" } ] ``` ``` -------------------------------- ### Open and Close Deno KV Database Source: https://deno.land/manual/runtime/kv Obtain a reference to the KV database and close the connection when done. Pass an optional path to specify the database file location. ```typescript const kv = await Deno.openKv(); // Execute some queries ... kv.close(); ``` -------------------------------- ### List Key-Value Pairs with a Prefix in Deno KV Source: https://deno.land/manual/runtime/kv Retrieve all key-value pairs that share a common prefix using `kv.list()`. The entries are returned in lexicographical order based on the key components following the prefix. ```typescript const kv = await Deno.openKv(); const entries = kv.list({ prefix: ["preferences"] }); for await (const entry of entries) { console.log(entry.key); // ["preferences", "ada"] console.log(entry.value); // { ... } console.log(entry.versionstamp); // "00000000000000010000" } ``` -------------------------------- ### Watch for Deno KV Updates Source: https://deno.land/manual/runtime/kv Listen for changes on specified keys and retrieve new values. This is useful for real-time applications like chat. ```typescript let seen = ""; for await (const [messageId] of kv.watch([["last_message_id", roomId]])) { const newMessages = await Array.fromAsync(kv.list({ start: ["messages", roomId, seen, ""], end: ["messages", roomId, messageId, ""], })); await websocket.write(JSON.stringify(newMessages)); seen = messageId; } ``` -------------------------------- ### Secondary Indexes: Save Preferences Source: https://deno.land/manual/runtime/kv Implement secondary indexes to access data by multiple keys. This function saves user preferences using a primary key (username) and a secondary key (email), where the secondary index value points to the primary key. ```typescript const kv = await Deno.openKv(); async function savePreferences(prefs) { const key = ["preferences", prefs.username]; // Set the primary key const r = await kv.set(key, prefs); // Set the secondary key's value to be the primary key await kv.set(["preferencesByEmail", prefs.email], key); return r; } ``` -------------------------------- ### Set a Key-Value Pair in Deno KV Source: https://deno.land/manual/runtime/kv Use `kv.set()` to store a JavaScript object as a value associated with a key. Keys can be arrays of strings, numbers, bigints, or booleans. Values can be arbitrary JavaScript objects. ```typescript const kv = await Deno.openKv(); const prefs = { username: "ada", theme: "dark", language: "en-US", }; const result = await kv.set(["preferences", "ada"], prefs); ``` -------------------------------- ### Delete a Key-Value Pair Source: https://deno.land/manual/runtime/kv Use `kv.delete()` to remove a key from the database. No action is taken if the key does not exist. ```typescript const kv = await Deno.openKv(); await kv.delete(["preferences", "alan"]); ``` -------------------------------- ### Set a Key-Value Pair Source: https://deno.land/manual/runtime/kv Use `kv.set()` to store a JavaScript object as a value for a given key. Keys are arrays of JavaScript types, and values can be arbitrary objects. This method also updates existing entries. ```APIDOC ## kv.set() ### Description Stores a key-value pair in the Deno KV database. If the key already exists, its value will be updated. ### Method `kv.set(key: readonly (string | number | boolean | bigint | null)[], value: any): Promise ` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **key** (Array) - Required - An array representing the key. Can contain strings, numbers, bigints, booleans, or null. - **value** (any) - Required - The JavaScript object to store as the value. ### Request Example ```javascript const kv = await Deno.openKv(); const prefs = { username: "ada", theme: "dark", language: "en-US", }; await kv.set(["preferences", "ada"], prefs); ``` ### Response #### Success Response (200) Returns a `KvCommitResult` object containing information about the commit. #### Response Example ```json { "versionstamp": "00000000000000010000" } ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.