redis-js — скилл для Claude Code: что делает и как установить
Справочник по библиотеке @upstash/redis для бессерверных сред. Помогает ИИ-агенту писать запросы к Redis без лишней ручной сериализации.
npx skills add upstash/redis-js --skill redis-js -a claude-code
npx skills add upstash/redis-js --skill skills -a claude-codeЧто делает redis-js
Скилл обучает ассистента приёмам работы с пакетом @upstash/redis в TypeScript и JavaScript. SDK сам сериализует примитивы и объекты, поэтому вызовы JSON.stringify или parseInt здесь не нужны. В материалах разобраны стандартные структуры данных Redis, разреженные массивы с кольцевыми буферами ARRING и поиск ближайших соседей через redis.vector.
Внутри описаны готовые архитектурные шаблоны: кэширование с политиками TTL, скользящие лимиты с пакетом @upstash/ratelimit и распределённые блокировки. Также есть инструкции по полнотекстовому поиску, агрегациям и автоматическому объединению запросов в пайплайны.
Для выполнения кода обязательно требуются переменные окружения UPSTASH_REDIS_REST_URL и UPSTASH_REDIS_REST_TOKEN, потому что клиент отправляет команды через REST API.
Какие задачи решает
- сохранять объекты JavaScript в Redis без ручного вызова JSON.stringify
- настроить ограничение частоты запросов через связку с @upstash/ratelimit
- собрать таблицу лидеров на основе Sorted Sets
- выполнять поиск и агрегацию данных через расширение search
- настроить пакетное выполнение команд через автоматические пайплайны
Примеры запросов агенту
- Сохрани профиль пользователя в Upstash Redis со сроком жизни один час
- Покажи пример ограничения запросов с помощью @upstash/ratelimit
- Создай векторный индекс и найди ближайших соседей через redis.vector
Как установить redis-js
1Через Skills CLI (Vercel)
npx skills add upstash/redis-js --skill redis-js -a claude-codenpx skills add upstash/redis-js --skill skills -a claude-code2Вручную: положить файлы
~/.claude/skills/skills/SKILL.mdПапка скилла целиком; для одного проекта — .claude/skills/skills/
1Через Skills CLI (Vercel)
npx skills add upstash/redis-js --skill skills -a codex2Вручную: положить файлы
.agents/skills/skills/SKILL.mdДля всех проектов — ~/.agents/skills/
1Через Skills CLI (Vercel)
npx skills add upstash/redis-js --skill skills -a cursor2Вручную: положить файлы
.cursor/skills/skills/SKILL.mdCursor читает и .agents/skills/, и .claude/skills/
1GitHub CLI
gh skill install upstash/redis-js skills2Вручную: положить файлы
.github/skills/skills/SKILL.md1Через Skills CLI (Vercel)
npx skills add upstash/redis-js --skill skills -a gemini-cli2Командой платформы
gemini skills install https://github.com/upstash/redis-js --path skillsВручную: положить файлы
.devin/skills/skills/SKILL.mdСтарый путь .windsurf/skills/ тоже читается
Через Skills CLI (Vercel)
npx skills add upstash/redis-js --skill skills -a opencodeClaude.ai
Упакуйте папку в zip и загрузите в Settings → Capabilities → Skills
По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов
Похожие
Рядом в теме «Бэкенд и API»
Всё по теме «Бэкенд и API» →Вопросы о redis-js
Как установить redis-js в Claude Code?
Выполните команду npx skills add upstash/redis-js --skill redis-js -a claude-code. Либо подключите каталог целиком: npx skills add upstash/redis-js --skill skills -a claude-code.
Что делает скилл redis-js?
Он предоставляет агенту правила и примеры использования SDK @upstash/redis, включая структуры данных, транзакции, полнотекстовый поиск и миграцию с ioredis.
Нужно ли вручную парсить JSON при чтении из Upstash Redis?
Нет. Библиотека автоматически сериализует и парсит объекты и числа, поэтому методы JSON.parse и JSON.stringify не требуются.
Исходный текст
SKILL.md · MIT
---
name: redis-js
description: Work with the Upstash Redis JavaScript/TypeScript SDK for serverless Redis operations. Use for caching, session storage, rate limiting, leaderboards, full-text search (querying, filtering, aggregating with @upstash/redis search extension), and all Redis data structures. Supports automatic serialization/deserialization of JavaScript types. Search also available via @upstash/search-redis and @upstash/search-ioredis adapters for TCP clients.
---
# Upstash Redis SDK - Complete Skills Guide
This directory contains comprehensive guides for using the `@upstash/redis` SDK. These skill files are designed to help developers and AI assistants understand and use the SDK effectively.
## Installation
```bash
npm install @upstash/redis
```
## Quick Start
### Basic Initialization
```typescript
import { Redis } from "@upstash/redis";
// Initialize with explicit credentials
const redis = new Redis({
url: "UPSTASH_REDIS_REST_URL",
token: "UPSTASH_REDIS_REST_TOKEN",
});
// Or initialize from environment variables
const redis = Redis.fromEnv();
```
### Environment Variables
Set these in your `.env` file:
```bash
UPSTASH_REDIS_REST_URL=https://your-redis.upstash.io
UPSTASH_REDIS_REST_TOKEN=your-token-here
```
## Skill Files Overview
### Data Structures (skills/data-structures/)
Redis data types with auto-serialization examples:
- **strings.md** - GET, SET, INCR, DECR, APPEND with automatic type handling
- **hashes.md** - HSET, HGET, HMGET with object serialization
- **lists.md** - LPUSH, RPUSH, LRANGE with array handling
- **sets.md** - SADD, SMEMBERS, set operations
- **sorted-sets.md** - ZADD, ZRANGE, ZRANK, leaderboard patterns
- **json.md** - JSON.SET, JSON.GET, JSONPath queries for nested objects
- **streams.md** - XADD, XREAD, XGROUP, consumer groups
- **arrays.md** - ARSET, ARINSERT, ARSCAN, ARGREP, AROP, ring buffers with ARRING on sparse index-addressed arrays
- **vector-indexes.md** - VECTOR.CREATE, VECTOR.ADD, VECTOR.QUERY nearest-neighbour search inside Redis via redis.vector
### Advanced Features (skills/advanced-features/)
Complex operations and optimizations:
- **auto-pipeline.md** - Automatic request batching, performance optimization
- **pipeline-and-transactions.md** - Manual pipelines, MULTI/EXEC, WATCH for atomic operations
- **scripting.md** - Lua scripts, EVAL, EVALSHA for server-side logic
### Patterns (skills/patterns/)
Common use cases and architectural patterns:
- **caching.md** - Cache-aside, write-through, TTL strategies
- **rate-limiting.md** - Integration with @upstash/ratelimit package
- **session-management.md** - Session storage and user state management
- **distributed-locks.md** - Lock implementations, deadlock prevention
- **leaderboard.md** - Sorted set leaderboards, real-time rankings
### Performance (skills/performance/)
Optimization techniques and best practices:
- **batching-operations.md** - MGET, MSET, batch operations
- **pipeline-optimization.md** - When to use pipelines, performance tips
- **ttl-expiration.md** - Key expiration strategies, memory management
- **data-serialization.md** - Deep dive into auto serialization, custom serializers, edge cases
- **error-handling.md** - Error types, retry strategies, timeout handling, debugging tips
- **redis-replicas.md** - Global database setup, read replicas, read-your-writes consistency
### Search (skills/search/)
Full-text search, filtering, and aggregation extension for Redis:
- **overview.md** - Schema definition, field types, pitfalls, package overview
- **commands/querying.md** - Query and count with filters, pagination, sorting, highlighting
- **commands/aggregating.md** - Metric aggregations ($avg, $sum, $stats), bucket aggregations ($terms, $range, $histogram, $facet)
- **commands/index-management.md** - Create, describe, drop indexes, waitIndexing
- **commands/aliases.md** - Index aliases for zero-downtime reindexing
- **adapters.md** - Using search with node-redis and ioredis via @upstash/search-redis and @upstash/search-ioredis
### Migrations (skills/migrations/)
Migration guides from other libraries:
- **from-ioredis.md** - Migration from ioredis, key differences, serialization changes
- **from-redis-node.md** - Migration from node-redis, API differences
## Common Mistakes (Especially for LLMs)
### ❌ Mistake 1: Treating Everything as Strings
```typescript
// ❌ WRONG - Don't do this with @upstash/redis
await redis.set("count", "42"); // Stored as string "42"
const count = await redis.get("count");
const incremented = parseInt(count) + 1; // Manual parsing needed
// ✅ CORRECT - Let the SDK handle it
await redis.set("count", 42); // Stored as number
const count = await redis.get("count");
const incremented = count + 1; // Just use it
```
### ❌ Mistake 2: Manual JSON Serialization
```typescript
// ❌ WRONG - Unnecessary with @upstash/redis
await redis.set("user", JSON.stringify({ name: "Alice" }));
const user = JSON.parse(await redis.get("user"));
// ✅ CORRECT - Automatic handling
await redis.set("user", { name: "Alice" });
const user = await redis.get("user");
```
## Quick Command Reference
```typescript
// Strings
await redis.set("key", "value");
await redis.get("key");
await redis.incr("counter");
await redis.decr("counter");
// Hashes
await redis.hset("user:1", { name: "Alice", age: 30 });
await redis.hget("user:1", "name");
await redis.hgetall("user:1");
// Lists
await redis.lpush("tasks", "task1", "task2");
await redis.rpush("tasks", "task3");
await redis.lrange("tasks", 0, -1);
// Sets
await redis.sadd("tags", "javascript", "redis");
await redis.smembers("tags");
// Sorted Sets
await redis.zadd("leaderboard", { score: 100, member: "player1" });
await redis.zrange("leaderboard", 0, -1);
// JSON
await redis.json.set("user:1", "$", { name: "Alice", address: { city: "NYC" } });
await redis.json.get("user:1");
// Expiration
await redis.setex("session", 3600, { userId: "123" });
await redis.expire("key", 60);
await redis.ttl("key");
```
## Best Practices
1. **Use environment variables** for credentials, never hardcode
2. **Leverage auto-serialization** - pass native JavaScript types
3. **Use TypeScript types** for better type safety
4. **Set appropriate TTLs** to manage memory
5. **Use pipelines** for multiple operations
6. **Namespace your keys** (e.g., `user:123`, `session:abc`)
## Resources
- [Official Documentation](https://upstash.com/docs/redis)
- [GitHub Repository](https://github.com/upstash/redis-js)
- [API Reference](https://upstash.com/docs/redis/sdks/ts/overview)
- [Examples](https://github.com/upstash/redis-js/tree/main/examples)
## Getting Help
For detailed information on specific topics, refer to the individual skill files in the `skills/` directory. Each file contains comprehensive examples, use cases, and best practices for its topic.
© upstash · MIT · upstash/redis-js