### Get All Keys from Unstorage Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/1.guide/1.index.md Illustrates how to retrieve a list of all keys currently stored. Meta keys are filtered out, and an optional base can be provided to restrict results. ```javascript await storage.getKeys(); // Alias: await storage.keys(); ``` -------------------------------- ### getKeys Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/1.guide/1.index.md Retrieves all keys currently stored. ```APIDOC ## getKeys / keys ### Description Get all keys. Returns an array of strings. Meta keys (ending with `$`) will be filtered. If a base is provided, only keys starting with the base will be returned and only mounts starting with base will be queried. Keys still have a full path. ### Method `getKeys(base?, opts?) `keys(base?, opts?) ### Parameters #### Path Parameters - **base** (string) - Optional - If provided, filters keys starting with this base. - **opts** (object) - Optional - Additional options. ``` -------------------------------- ### Unstorage Initialization Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/1.guide/1.index.md Demonstrates how to create an instance of unstorage, optionally specifying a driver. ```APIDOC ## Unstorage Initialization ### Description Initializes the unstorage with an optional configuration object. ### Method `createStorage(opts?) ### Parameters #### Request Body - **opts** (object) - Optional - Configuration options for the storage instance. - **driver** (object) - Optional - The storage driver to use. Defaults to the memory driver if not provided. ``` -------------------------------- ### Initialize Unstorage with MongoDB Driver (Node.js) Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/2.drivers/mongodb.md Demonstrates how to create an Unstorage instance using the MongoDB driver. Requires the 'mongodb' package to be installed. This example shows the basic setup with connection string, database name, and collection name. ```javascript import { createStorage } from "unstorage"; import mongodbDriver from "unstorage/drivers/mongodb"; const storage = createStorage({ driver: mongodbDriver({ connectionString: "CONNECTION_STRING", databaseName: "test", collectionName: "test", }), }); ``` -------------------------------- ### Getting Mount Information by Key in Unstorage Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/1.guide/1.index.md Illustrates how to retrieve the mount point (driver and base) for a specific key within the Unstorage instance. This is useful for understanding which driver is responsible for a given key. ```javascript storage.mount("cache" /* ... */); storage.mount("cache:routes" /* ... */); storage.getMount("cache:routes:foo:bar"); // => { base: "cache:routes:", driver: "..." } ``` -------------------------------- ### getItems Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/1.guide/1.index.md Retrieves multiple items from storage in parallel (experimental). ```APIDOC ## getItems ### Description (Experimental) Gets the value of multiple keys in storage in parallel. Each item in the array can either be a string or an object with `{ key, options? }` format. Returned value is a Promise resolving to an array of objects with `{ key, value }` format. ### Method `getItems(items, opts) ### Parameters #### Request Body - **items** (Array) - Required - An array of keys or objects with key and options. - **opts** (object) - Optional - Additional options. ``` -------------------------------- ### clear Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/1.guide/1.index.md Removes all stored key/values. Can optionally clear based on a prefix. ```APIDOC ## clear ### Description Removes all stored key/values. If a base is provided, only mounts matching base will be cleared. ### Method `clear(base?, opts?) ### Parameters #### Path Parameters - **base** (string) - Optional - If provided, only clears storage entries matching this base prefix. - **opts** (object) - Optional - Additional options. ``` -------------------------------- ### getMeta Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/1.guide/1.index.md Retrieves metadata for a specific key. ```APIDOC ## getMeta ### Description Get metadata object for a specific key. This data is fetched from two sources: Driver native meta (like file creation time) and Custom meta set by `storage.setMeta` (overrides driver native meta). ### Method `getMeta(key, opts = { nativeOnly? }) ### Parameters #### Path Parameters - **key** (string) - Required - The key to get metadata for. - **opts** (object) - Optional - Options object. - **nativeOnly** (boolean) - Optional - If true, only returns driver native meta. ``` -------------------------------- ### Create Unstorage Instance and Get Item Source: https://github.com/fahreddinozcan/unstorage/blob/main/README.md Shows how to import and create an instance of Unstorage using `createStorage`. It also includes an example of retrieving an item from storage using `getItem`, demonstrating basic usage. ```javascript import { createStorage } from "unstorage"; const storage = createStorage(/* opts */); await storage.getItem("foo:bar"); // or storage.getItem('/foo/bar') ``` -------------------------------- ### dispose Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/1.guide/1.index.md Disposes all mounted storages, closing any open handles. ```APIDOC ## dispose ### Description Disposes all mounted storages to ensure there are no open-handles left. Call it before exiting the process. Note: Dispose also clears in-memory data. ### Method `dispose() ``` -------------------------------- ### Mounting Storage Drivers with Unstorage Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/1.guide/1.index.md Demonstrates how to mount additional storage drivers, such as the file system driver, to a Unstorage instance. Mounted drivers are used for keys that start with the specified mountpoint. Options like `readOnly` and `noClear` can disable write and clear operations. ```javascript import { createStorage } from "unstorage"; import fsDriver from "unstorage/drivers/fs"; // Create a storage container with default memory storage const storage = createStorage({}); storage.mount("/output", fsDriver({ base: "./output" })); // Writes to ./output/test file await storage.setItem("/output/test", "works"); // Adds value to in-memory storage await storage.setItem("/foo", "bar"); ``` -------------------------------- ### setItems Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/1.guide/1.index.md Adds or updates multiple items in storage in parallel (experimental). ```APIDOC ## setItems ### Description (Experimental) Add/Update items in parallel to the storage. Each item in `items` array should be in `{ key, value, options? }` format. Returned value is a Promise resolving to an array of objects with `{ key, value }` format. ### Method `setItems(items, opts) ### Parameters #### Request Body - **items** (Array) - Required - An array of objects, each containing `key`, `value`, and optional `options`. - **opts** (object) - Optional - Additional options. ``` -------------------------------- ### Get Metadata for a Key in Unstorage Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/1.guide/1.index.md Explains how to retrieve metadata associated with a storage key. This metadata can be driver-specific (like file timestamps) or custom metadata set via `setMeta`. ```javascript // For fs driver returns an object like { mtime, atime, size } await storage.getMeta("foo:bar"); ``` -------------------------------- ### Watching for Storage Events with Unstorage Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/1.guide/1.index.md Shows how to start watching for events across all mountpoints in Unstorage. If a driver does not support watching, events are only emitted when `storage.*` methods are called. The returned `unwatch` function can be used to stop the watcher. ```javascript const unwatch = await storage.watch((event, key) => {}); // to stop this watcher await unwatch(); ``` -------------------------------- ### Unmounting Storage Drivers in Unstorage Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/1.guide/1.index.md Provides an example of how to unregister a mountpoint from a Unstorage instance. This function has no effect if the mountpoint is not found or if it is the root mountpoint. ```javascript await storage.unmount("/output"); ``` -------------------------------- ### getItem / get Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/1.guide/1.index.md Retrieves the value associated with a given key from storage. ```APIDOC ## getItem / get ### Description Gets the value of a key in storage. Resolves to either a JavaScript primitive value or `null`. ### Method `getItem(key, opts?) `get(key, opts?) ### Parameters #### Path Parameters - **key** (string) - Required - The key whose value to retrieve. - **opts** (object) - Optional - Additional options. ``` -------------------------------- ### setItem / set Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/1.guide/1.index.md Adds or updates a value for a given key in storage. ```APIDOC ## setItem / set ### Description Adds or updates a value to the storage. If the value is not a string, it will be stringified. If the value is `undefined`, it is the same as calling `removeItem(key)`. ### Method `setItem(key, value, opts?) `set(key, value, opts?) ### Parameters #### Path Parameters - **key** (string) - Required - The key to set. - **value** (any) - Required - The value to store. - **opts** (object) - Optional - Additional options. ``` -------------------------------- ### Getting All Mount Points by Base in Unstorage Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/1.guide/1.index.md Explains how to retrieve all mount points associated with a specific base path. The `parents` option can be used to include parent mount points in the result. ```javascript storage.mount("cache" /* ... */); storage.mount("cache:sub" /* ... */); storage.getMounts("cache:sub"); // => [{ base: "cache:sub", driver }] storage.getMounts("cache:"); // => [{ base: "cache:sub", driver }, { base: "cache:", driver }] storage.getMounts(""); storage.getMounts("cache:sub", { parents: true }); // => [{ base: "cache:sub", driver }, { base: "cache:", driver }, { base: "", driver }] ``` -------------------------------- ### Dispose Unstorage Instance Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/1.guide/1.index.md Shows how to properly dispose of the unstorage instance to release any open handles, especially important before exiting a process. This action also clears in-memory data. ```javascript await storage.dispose(); ``` -------------------------------- ### Install Unstorage Package Source: https://github.com/fahreddinozcan/unstorage/blob/main/README.md Demonstrates how to install the unstorage npm package using different package managers (yarn, npm, pnpm). This is a prerequisite for using the library. ```sh # yarn yarn add unstorage # npm npm install unstorage # pnpm pnpm add unstorage ``` -------------------------------- ### Initialize Unstorage with Capacitor Preferences Driver Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/2.drivers/capacitor-preferences.md This snippet demonstrates how to create an Unstorage instance using the Capacitor Preferences driver. It requires installing `@capacitor/preferences` and shows the import and initialization process. The `base` option is used to prefix keys, preventing potential collisions. ```javascript import { createStorage } from "unstorage"; import capacitorPreferences from "unstorage/drivers/capacitor-preferences"; const storage = createStorage({ driver: capacitorPreferences({ base: "test", }), }); ``` -------------------------------- ### Retrieve Raw Item Value from Unstorage Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/1.guide/1.index.md Demonstrates retrieving an item's value in its raw format, which can be useful for binary data or specific driver formats. This is an experimental feature. ```javascript // Value can be a Buffer, Array or Driver's raw format const value = await storage.getItemRaw("foo:bar.bin"); ``` -------------------------------- ### Typing Subsets with prefixStorage in Unstorage Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/1.guide/1.index.md Demonstrates how to create a type-safe, prefixed storage instance using `prefixStorage`. This allows you to define specific types for data stored under a particular prefix, enhancing data integrity. ```typescript const storage = createStorage(); const htmlStorage = prefixStorage(storage, "assets:html"); await htmlStorage.getItem("foo.html"); // => type Post = { title: string; content: string; }; const postStorage = prefixStorage(storage, "assets:posts"); await postStorage.getItem("foo.json"); // => ``` -------------------------------- ### Initialize Unstorage with Vercel KV Driver Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/2.drivers/vercel.md This snippet demonstrates how to create an Unstorage instance using the Vercel KV driver. It shows the necessary import and the basic configuration, including optional parameters for URL, token, base, environment prefix, and TTL. Ensure `@vercel/kv` is installed. ```javascript import { createStorage } from "unstorage"; import vercelKVDriver from "unstorage/drivers/vercel-kv"; const storage = createStorage({ driver: vercelKVDriver({ // url: "https://.kv.vercel-storage.com", // KV_REST_API_URL // token: "", // KV_REST_API_TOKEN // base: "test", // env: "KV", // ttl: 60, // in seconds }), }); ``` -------------------------------- ### removeMeta Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/1.guide/1.index.md Removes metadata for a specific key. ```APIDOC ## removeMeta ### Description Remove meta for a specific key by adding a `$` suffix. Equivalent to `storage.removeItem('key$')`. ### Method `removeMeta(key, opts?) ### Parameters #### Path Parameters - **key** (string) - Required - The key whose metadata to remove. - **opts** (object) - Optional - Additional options. ``` -------------------------------- ### setMeta Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/1.guide/1.index.md Sets custom metadata for a specific key. ```APIDOC ## setMeta ### Description Set custom meta for a specific key by adding a `$` suffix. Equivalent to `storage.setItem('key$', metaValue)`. ### Method `setMeta(key, opts?) ### Parameters #### Path Parameters - **key** (string) - Required - The key to set metadata for. - **opts** (object) - Optional - The metadata object to set. ``` -------------------------------- ### hasItem / has Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/1.guide/1.index.md Checks if a specific key exists in the storage. ```APIDOC ## hasItem / has ### Description Checks if storage contains a key. Resolves to either `true` or `false`. ### Method `hasItem(key, opts?) `has(key, opts?) ### Parameters #### Path Parameters - **key** (string) - Required - The key to check for. - **opts** (object) - Optional - Additional options. ``` -------------------------------- ### Creating a Typed Unstorage Instance Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/1.guide/1.index.md Illustrates how to create a Unstorage instance with a specified generic type, ensuring that all subsequent `getItem` calls return that type and `setItem` calls adhere to it. This provides a type-safe storage container. ```typescript const storage = createStorage(); await storage.getItem("k"); // => storage.setItem("k", "val"); // Check ok storage.setItem("k", 123); // TS error ``` -------------------------------- ### getItemRaw Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/1.guide/1.index.md Retrieves the raw value of a key from storage (experimental). ```APIDOC ## getItemRaw ### Description (Experimental) Gets the value of a key in storage in raw format. The value can be a Buffer, Array, or the driver's raw format. ### Method `getItemRaw(key, opts?) ### Parameters #### Path Parameters - **key** (string) - Required - The key whose raw value to retrieve. - **opts** (object) - Optional - Additional options. ``` -------------------------------- ### Stopping All Watchers in Unstorage Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/1.guide/1.index.md Demonstrates how to stop all active watchers on all mountpoints within Unstorage. ```javascript await storage.unwatch(); ``` -------------------------------- ### Retrieve Item Value from Unstorage Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/1.guide/1.index.md Illustrates how to retrieve the value associated with a given key from storage. It resolves to the stored value or null if the key is not found. Both `getItem` and its alias `get` are available. ```javascript await storage.getItem("foo:bar"); // Alias: await storage.get("foo:bar"); ``` -------------------------------- ### Set Custom Metadata for a Key in Unstorage Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/1.guide/1.index.md Demonstrates how to set custom metadata for a key by appending a `$` suffix to the key. This is equivalent to using `setItem` with a suffixed key. ```javascript await storage.setMeta("foo:bar", { flag: 1 }); // Same as storage.setItem('foo:bar$', { flag: 1 }) ``` -------------------------------- ### Clear All Storage Contents in Unstorage Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/1.guide/1.index.md Explains how to remove all key-value pairs from storage. An optional base can be provided to clear only specific mounted storage areas. ```javascript await storage.clear(); ``` -------------------------------- ### setItemRaw Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/1.guide/1.index.md Adds or updates a value in raw format to storage (experimental). ```APIDOC ## setItemRaw ### Description (Experimental) Add/Update a value to the storage in raw format. If value is `undefined`, it is the same as calling `removeItem(key)`. ### Method `setItemRaw(key, value, opts?) ### Parameters #### Path Parameters - **key** (string) - Required - The key to set. - **value** (any) - Required - The raw value to store (e.g., Buffer, Uint8Array). - **opts** (object) - Optional - Additional options. ``` -------------------------------- ### removeItem / remove / del Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/1.guide/1.index.md Removes a key and its associated value from storage. ```APIDOC ## removeItem / remove / del ### Description Removes a value (and its meta) from storage. ### Method `removeItem(key, opts = { removeMeta = false }) `remove(key, opts) `del(key, opts) ### Parameters #### Path Parameters - **key** (string) - Required - The key to remove. - **opts** (object) - Optional - Options object. Can include `removeMeta` (boolean). - **removeMeta** (boolean) - Optional - If true, removes associated metadata as well. Defaults to `false`. ``` -------------------------------- ### Unstorage Redis Driver: Single Instance Configuration Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/2.drivers/redis.md This snippet demonstrates how to initialize the Unstorage with the Redis driver for a single Redis instance. It requires 'ioredis' to be installed and specifies connection details like base namespace, host, TLS, port, and password. ```javascript import { createStorage } from "unstorage"; import redisDriver from "unstorage/drivers/redis"; const storage = createStorage({ driver: redisDriver({ base: "unstorage", host: 'HOSTNAME', tls: true as any, port: 6380, password: 'REDIS_PASSWORD' }), }); ``` -------------------------------- ### Initialize Unstorage with Azure App Configuration Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/2.drivers/azure.md Demonstrates how to set up Unstorage to use Azure App Configuration as a key-value store. It requires installing `@azure/app-configuration` and `@azure/identity`. The configuration includes the app configuration store name, an optional label for environment differentiation, and an optional prefix for application isolation. ```javascript import { createStorage } from "unstorage"; import azureAppConfiguration from "unstorage/drivers/azure-app-configuration"; const storage = createStorage({ driver: azureAppConfiguration({ appConfigName: "unstoragetest", label: "dev", prefix: "app01", }), }); ``` -------------------------------- ### Install PlanetScale Database Package Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/2.drivers/planetscale.md This snippet shows the npm dependency to install the PlanetScale database package required for the Unstorage driver. It ensures the necessary library for interacting with PlanetScale is available in your project. ```json { "dependencies": { "@planetscale/database": "^1.5.0" } } ``` -------------------------------- ### Check for Item Existence in Unstorage Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/1.guide/1.index.md Shows how to check if a specific key exists within the storage. It supports both `hasItem` and its alias `has` for improved readability. ```javascript await storage.hasItem("foo:bar"); // Alias: await storage.has("foo:bar"); ``` -------------------------------- ### Remove Item from Unstorage Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/1.guide/1.index.md Details how to remove a key and its associated value from storage. It supports removing metadata as well and provides `removeItem`, `remove`, and `del` aliases. ```javascript await storage.removeItem("foo:bar", { removeMeta: true }); // same as await storage.removeItem("foo:bar", true); // Aliases: await storage.remove("foo:bar"); await storage.del("foo:bar"); ``` -------------------------------- ### Install Vercel KV Dependency Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/2.drivers/vercel.md This JSON snippet shows the necessary addition to your project's `package.json` to include the `@vercel/kv` dependency, which is required to use the Vercel KV driver with Unstorage. ```json { "dependencies": { "@vercel/kv": "latest" } } ``` -------------------------------- ### Store or Update Item in Unstorage Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/1.guide/1.index.md Explains how to add a new key-value pair or update the value of an existing key. Non-string values are stringified, and `undefined` values result in item removal. Supports both `setItem` and its alias `set`. ```javascript await storage.setItem("foo:bar", "baz"); // Alias: await storage.set("foo:bar", "baz"); ``` -------------------------------- ### Remove Metadata for a Key in Unstorage Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/1.guide/1.index.md Shows how to remove metadata associated with a key by appending a `$` suffix. This is equivalent to using `removeItem` with a suffixed key. ```javascript await storage.removeMeta("foo:bar"); // Same as storage.removeItem('foo:bar$') ``` -------------------------------- ### Typed getItem and getItemRaw in Unstorage Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/1.guide/1.index.md Shows how to use generic types with `getItem` and `getItemRaw` methods in Unstorage to specify the expected return type. This enhances type safety when retrieving data. ```typescript await storage.getItem("k"); // => await storage.getItemRaw("k"); // => ``` -------------------------------- ### Install Netlify Blobs Dependency Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/2.drivers/netlify.md Specifies the necessary dependency for using the Netlify Blobs driver with Unstorage. This includes installing `@netlify/blobs` as a devDependency in your project's `package.json`. ```json { "devDependencies": { "@netlify/blobs": "latest" } } ``` -------------------------------- ### Store Raw Item Value in Unstorage Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/1.guide/1.index.md Shows how to store a value in its raw format, suitable for binary data. If the value is `undefined`, the item is removed. This is an experimental feature. ```javascript await storage.setItemRaw("data/test.bin", new Uint8Array([1, 2, 3])); ``` -------------------------------- ### Handling Null with Strict Mode in Unstorage Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/1.guide/1.index.md Explains that in strict mode, `getItem` in Unstorage will also return `null` to help handle cases where an item might be missing. This encourages explicit handling of potentially absent data. ```typescript "use strict"; await storage.getItem("k"); // => ``` -------------------------------- ### Create Storage with Cloudflare R2 Binding Driver (JS) Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/2.drivers/cloudflare.md Illustrates setting up unstorage with the Cloudflare R2 binding driver. This driver is specifically for Cloudflare Workers environments and uses R2 bucket bindings. Examples show binding by name, direct binding object, and through environment variables. ```javascript import { createStorage } from "unstorage"; import cloudflareR2BindingDriver from "unstorage/drivers/cloudflare-r2-binding"; // Using binding name to be picked from globalThis const storage = createStorage({ driver: cloudflareR2BindingDriver({ binding: "BUCKET" }), }); // Directly setting binding const storage = createStorage({ driver: cloudflareR2BindingDriver({ binding: globalThis.BUCKET }), }); // Using from Durable Objects and Workers using Modules Syntax const storage = createStorage({ driver: cloudflareR2BindingDriver({ binding: this.env.BUCKET }), }); ``` -------------------------------- ### Type Checking setItem Parameters in Unstorage Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/1.guide/1.index.md Demonstrates how TypeScript's type checking works with the `setItem` and `setItemRaw` methods in Unstorage. Mismatched types between the expected type parameter and the provided value will result in a TypeScript error. ```typescript storage.setItem("k", "val"); // check ok storage.setItemRaw("k", "val"); // check ok storage.setItem("k", 123); // ts error storage.setItemRaw("k", 123); // ts error ``` -------------------------------- ### TypeScript Error with Generic Type Mismatch Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/1.guide/1.index.md Highlights a TypeScript error scenario where attempting to set a value with a type that is incompatible with the storage instance's generic type parameter will result in an error. This reinforces type safety. ```typescript const storage = createStorage(); storage.setItem("k", 123); // TS error: is not compatible with ``` -------------------------------- ### Initialize Unstorage with Azure Cosmos DB Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/2.drivers/azure.md Shows how to configure Unstorage to persist data in Azure Cosmos DB using its NoSQL API. This requires installing `@azure/cosmos` and `@azure/identity`. The setup involves providing the Cosmos DB endpoint and account key, or relying on `DefaultAzureCredential` for authentication. Optional parameters include database and container names. ```javascript import { createStorage } from "unstorage"; import azureCosmos from "unstorage/drivers/azure-cosmos"; const storage = createStorage({ driver: azureCosmos({ endpoint: "ENDPOINT", accountKey: "ACCOUNT_KEY", }), }); ``` -------------------------------- ### Initialize Unstorage with Azure Table Storage Driver Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/2.drivers/azure.md Demonstrates how to create an unstorage instance using the Azure Table Storage driver. Requires installation of '@azure/data-table' and '@azure/identity'. The driver stores data in Azure Table Storage using a fixed partition key. ```javascript import { createStorage } from "unstorage"; import azureStorageTableDriver from "unstorage/drivers/azure-storage-table"; const storage = createStorage({ driver: azureStorageTableDriver({ accountName: "myazurestorageaccount", }), }); ``` -------------------------------- ### Integrate Azure Blob Storage with Unstorage Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/2.drivers/azure.md This driver stores Key Vault information in an Azure blob storage blob. It requires `@azure/storage-blob` and `@azure/identity` to be installed. Each entry is stored in a separate blob within a specified container. ```javascript import { createStorage } from "unstorage"; import azureStorageBlobDriver from "unstorage/drivers/azure-storage-blob"; const storage = createStorage({ driver: azureStorageBlobDriver({ accountName: "myazurestorageaccount", }), }); ``` -------------------------------- ### Integrate Azure Key Vault Secrets with Unstorage Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/2.drivers/azure.md This driver stores Key Vault information in Azure Key Vault secrets. It requires `@azure/keyvault-secrets` and `@azure/identity` to be installed. Keys are encoded to avoid naming conflicts. Access time may be slower than other storage solutions. ```javascript import { createStorage } from "unstorage"; import azureKeyVault from "unstorage/drivers/azure-key-vault"; const storage = createStorage({ driver: azureKeyVault({ vaultName: "testunstoragevault", }), }); ``` -------------------------------- ### Initialize unstorage with GitHub Driver Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/2.drivers/github.md This snippet demonstrates how to initialize the unstorage with the GitHub driver. It requires the repository and branch information, with an option to specify a directory. A GitHub token is recommended to avoid rate limiting. ```javascript import { createStorage } from "unstorage"; import githubDriver from "unstorage/drivers/github"; const storage = createStorage({ driver: githubDriver({ repo: "nuxt/nuxt", branch: "main", dir: "/docs", }), }); ``` -------------------------------- ### HTTP Storage Driver Usage Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/2.drivers/http.md Demonstrates how to import and initialize the unstorage HTTP driver with a base URL. ```APIDOC ## HTTP Storage Driver ### Description This driver allows you to use a remote HTTP/HTTPS endpoint as a data storage for `unstorage`. It implements meta information for each key, such as modification time and status, by performing `HEAD` requests. ### Usage Example ```javascript import { createStorage } from "unstorage"; import httpDriver from "unstorage/drivers/http"; const storage = createStorage({ driver: httpDriver({ base: "http://cdn.com" }), }); ``` ### Options - `base`: (string, required) The base URL for all HTTP requests. - `headers`: (object, optional) Custom headers to be included in all requests made by this driver. ### Supported Operations - **`getItem(key)`**: Maps to an HTTP `GET` request. Returns the deserialized value if the response status is OK. - **`hasItem(key)`**: Maps to an HTTP `HEAD` request. Returns `true` if the response status is OK (200). - **`getMeta(key)`**: Maps to an HTTP `HEAD` request. Extracts `mtime` from the `Last-Modified` header and `ttl` from the `X-TTL` header. - **`setItem(key, value, options)`**: Maps to an HTTP `PUT` request. The serialized `value` is sent in the request body. The `ttl` option (in seconds) will be sent as an `X-TTL` header. - **`removeItem(key)`**: Maps to an HTTP `DELETE` request. - **`clear()`**: This operation is not supported by the HTTP driver. ### Transaction Options When performing operations, you can provide transaction-specific options: - `headers`: (object, optional) Custom headers to be sent with a specific operation. - `ttl`: (number, optional) Custom Time-To-Live in seconds for the operation. This will be mapped to the `X-TTL` HTTP header. ``` -------------------------------- ### Create Local Storage Instance (JavaScript) Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/2.drivers/browser.md This snippet demonstrates how to create a storage instance using the Unstorage Local Storage driver. It configures the storage with a base key prefix to prevent collisions and optionally accepts a localStorage object or window object. ```javascript import { createStorage } from "unstorage"; import localStorageDriver from "unstorage/drivers/localstorage"; const storage = createStorage({ driver: localStorageDriver({ base: "app:" }), }); ``` -------------------------------- ### Configure Unstorage with PlanetScale Driver Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/2.drivers/planetscale.md This JavaScript code demonstrates how to initialize Unstorage with the PlanetScale driver. It requires a database URL and optionally accepts a table name and cache boost configuration. ```javascript import { createStorage } from "unstorage"; import planetscaleDriver from "unstorage/drivers/planetscale"; const storage = createStorage({ driver: planetscaleDriver({ // This should certainly not be inlined in your code but loaded via runtime config // or environment variables depending on your framework/project. url: "mysql://xxxxxxxxx:************@xxxxxxxxxx.us-east-3.psdb.cloud/my-database?sslaccept=strict", // table: 'storage' }), }); ``` -------------------------------- ### Create Unstorage Overlay with Memory and FS Drivers Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/2.drivers/overlay.md Demonstrates creating an Unstorage instance using the overlay driver, with an in-memory layer on top of an fs layer. Writes go to memory, reads check both. No direct disk writes occur for new keys. ```javascript import { createStorage } from "unstorage"; import overlay from "unstorage/drivers/overlay"; import memory from "unstorage/drivers/memory"; import fs from "unstorage/drivers/fs"; const storage = createStorage({ driver: overlay({ layers: [memory(), fs({ base: "./data" })], }), }); ``` -------------------------------- ### Initialize unstorage with LRU Cache Driver Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/2.drivers/lru-cache.md Demonstrates how to create an unstorage instance configured to use the LRU cache driver. This requires importing both `createStorage` from 'unstorage' and the `lruCacheDriver` from 'unstorage/drivers/lru-cache'. The driver is then passed as an option to `createStorage`. ```javascript import { createStorage } from "unstorage"; import lruCacheDriver from "unstorage/drivers/lru-cache"; const storage = createStorage({ driver: lruCacheDriver(), }); ``` -------------------------------- ### Create unstorage HTTP Server with listhen Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/1.guide/3.http-server.md Programmatically creates an HTTP server for unstorage, exposing methods to communicate with a storage instance. It uses `listhen` for the HTTP listener and `h3` for the server framework. An `authorize` function can be implemented for security. ```javascript import { listen } from "listhen"; import { createStorage } from "unstorage"; import { createStorageServer } from "unstorage/server"; const storage = createStorage(); const storageServer = createStorageServer(storage, { authorize(req) { // req: { key, type, event } if (req.type === "read" && req.key.startsWith("private:")) { throw new Error("Unauthorized Read"); } }, }); // Alternatively we can use `storageServer.handle` as a middleware await listen(storageServer.handle); ``` -------------------------------- ### Create Deploy-Scoped Netlify Blobs Storage Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/2.drivers/netlify.md Sets up Unstorage with a deploy-scoped Netlify Blobs store. Ideal for builds, this store is managed alongside the deploy and is automatically deleted or rolled back with it. Requires `@netlify/blobs` dependency. ```javascript import { createStorage } from "unstorage"; import netlifyBlobsDriver from "unstorage/drivers/netlify-blobs"; const storage = createStorage({ driver: netlifyBlobsDriver({ deployScoped: true, }), }); ``` -------------------------------- ### Create Session Storage Instance (JavaScript) Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/2.drivers/browser.md This snippet shows how to initialize Unstorage with the Session Storage driver. Similar to Local Storage, it allows setting a base key prefix and accepting optional sessionStorage or window objects. ```javascript import { createStorage } from "unstorage"; import sessionStorageDriver from "unstorage/drivers/session-storage"; const storage = createStorage({ driver: sessionStorageDriver({ base: "app:" }), }); ``` -------------------------------- ### Create IndexedDB Instance (JavaScript) Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/2.drivers/browser.md This snippet illustrates the creation of an Unstorage instance using the IndexedDB driver. It requires the 'idb-keyval' package and allows customization of the database and store names, along with a base key prefix. Note that this driver is intended for browser environments only. ```javascript import { createStorage } from "unstorage"; import indexedDbDriver from "unstorage/drivers/indexedb"; const storage = createStorage({ driver: indexedDbDriver({ base: "app:" }), }); ``` -------------------------------- ### Create Unstorage with Node.js Filesystem Driver Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/2.drivers/fs.md Initializes Unstorage with the filesystem driver, mapping data to the real filesystem. It supports watching via chokidar and retrieves file metadata like mtime, atime, and size using fs.stat. The 'base' option specifies the root directory for storage operations. ```javascript import { createStorage } from "unstorage"; import fsDriver from "unstorage/drivers/fs"; const storage = createStorage({ driver: fsDriver({ base: "./tmp" }), }); ``` -------------------------------- ### Create Unstorage with Lite Node.js Filesystem Driver Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/2.drivers/fs.md Initializes Unstorage using a Lite filesystem driver that relies solely on pure Node.js APIs without additional dependencies. The 'base' option defines the root directory for storage, and an optional 'ignore' callback can be provided to filter paths. ```javascript import { createStorage } from "unstorage"; import fsLiteDriver from "unstorage/drivers/fs-lite"; const storage = createStorage({ driver: fsLiteDriver({ base: "./tmp" }), }); ``` -------------------------------- ### Create Storage with Cloudflare KV HTTP Driver (JS) Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/2.drivers/cloudflare.md Demonstrates creating a unstorage instance using the Cloudflare KV HTTP driver. It showcases authentication using apiToken, email/apiKey, and userServiceKey. This driver works universally but is recommended for non-worker environments. ```javascript import { createStorage } from "unstorage"; import cloudflareKVHTTPDriver from "unstorage/drivers/cloudflare-kv-http"; // Using `apiToken` const storage = createStorage({ driver: cloudflareKVHTTPDriver({ accountId: "my-account-id", namespaceId: "my-kv-namespace-id", apiToken: "supersecret-api-token", }), }); // Using `email` and `apiKey` const storage = createStorage({ driver: cloudflareKVHTTPDriver({ accountId: "my-account-id", namespaceId: "my-kv-namespace-id", email: "me@example.com", apiKey: "my-api-key", }), }); // Using `userServiceKey` const storage = createStorage({ driver: cloudflareKVHTTPDriver({ accountId: "my-account-id", namespaceId: "my-kv-namespace-id", userServiceKey: "v1.0-my-service-key", }), }); ``` -------------------------------- ### Create Namespaced Storage Instance with Unstorage Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/1.guide/2.utils.md The `prefixStorage` utility creates a namespaced instance of a main storage. This is useful for creating shortcuts and limiting access to specific storage segments. It takes the main storage instance and a prefix string as input. Operations on the namespaced storage are virtually prefixed, simplifying key management. ```typescript import { createStorage, prefixStorage } from "unstorage"; const storage = createStorage(); const assetsStorage = prefixStorage(storage, "assets"); // Same as storage.setItem('assets:x', 'hello!') await assetsStorage.setItem("x", "hello!"); ``` -------------------------------- ### Initialize Netlify Edge Function Storage Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/2.drivers/netlify.md Demonstrates initializing Unstorage with the Netlify Blobs driver within a Netlify edge function using a URL import. This is for cases where you are creating your own edge functions and not using a framework compiler. Requires `@netlify/blobs`. ```javascript import { createStorage } from "https://esm.sh/unstorage"; import netlifyBlobsDriver from "https://esm.sh/unstorage/drivers/netlify-blobs"; export default async function handler(request: Request) { const storage = createStorage({ driver: netlifyBlobsDriver({ name: "blob-store-name", }), }); // ... ``` -------------------------------- ### Create Netlify Blobs Storage Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/2.drivers/netlify.md Initializes Unstorage with the Netlify Blobs driver for a named store. Requires `@netlify/blobs` dependency. The `name` option specifies the store, which is created if it doesn't exist. ```javascript import { createStorage } from "unstorage"; import netlifyBlobsDriver from "unstorage/drivers/netlify-blobs"; const storage = createStorage({ driver: netlifyBlobsDriver({ name: "blob-store-name", }), }); ``` -------------------------------- ### Initialize unstorage with HTTP Driver Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/2.drivers/http.md This snippet demonstrates how to create an unstorage instance using the HTTP driver. It requires a base URL for the remote endpoint and can optionally include custom headers for all requests. ```javascript import { createStorage } from "unstorage"; import httpDriver from "unstorage/drivers/http"; const storage = createStorage({ driver: httpDriver({ base: "http://cdn.com" }), }); ``` -------------------------------- ### Connect to unstorage HTTP Server with http driver Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/1.guide/3.http-server.md Establishes a connection to an unstorage HTTP server using the provided http driver. This allows remote interaction with the storage instance, enabling operations like fetching keys. ```typescript import { createStorage } from "unstorage"; import httpDriver from "unstorage/drivers/http"; const client = createStorage({ driver: httpDriver({ base: "SERVER_ENDPOINT", }), }); const keys = await client.getKeys(); ``` -------------------------------- ### Create PlanetScale Storage Table Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/2.drivers/planetscale.md This SQL query defines the schema for a table in a PlanetScale database to be used with Unstorage. It includes columns for id, value, creation, and update timestamps, suitable for key-value storage. ```sql create table ( id varchar(255) not null primary key, value longtext, created_at timestamp default current_timestamp, updated_at timestamp default current_timestamp on update current_timestamp ); ``` -------------------------------- ### Migrate Netlify Blobs Store Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/2.drivers/netlify.md Command to migrate global blob stores in `@netlify/blobs` version `7.0.0` and later. Use this command in your project directory with the latest Netlify CLI to ensure compatibility with older global stores. ```sh netlify recipes blobs-migrate ``` -------------------------------- ### Define a Custom unstorage Driver in JavaScript Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/1.guide/4.custom-driver.md This snippet shows how to define a custom driver for unstorage using the `defineDriver` function. It includes the essential methods like `hasItem`, `getItem`, `setItem`, `removeItem`, `getKeys`, `clear`, `dispose`, and `watch`. The custom driver can be initialized and used with `createStorage`. ```javascript import { createStorage, defineDriver } from "unstorage"; const myStorageDriver = defineDriver((options) => { return { name: "my-custom-driver", options, async hasItem(key, _opts) {}, async getItem(key, _opts) {}, async setItem(key, value, _opts) {}, async removeItem(key, _opts) {}, async getKeys(base, _opts) {}, async clear(base, _opts) {}, async dispose() {}, async watch(callback) {}, }; }); const storage = createStorage({ driver: myStorageDriver(), }); ``` -------------------------------- ### Restore Storage Data from Snapshot with Unstorage Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/1.guide/2.utils.md The `restoreSnapshot` utility restores storage data from a snapshot object previously created by the `snapshot` utility. It takes the target storage instance, the snapshot data object, and an optional base path for restoring keys. This function effectively repopulates the storage with the provided data. ```javascript await restoreSnapshot(storage, { "foo:bar": "baz" }, "/etc2"); ``` -------------------------------- ### Snapshot Storage Data with Unstorage Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/1.guide/2.utils.md The `snapshot` utility generates a plain JavaScript object containing all key-value pairs from a specified base within the storage. The base path is removed from the keys in the resulting snapshot object. This is useful for backing up or transferring storage contents. ```javascript import { snapshot } from "unstorage"; const data = await snapshot(storage, "/etc"); ``` -------------------------------- ### Cloudflare KV Binding Driver for unstorage Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/2.drivers/cloudflare.md This driver allows storing data in Cloudflare KV using worker bindings. It requires a Cloudflare worker environment and KV bindings to be set up. The driver can accept the binding name, the binding object directly, or a binding from Durable Objects/Workers using Modules Syntax. It is not suitable for environments outside of Cloudflare Workers, where `cloudflare-kv-http` should be used instead. ```javascript import { createStorage } from "unstorage"; import cloudflareKVBindingDriver from "unstorage/drivers/cloudflare-kv-binding"; // Using binding name to be picked from globalThis const storage = createStorage({ driver: cloudflareKVBindingDriver({ binding: "STORAGE" }), }); // Directly setting binding const storage = createStorage({ driver: cloudflareKVBindingDriver({ binding: globalThis.STORAGE }), }); // Using from Durable Objects and Workers using Modules Syntax const storage = createStorage({ driver: cloudflareKVBindingDriver({ binding: this.env.STORAGE }), }); // Using outside of Cloudflare Workers (like Node.js) // Use cloudflare-kv-http ``` -------------------------------- ### Cloudflare KV HTTP Driver Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/2.drivers/cloudflare.md This driver allows Unstorage to interact with Cloudflare KV namespaces using the HTTP API. It supports authentication via API Token, email/API Key, or User Service Key. ```APIDOC ## Cloudflare KV HTTP Driver Setup ### Description This driver enables Unstorage to interface with Cloudflare KV HTTP API for storage operations. ### Authentication Methods Supports the following authentication methods: 1. **`apiToken`**: Use a Cloudflare API Token. 2. **`email` and `apiKey`**: Use your Cloudflare account email and API Key. 3. **`userServiceKey`**: Use a special User Service Key. ### Options - **`accountId`** (string) - Required - Your Cloudflare account ID. - **`namespaceId`** (string) - Required - The ID of the KV namespace. - **`apiToken`** (string) - Optional - Cloudflare API Token. - **`email`** (string) - Optional - Account email (used with `apiKey`). - **`apiKey`** (string) - Optional - Account API key (used with `email`). - **`userServiceKey`** (string) - Optional - User Service Key. - **`apiURL`** (string) - Optional - Custom API URL. Defaults to `https://api.cloudflare.com`. - **`base`** (string) - Optional - Prefix for all stored keys. ### Supported Methods - **`getItem(key)`**: Maps to Cloudflare KV API `GET /accounts/:accountId/storage/kv/namespaces/:namespaceId/values/:key`. - **`hasItem(key)`**: Maps to Cloudflare KV API `GET /accounts/:accountId/storage/kv/namespaces/:namespaceId/values/:key`. Returns `true` if the response indicates success. - **`setItem(key, value, options?)`**: Maps to Cloudflare KV API `PUT /accounts/:accountId/storage/kv/namespaces/:namespaceId/values/:key`. Supports `ttl` option (in seconds, min 60). - **`removeItem(key)`**: Maps to Cloudflare KV API `DELETE /accounts/:accountId/storage/kv/namespaces/:namespaceId/values/:key`. - **`getKeys()`**: Maps to Cloudflare KV API `GET /accounts/:accountId/storage/kv/namespaces/:namespaceId/keys`. - **`clear()`**: Maps to Cloudflare KV API `DELETE /accounts/:accountId/storage/kv/namespaces/:namespaceId/bulk`. ``` -------------------------------- ### Cloudflare R2 Binding Driver Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/2.drivers/cloudflare.md This driver enables Unstorage to interact with Cloudflare R2 buckets directly within a Cloudflare Worker environment using bindings. ```APIDOC ## Cloudflare R2 Binding Driver Setup ### Description This driver allows Unstorage v2 to interact with Cloudflare R2 buckets when deployed within a Cloudflare Worker environment using R2 bindings. ::warning This is an experimental driver and only works in a Cloudflare Worker environment. :: ### Configuration - **`binding`** (object | string) - Required - The R2 bucket binding object or its name. - If a string is provided, it will attempt to resolve it from `globalThis` (e.g., `globalThis.MY_BUCKET`). - If used within a worker's `env` (Modules syntax), provide `this.env.MY_BUCKET`. - Defaults to `BUCKET` if not specified. - **`base`** (string) - Optional - Prefix for all stored keys. ### Usage Examples ```js import { createStorage } from "unstorage"; import cloudflareR2BindingDriver from "unstorage/drivers/cloudflare-r2-binding"; // Using binding name (resolved from globalThis) const storage = createStorage({ driver: cloudflareR2BindingDriver({ binding: "MY_BUCKET" }), }); // Directly setting binding object const storage = createStorage({ driver: cloudflareR2BindingDriver({ binding: globalThis.MY_BUCKET }), }); // Using from Durable Objects and Workers using Modules Syntax const storage = createStorage({ driver: cloudflareR2BindingDriver({ binding: this.env.MY_BUCKET }), }); ``` ### Supported Methods This driver supports the standard Unstorage methods for interacting with R2 buckets: - `getItem(key)` - `setItem(key, value)` - `removeItem(key)` - `getKeys()` - `clear()` ``` -------------------------------- ### Unstorage Redis Driver: Cluster Configuration Source: https://github.com/fahreddinozcan/unstorage/blob/main/docs/2.drivers/redis.md This snippet shows the configuration for using the Unstorage Redis driver with a Redis cluster, such as AWS ElastiCache or Azure Redis Cache. It highlights the use of the 'hastag' prefix '{unstorage}' for keys to ensure they hash to the same slot, preventing 'CROSSSLOT' errors. It includes cluster node definitions and options for secure connection. ```javascript const storage = createStorage({ driver: redisDriver({ base: "{unstorage}", cluster: [ { port: 6380, host: "HOSTNAME", }, ], clusterOptions: { redisOptions: { tls: { servername: "HOSTNAME" }, password: "REDIS_PASSWORD", }, }, }), }); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.