### Project Setup with Git Clone and NPM Install Source: https://github.com/fahreddinozcan/redisimim/blob/main/examples/nextjs-pages-router/README.md This snippet shows the commands to clone the example project repository and install its dependencies using npm. It's a standard procedure for setting up Node.js projects. ```shell git clone https://github.com/upstash/redis-js.git cd redis-js/examples/nextjs-pages-router npm install ``` -------------------------------- ### Installation and Basic Usage Source: https://github.com/fahreddinozcan/redisimim/blob/main/README.md Instructions on how to install the @upstash/redis SDK and examples of basic Redis commands like SET, GET, ZADD, LPUSH, HSET, and SADD. ```APIDOC ## Installation ```bash # npm install @upstash/redis # or # yarn add @upstash/redis # or # pnpm add @upstash/redis ``` ## Basic Usage ### Initialize Redis Client ```ts import { Redis } from "@upstash/redis" const redis = new Redis({ url: "", token: "", }) ``` ### String Operations #### SET ```ts // Set a key-value pair await redis.set('key', 'value'); // Set a key with an expiration time in seconds await redis.set('key3', 'value3', { ex: 1 }); ``` #### GET ```ts // Get the value of a key let data = await redis.get('key'); console.log(data); // Output: "value" ``` ### Sorted Set Operations #### ZADD ```ts // Add members to a sorted set await redis.zadd('scores', { score: 1, member: 'team1' }) ``` #### ZRANGE ```ts // Get a range of members from a sorted set data = await redis.zrange('scores', 0, 100); console.log(data); ``` ### List Operations #### LPUSH ```ts // Push an element to the left of a list await redis.lpush('elements', 'magnesium'); ``` #### LRANGE ```ts // Get a range of elements from a list data = await redis.lrange('elements', 0, 100); console.log(data); ``` ### Hash Operations #### HSET ```ts // Set fields in a hash await redis.hset('people', { name: 'joe' }); ``` #### HGET ```ts // Get the value of a field in a hash data = await redis.hget('people', 'name'); console.log(data); // Output: "joe" ``` ### Set Operations #### SADD ```ts // Add members to a set await redis.sadd('animals', 'cat'); ``` #### SPOP ```ts // Remove and return a random member from a set data = await redis.spop('animals', 1); console.log(data); ``` ``` -------------------------------- ### Setup Project Environment Source: https://github.com/fahreddinozcan/redisimim/blob/main/examples/fastapi/README.md Clones the repository and installs the necessary Python dependencies for the FastAPI application. ```shell git clone https://github.com/upstash/redis-js.git cd redis-js/examples/fastapi pip install -r requirements.txt ``` -------------------------------- ### Install and Initialize Upstash Redis Client Source: https://github.com/fahreddinozcan/redisimim/blob/main/README.md Installs the @upstash/redis package and initializes the Redis client with URL and token. Demonstrates basic usage for setting and getting string values. ```bash npm install @upstash/redis ``` ```typescript import { Redis } from "@upstash/redis" const redis = new Redis({ url: , token: , }) // string await redis.set('key', 'value'); let data = await redis.get('key'); console.log(data) ``` -------------------------------- ### Clone and Setup Django Project Source: https://github.com/fahreddinozcan/redisimim/blob/main/examples/vercel-python-runtime-django/README.md This snippet shows how to clone the Redis-JS example repository and navigate into the Vercel Python Runtime Django directory. ```shell git clone https://github.com/upstash/redis-js.git cd redis-js/examples/vercel-python-runtime-django ``` -------------------------------- ### Initialize Next.js Redis Project Source: https://github.com/fahreddinozcan/redisimim/blob/main/examples/nextjs-app-router/README.md Commands to clone the repository, navigate to the project directory, and install the necessary dependencies for the Next.js App Router example. ```shell git clone https://github.com/upstash/redis-js.git cd redis-js/examples/nextjs-app-router npm install ``` -------------------------------- ### Clone Redis Example Repository Source: https://github.com/fahreddinozcan/redisimim/blob/main/examples/aws-sam/README.md Clones the redis-js repository and navigates to the AWS SAM example directory. This is the initial step for setting up the project. ```shell git clone https://github.com/upstash/redis-js.git cd redis-js/examples/aws-sam ``` -------------------------------- ### Initialize and Run Cloudflare Worker Project Source: https://github.com/fahreddinozcan/redisimim/blob/main/examples/cloudflare-workers/README.md Commands to clone the repository, install dependencies, and launch the local development server for testing the worker. ```bash git clone https://github.com/upstash/upstash-redis.git cd upstash-redis/examples/cloudflare-workers npm install npm run start ``` -------------------------------- ### Initialize Azure Functions Project Source: https://github.com/fahreddinozcan/redisimim/blob/main/examples/azure-functions/README.md Clones the repository and installs necessary dependencies for the Azure Functions project. ```shell git clone https://github.com/upstash/redis-js.git cd redis-js/examples/azure-functions npm install ``` -------------------------------- ### Deploy AWS SAM Application (Guided) Source: https://github.com/fahreddinozcan/redisimim/blob/main/examples/aws-sam/README.md Deploys the AWS SAM application using a guided deployment process. This command will prompt the user for necessary environment variables, such as database credentials, before deploying the serverless resources. ```shell sam deploy --guided ``` -------------------------------- ### Run FastAPI Application Source: https://github.com/fahreddinozcan/redisimim/blob/main/examples/fastapi/README.md Starts the FastAPI development server to run the application locally. ```shell fastapi dev main.py ``` -------------------------------- ### Create and Activate Conda Environment Source: https://github.com/fahreddinozcan/redisimim/blob/main/examples/vercel-python-runtime-django/README.md Instructions for creating a Conda environment with Python 3.12 and installing project dependencies from requirements.txt. ```shell conda create --name vercel-django python=3.12 conda activate vercel-django pip install -r requirements.txt ``` -------------------------------- ### Upstash Redis Data Structure Examples (TypeScript) Source: https://github.com/fahreddinozcan/redisimim/blob/main/README.md Provides examples of using the Upstash Redis client to interact with various Redis data structures including strings with expiration, sorted sets, lists, hashes, and sets. ```typescript // string with expiration await redis.set('key3', 'value3', {ex: 1}); // sorted set await redis.zadd('scores', { score: 1, member: 'team1' }) data = await redis.zrange('scores', 0, 100 ) console.log(data) // list await redis.lpush('elements', 'magnesium') data = await redis.lrange('elements', 0, 100 ) console.log(data) // hash await redis.hset('people', {name: 'joe'}) data = await redis.hget('people', 'name' ) console.log(data) // sets await redis.sadd('animals', 'cat') data = await redis.spop('animals', 1) console.log(data) ``` -------------------------------- ### Perform JSON Document Operations with Redis Source: https://context7.com/fahreddinozcan/redisimim/llms.txt Demonstrates how to store, retrieve, and manipulate JSON documents within Redis using JSONPath. Includes examples for setting values, performing numeric/string/array operations, and merging objects. ```typescript import { Redis } from "@upstash/redis"; const redis = Redis.fromEnv(); // Set JSON document await redis.json.set("user:1", "$", { name: "John Doe", email: "john@example.com", age: 30, address: { city: "New York", country: "USA" }, tags: ["developer", "typescript"], active: true }); // Get entire document const user = await redis.json.get("user:1", "$"); // Set nested value await redis.json.set("user:1", "$.address.zip", "10001"); // Increment numeric values await redis.json.numincrby("user:1", "$.age", 1); // Array operations await redis.json.arrappend("user:1", "$.tags", "redis", "upstash"); // Merge JSON await redis.json.merge("user:1", "$", { verified: true, lastLogin: Date.now() }); ``` -------------------------------- ### Perform Redis String Operations Source: https://context7.com/fahreddinozcan/redisimim/llms.txt Covers common string manipulation commands including setting, getting, expiration, atomic increments, and multi-key operations. ```typescript import { Redis } from "@upstash/redis"; const redis = Redis.fromEnv(); // Basic set and get await redis.set("user:1:name", "John Doe"); const name = await redis.get("user:1:name"); // Set with expiration await redis.set("session:abc123", { userId: 1, role: "admin" }, { ex: 3600 }); // Conditional sets await redis.set("lock:resource", "locked", { nx: true, ex: 30 }); // Increment/Decrement await redis.incr("visits"); await redis.incrby("visits", 10); // Multiple keys await redis.mset({ "key1": "value1", "key2": "value2" }); const values = await redis.mget<[string, string]>("key1", "key2"); ``` -------------------------------- ### Perform Hash Operations with Upstash Redis Source: https://context7.com/fahreddinozcan/redisimim/llms.txt Demonstrates how to store, retrieve, and manipulate field-value pairs within a Redis hash. Includes operations for setting, getting, incrementing, and deleting fields, as well as scanning and setting expirations. ```typescript import { Redis } from "@upstash/redis"; const redis = Redis.fromEnv(); // Set hash fields await redis.hset("user:100", { name: "Alice", email: "alice@example.com", age: 30, active: true, }); // Get single field const email = await redis.hget("user:100", "email"); // Get all fields and values const allData = await redis.hgetall<{ name: string; email: string; age: number; active: boolean; }>("user:100"); // Increment numeric field await redis.hincrby("user:100", "age", 1); // Hash field expiration (Redis 7.4+) await redis.hexpire("user:100", 3600, "email"); ``` -------------------------------- ### Initialize Upstash Redis Client Source: https://context7.com/fahreddinozcan/redisimim/llms.txt Demonstrates how to initialize the Redis client using explicit credentials, environment variables, or advanced configuration options such as retry logic and telemetry. ```typescript import { Redis } from "@upstash/redis"; // Initialize with explicit credentials const redis = new Redis({ url: "https://your-redis-endpoint.upstash.io", token: "your-redis-token", }); // Initialize from environment variables (UPSTASH_REDIS_REST_URL, UPSTASH_REDIS_REST_TOKEN) const redisFromEnv = Redis.fromEnv(); // Initialize with advanced options const redisAdvanced = new Redis({ url: process.env.UPSTASH_REDIS_REST_URL, token: process.env.UPSTASH_REDIS_REST_TOKEN, automaticDeserialization: true, enableTelemetry: false, enableAutoPipelining: true, readYourWrites: true, latencyLogging: true, retry: { retries: 5, backoff: (retryCount) => Math.exp(retryCount) * 50, }, }); ``` -------------------------------- ### Running and Deploying the Next.js Application Source: https://github.com/fahreddinozcan/redisimim/blob/main/examples/nextjs-pages-router/README.md Instructions for running the Next.js application locally using `npm run dev` and deploying it using `vercel`. This covers the development and deployment lifecycle of the application. ```shell npm run dev vercel ``` -------------------------------- ### Execute Batch Commands with Redis Pipelines Source: https://context7.com/fahreddinozcan/redisimim/llms.txt Shows how to use pipelines to send multiple commands in a single HTTP request for improved performance. Covers basic chaining, type-safe execution, and error handling for individual commands. ```typescript import { Redis } from "@upstash/redis"; const redis = Redis.fromEnv(); // Create pipeline and chain commands const pipeline = redis.pipeline(); pipeline.set("key1", "value1"); pipeline.get("key1"); // Execute all commands const results = await pipeline.exec(); // With type inference and error handling const resultsWithErrors = await redis .pipeline() .set("valid", "data") .incr("not-a-number") .exec({ keepErrors: true }); ``` -------------------------------- ### Deploy Django App with Vercel CLI Source: https://github.com/fahreddinozcan/redisimim/blob/main/examples/vercel-python-runtime-django/README.md Instructions for deploying the Django application using the Vercel CLI and setting environment variables in Vercel project settings. ```shell vercel # Then set UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN in Vercel project settings. ``` -------------------------------- ### Redis Bitfield Operations Source: https://context7.com/fahreddinozcan/redisimim/llms.txt Manipulate strings as arrays of bits for compact data storage using Bitfield operations. Supports setting, getting, counting, and finding bits, as well as bitwise operations (AND, OR, XOR, NOT) and complex Bitfield commands with overflow handling. ```typescript import { Redis } from "@upstash/redis"; const redis = Redis.fromEnv(); // Set individual bits await redis.setbit("flags", 0, 1); await redis.setbit("flags", 7, 1); // Get bit value const bit = await redis.getbit("flags", 0); // 1 // Count set bits const count = await redis.bitcount("flags"); const rangeCount = await redis.bitcount("flags", 0, 0); // First byte only // Find first bit position const firstOne = await redis.bitpos("flags", 1); const firstZero = await redis.bitpos("flags", 0); // Bitwise operations await redis.set("key1", "\x0f"); // 00001111 await redis.set("key2", "\xf0"); // 11110000 await redis.bitop("AND", "result:and", "key1", "key2"); // 00000000 await redis.bitop("OR", "result:or", "key1", "key2"); // 11111111 await redis.bitop("XOR", "result:xor", "key1", "key2"); // 11111111 await redis.bitop("NOT", "result:not", "key1"); // 11110000 // Bitfield operations (multiple sub-values in single string) await redis.set("counters", Buffer.alloc(8)); const results = await redis.bitfield("counters") .set("u8", 0, 100) // Set 8-bit unsigned at offset 0 to 100 .set("u8", 8, 200) // Set 8-bit unsigned at offset 8 to 200 .get("u8", 0) // Get value at offset 0 .incr("u8", 0, 1) // Increment value at offset 0 .exec(); console.log(results); // [0, 0, 100, 101] // Bitfield with overflow handling const overflowResults = await redis.bitfield("counters") .overflow("SAT") // Saturate on overflow .incr("u8", 0, 200) // Will saturate at 255 .exec(); ``` -------------------------------- ### Provision Azure Infrastructure Source: https://github.com/fahreddinozcan/redisimim/blob/main/examples/azure-functions/README.md Commands to create a resource group, storage account, and the Function App instance in Azure. ```shell az account list-locations az group create --name AzureFunctionsQuickstart-rg --location az storage account create --name --location --resource-group AzureFunctionsQuickstart-rg --sku Standard_LRS --allow-blob-public-access false az functionapp create --resource-group AzureFunctionsQuickstart-rg --consumption-plan-location --runtime node --runtime-version 18 --functions-version 4 --name --storage-account ``` -------------------------------- ### Build and Deploy Azure Function Source: https://github.com/fahreddinozcan/redisimim/blob/main/examples/azure-functions/README.md Compiles the application code and publishes it to the provisioned Azure Function App. ```shell npm run build func azure functionapp publish ``` -------------------------------- ### Run Django Development Server Source: https://github.com/fahreddinozcan/redisimim/blob/main/examples/vercel-python-runtime-django/README.md Command to run the Django development server locally. Assumes Redis environment variables are set. ```shell python manage.py runserver ``` -------------------------------- ### Build AWS SAM Application Source: https://github.com/fahreddinozcan/redisimim/blob/main/examples/aws-sam/README.md Builds the AWS Serverless Application Model (SAM) project. This command prepares the application for deployment by packaging dependencies and code. ```shell sam build ``` -------------------------------- ### Configure Redis Environment Variables Source: https://github.com/fahreddinozcan/redisimim/blob/main/examples/nextjs-app-router/README.md Format for defining the required Upstash Redis REST URL and token within the project's .env file. ```text UPSTASH_REDIS_REST_URL= UPSTASH_REDIS_REST_TOKEN= ``` -------------------------------- ### Configure Redis Client with Auto Pipelining Source: https://github.com/fahreddinozcan/redisimim/blob/main/examples/auto-pipeline/README.md Initializes the Upstash Redis client using environment variables and enables the auto-pipelining feature. This configuration allows the client to automatically group commands to reduce network latency. ```typescript import { Redis } from '@upstash/redis' export const LATENCY_LOGGING = true export const ENABLE_AUTO_PIPELINING = true const client = Redis.fromEnv({ latencyLogging: LATENCY_LOGGING, enableAutoPipelining: ENABLE_AUTO_PIPELINING }); export default client; ``` -------------------------------- ### Integrate Upstash Redis with Cloudflare Workers Source: https://context7.com/fahreddinozcan/redisimim/llms.txt Shows how to use the dedicated Cloudflare module to initialize the Redis client using environment bindings within a Cloudflare Worker fetch handler. ```typescript import { Redis } from "@upstash/redis/cloudflare"; export interface Env { UPSTASH_REDIS_REST_URL: string; UPSTASH_REDIS_REST_TOKEN: string; } export default { async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise { const redis = Redis.fromEnv(env); const count = await redis.incr("page-views"); return new Response(JSON.stringify({ count })); }, }; ``` -------------------------------- ### Manage Redis Streams for Event Sourcing Source: https://context7.com/fahreddinozcan/redisimim/llms.txt Demonstrates how to add, read, and manage stream entries, including consumer group operations for reliable message processing. It covers essential commands like xadd, xreadgroup, xack, and stream maintenance tasks like trimming. ```typescript import { Redis } from "@upstash/redis"; const redis = Redis.fromEnv(); const entryId = await redis.xadd("events", "*", { type: "order_created", orderId: "12345", userId: "user_abc", amount: 99.99 }); const entries = await redis.xrange("events", "-", "+"); await redis.xgroup("CREATE", "events", "order-processors", "$", { mkstream: true }); const groupEntries = await redis.xreadgroup("order-processors", "consumer-1", { streams: ["events"], ids: [">"] }, { count: 10 }); await redis.xack("events", "order-processors", "1234567890123-0"); await redis.xtrim("events", { strategy: "MAXLEN", threshold: 1000, exactness: "~" }); ``` -------------------------------- ### Implement Data Retrieval with Auto Pipelining Source: https://github.com/fahreddinozcan/redisimim/blob/main/examples/auto-pipeline/README.md Demonstrates fetching data from Redis using scan and hgetall operations. The auto-pipelining feature automatically batches these commands when executed concurrently. ```typescript import client from "./redis" export async function getUsers() { const keys = await client.scan(0, { match: 'user:*' }); if (keys[1].length === 0) { client.hmset('user:1', {'username': 'Adam', 'birthday': '1990-01-01'}); client.hmset('user:2', {'username': 'Eve', 'birthday': '1980-01-05'}); } const users = await Promise.all(keys[1].map(async key => { return client.hgetall(key) ?? {username: "default", birthday: "2000-01-01"}; })); return users as {username: string, birthday: string}[] } ``` -------------------------------- ### Implement Middleware for Redis Client Source: https://context7.com/fahreddinozcan/redisimim/llms.txt Shows how to wrap the Redis client with custom middleware to handle logging, metrics, and request modifications. Middlewares are executed in the order they are added. ```typescript import { Redis } from "@upstash/redis"; const redis = Redis.fromEnv(); redis.use(async (req, next) => { console.log("Request:", JSON.stringify(req.body)); const response = await next(req); return response; }); redis.use(async (req, next) => { req.headers = { ...req.headers, "X-Request-ID": crypto.randomUUID(), }; return next(req); }); ``` -------------------------------- ### Configure Redis Environment Variables Source: https://github.com/fahreddinozcan/redisimim/blob/main/examples/fastapi/README.md Exports the required Upstash Redis REST URL and token as environment variables for the application to connect to the database. ```shell export UPSTASH_REDIS_REST_URL= export UPSTASH_REDIS_REST_TOKEN= ``` -------------------------------- ### Integrate Redis Data in Next.js Server Components Source: https://github.com/fahreddinozcan/redisimim/blob/main/examples/auto-pipeline/README.md Shows how to call multiple data fetching functions within a Next.js Server Component. By using Promise.all, the auto-pipelining feature effectively batches the underlying Redis commands. ```typescript "use server" import client from "../data/redis" import { getEvents } from "../data/getEvents"; import { getUsers } from "../data/getUsers"; const DataComponent = async () => { const [ users, events ] = await Promise.all([ getUsers(), getEvents() ]) const counter = client.pipelineCounter return (
...
); }; export default DataComponent; ``` -------------------------------- ### Perform Geospatial Queries with Redis Source: https://context7.com/fahreddinozcan/redisimim/llms.txt Shows how to store location data, calculate distances between points, and perform radius or bounding box searches. These operations are useful for location-aware applications like store locators. ```typescript import { Redis } from "@upstash/redis"; const redis = Redis.fromEnv(); await redis.geoadd("stores", { longitude: -122.4194, latitude: 37.7749, member: "store:sf" }, { longitude: -118.2437, latitude: 34.0522, member: "store:la" }); const distance = await redis.geodist("stores", "store:sf", "store:la", "KM"); const nearbyStores = await redis.geosearch("stores", { type: "FROMLONLAT", coordinate: { lon: -122.4, lat: 37.8 } }, { type: "BYRADIUS", radius: 50, radiusType: "KM" }, "ASC", { count: { limit: 10 }, withDist: true, withCoord: true }); await redis.geosearchstore("nearby-stores", "stores", { type: "FROMLONLAT", coordinate: { lon: -122.4, lat: 37.8 } }, { type: "BYRADIUS", radius: 100, radiusType: "KM" }, "ASC", { storeDist: true }); ``` -------------------------------- ### Telemetry Configuration Source: https://github.com/fahreddinozcan/redisimim/blob/main/README.md Information on how to manage telemetry data collection for the @upstash/redis SDK. ```APIDOC ## Telemetry This library sends anonymous telemetry data to help us improve your experience. We collect the following: - SDK version - Platform (Deno, Cloudflare, Vercel) - Runtime version (node@18.x) You can opt out by setting the `UPSTASH_DISABLE_TELEMETRY` environment variable to any truthy value: ```sh UPSTASH_DISABLE_TELEMETRY=1 ``` Alternatively, you can pass `enableTelemetry: false` when initializing the Redis client: ```ts import { Redis } from "@upstash/redis" const redis = new Redis({ url: "", token: "", enableTelemetry: false, }); ``` ``` -------------------------------- ### Manage Redis Sets with TypeScript Source: https://context7.com/fahreddinozcan/redisimim/llms.txt Demonstrates how to perform CRUD operations on sets, check membership, and execute set algebra like union, intersection, and difference. These operations are essential for managing unique collections of data. ```typescript import { Redis } from "@upstash/redis"; const redis = Redis.fromEnv(); // Add members to set await redis.sadd("tags:post:1", "javascript", "typescript", "redis", "nodejs"); // Check membership const isMember = await redis.sismember("tags:post:1", "redis"); const members = await redis.smismember("tags:post:1", ["redis", "python", "go"]); // Get all members const allTags = await redis.smembers("tags:post:1"); // Set operations await redis.sadd("set:a", "1", "2", "3", "4"); await redis.sadd("set:b", "3", "4", "5", "6"); // Union, Intersection, Difference const union = await redis.sunion("set:a", "set:b"); const intersection = await redis.sinter("set:a", "set:b"); const difference = await redis.sdiff("set:a", "set:b"); // Scan set members const [cursor, scannedMembers] = await redis.sscan("tags:post:1", 0, { match: "java*" }); ``` -------------------------------- ### Enable Auto-Pipelining for Performance Source: https://context7.com/fahreddinozcan/redisimim/llms.txt Demonstrates how to enable automatic request batching to reduce HTTP overhead for concurrent Redis operations. This feature automatically groups commands executed within the same event loop tick. ```typescript import { Redis } from "@upstash/redis"; const redis = new Redis({ url: process.env.UPSTASH_REDIS_REST_URL!, token: process.env.UPSTASH_REDIS_REST_TOKEN!, enableAutoPipelining: true, }); async function fetchUserData(userId: string) { const [profile, settings, notifications] = await Promise.all([ redis.hgetall(`user:${userId}:profile`), redis.hgetall(`user:${userId}:settings`), redis.lrange(`user:${userId}:notifications`, 0, 9), ]); return { profile, settings, notifications }; } ``` -------------------------------- ### Perform List Operations with Upstash Redis Source: https://context7.com/fahreddinozcan/redisimim/llms.txt Covers managing ordered collections in Redis using list commands. Demonstrates push/pop operations, range retrieval, index manipulation, and list trimming. ```typescript import { Redis } from "@upstash/redis"; const redis = Redis.fromEnv(); // Push elements await redis.lpush("tasks", "task3", "task2", "task1"); await redis.rpush("tasks", "task4", "task5"); // Get range of elements const allTasks = await redis.lrange("tasks", 0, -1); // Pop elements const firstTask = await redis.lpop("tasks"); const lastTask = await redis.rpop("tasks"); // Insert before/after pivot await redis.linsert("tasks", "before", "task3", "task2.5"); // Trim list to range await redis.ltrim("tasks", 0, 99); ``` -------------------------------- ### Configure Redis Environment Variables Source: https://github.com/fahreddinozcan/redisimim/blob/main/examples/azure-functions/README.md Sets the required Upstash Redis REST URL and token as application settings within the Azure Function App. ```shell az functionapp config appsettings set --name --resource-group AzureFunctionsQuickstart-rg --settings UPSTASH_REDIS_REST_URL= UPSTASH_REDIS_REST_TOKEN= ``` -------------------------------- ### Redis Pub/Sub Messaging Source: https://context7.com/fahreddinozcan/redisimim/llms.txt Implement real-time messaging using Redis Pub/Sub. Supports subscribing to channels, listening for messages, pattern subscriptions, and publishing messages. ```typescript import { Redis } from "@upstash/redis"; const redis = Redis.fromEnv(); // Subscribe to channels const subscriber = redis.subscribe<{ event: string; data: any }>("notifications"); // Listen for messages subscriber.on("message", ({ channel, message }) => { console.log(`Received on ${channel}:`, message); }); // Listen for subscription events subscriber.on("subscribe", (count) => { console.log(`Subscribed. Total subscriptions: ${count}`); }); // Listen for specific channel subscriber.on("message:notifications", ({ message }) => { console.log("Notification:", message); }); // Error handling subscriber.on("error", (error) => { console.error("Subscription error:", error); }); // Pattern subscription const patternSub = redis.psubscribe("user:*:events"); patternSub.on("pmessage", ({ pattern, channel, message }) => { console.log(`Pattern ${pattern} matched ${channel}:`, message); }); // Publish messages await redis.publish("notifications", { event: "user_signup", data: { userId: 123, email: "user@example.com" } }); // Get subscribed channels const channels = subscriber.getSubscribedChannels(); // Unsubscribe from specific channels await subscriber.unsubscribe(["notifications"]); // Unsubscribe from all await subscriber.unsubscribe(); ``` -------------------------------- ### List Operations API Source: https://context7.com/fahreddinozcan/redisimim/llms.txt Commands for managing ordered collections with push/pop operations from both ends, supporting queue and stack patterns. ```APIDOC ## List Operations List commands for managing ordered collections with push/pop operations from both ends, supporting queue and stack patterns. ### Push elements **Method:** `LPUSH` / `RPUSH` **Endpoint:** N/A (Command-based) **Description:** Pushes elements to the head (left) or tail (right) of a list. ### Get list length **Method:** `LLEN` **Endpoint:** N/A (Command-based) **Description:** Returns the length of a list. ### Get range of elements **Method:** `LRANGE` **Endpoint:** N/A (Command-based) **Description:** Retrieves a range of elements from a list based on start and end indices. ### Pop elements **Method:** `LPOP` / `RPOP` **Endpoint:** N/A (Command-based) **Description:** Removes and returns the first (left) or last (right) element from a list. ### Pop multiple elements **Method:** `LPOP` / `RPOP` (with count) **Endpoint:** N/A (Command-based) **Description:** Removes and returns multiple elements from the head or tail of a list. ### Get element by index **Method:** `LINDEX` **Endpoint:** N/A (Command-based) **Description:** Retrieves the element at a specific index in a list. ### Set element at index **Method:** `LSET` **Endpoint:** N/A (Command-based) **Description:** Sets the value of an element at a specific index in a list. ### Insert before/after pivot **Method:** `LINSERT` **Endpoint:** N/A (Command-based) **Description:** Inserts a new element into a list before or after a specified pivot element. ### Remove elements by value **Method:** `LREM` **Endpoint:** N/A (Command-based) **Description:** Removes occurrences of a specified value from a list. ### Trim list to range **Method:** `LTRIM` **Endpoint:** N/A (Command-based) **Description:** Trims a list so that it contains only the specified range of elements. ### Move element between lists **Method:** `LMOVE` **Endpoint:** N/A (Command-based) **Description:** Atomically moves an element from one list to another. ### Push only if list exists **Method:** `LPUSHX` / `RPUSHX` **Endpoint:** N/A (Command-based) **Description:** Pushes an element to a list, only if the list already exists. ### Find position of element **Method:** `LPOS` **Endpoint:** N/A (Command-based) **Description:** Returns the index of the first occurrence of a specific element in a list. ``` -------------------------------- ### Redis Lua Scripting with EVALSHA Source: https://context7.com/fahreddinozcan/redisimim/llms.txt Execute Lua scripts on the Redis server for complex operations, with automatic caching via EVALSHA for efficiency. Supports direct EVAL execution and read-only scripts. ```typescript import { Redis } from "@upstash/redis"; const redis = Redis.fromEnv(); // Create reusable script const rateLimiter = redis.createScript(` local key = KEYS[1] local limit = tonumber(ARGV[1]) local window = tonumber(ARGV[2]) local current = redis.call("INCR", key) if current == 1 then redis.call("EXPIRE", key, window) end if current > limit then return 0 end return 1 `); // Execute script (automatically uses EVALSHA after first run) const allowed = await rateLimiter.exec( ["rate:user:123"], // KEYS ["10", "60"] // ARGV: 10 requests per 60 seconds ); console.log(allowed); // 1 (allowed) or 0 (rate limited) // Direct EVAL execution const result = await redis.eval( `return ARGV[1] .. " " .. ARGV[2]`, [], // No keys ["Hello", "World"] // Arguments ); console.log(result); // "Hello World" // EVAL with keys const swapResult = await redis.eval( ` local temp = redis.call("GET", KEYS[1]) redis.call("SET", KEYS[1], redis.call("GET", KEYS[2])) redis.call("SET", KEYS[2], temp) return {redis.call("GET", KEYS[1]), redis.call("GET", KEYS[2])} `, ["key1", "key2"], // Keys [] // No additional args ); // Read-only script (for replicas) const readOnlyScript = redis.createScript( `return redis.call("GET", KEYS[1])`, { readonly: true } ); const value = await readOnlyScript.exec(["mykey"], []); // Script management const sha = await redis.scriptLoad(`return "hello"`); const exists = await redis.scriptExists(sha); await redis.scriptFlush(); ``` -------------------------------- ### HyperLogLog Operations Source: https://context7.com/fahreddinozcan/redisimim/llms.txt Probabilistic data structure operations for counting unique elements with high memory efficiency. ```APIDOC ## HYPERLOGLOG OPERATIONS ### Description Used for cardinality estimation. Allows adding elements to a set and retrieving an approximate count of unique items. ### Method PFADD, PFCOUNT, PFMERGE ### Parameters - **key** (string) - Required - Name of the HyperLogLog structure. - **elements** (string[]) - Required - Elements to add to the set. ### Request Example await redis.pfadd("unique-visitors", "user:1", "user:2"); ### Response #### Success Response (200) - **count** (number) - The estimated number of unique elements. ```