cloudflare-worker-dev
БесплатноБез исполняемых скриптовНе проверенCloudflare Workers, KV, Durable Objects, and edge computing development. Use for serverless APIs, caching, rate limiting, real-time features. Activate on…
от curiositech★ 283 звезды на GitHubОб этом скилле
Cloudflare Workers Development
Build high-performance edge APIs with Workers, KV for caching, and Durable Objects for real-time coordination.
Core Architecture
When to Use What
| Service | Use Case | Characteristics |
|---|---|---|
| Workers | Request handling, API logic | Stateless, 50ms CPU (free), 30s (paid) |
| KV | Caching, config, sessions | Eventually consistent, fast reads |
| Durable Objects | Real-time, coordination | Strongly consistent, single-threaded |
| R2 | File storage | S3-compatible, no egress fees |
| D1 | SQLite at edge | Serverless SQL, good for reads |
Worker Fundamentals
Basic Worker Structure
// src/index.ts
export interface Env {
MEETING_CACHE: KVNamespace;
RATE_LIMIT: KVNamespace;
API_KEY: string;
}
export default {
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
const url = new URL(request.url);
// CORS handling
if (request.method === 'OPTIONS') {
return handleCORS();
}
try {
// Route handling
if (url.pathname === '/health') {
return json({ status: 'ok' });
}
if (url.pathname.startsWith('/api/')) {
return handleAPI(request, env, ctx);
}
return new Response('Not Found', { status: 404 });
} catch (error) {
console.error('Worker error:', error);
return json({ error: 'Internal error' }, 500);
}
},
// Cron trigger
async scheduled(event: ScheduledEvent, env: Env, ctx: ExecutionContext) {
ctx.waitUntil(runScheduledTask(env));
}
};
CORS Headers (Essential)
const CORS_HEADERS = {
'Access-Control-Allow-Origin': '*', // Or specific origin
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
'Access-Control-Max-Age': '86400',
};
function handleCORS(): Response {
return new Response(null, { status: 204, headers: CORS_HEADERS });
}
function json(data: unknown, status = 200): Response {
return new Response(JSON.stringify(data), {
status,
headers: {
...CORS_HEADERS,
'Content-Type': 'application/json',
},
});
}
wrangler.toml Configuration
name = "my-worker"
main = "src/index.ts"
compatibility_date = "2024-01-01"
# KV Namespaces
kv_namespaces
binding = "MEETING_CACHE"
id = "abc123..." # Production
preview_id = "def456..." # Dev
kv_namespaces
binding = "RATE_LIMIT"
id = "ghi789..."
# Environment variables
[vars]
CACHE_TTL = "86400"
RATE_LIMIT_REQUESTS = "100"
RATE_LIMIT_WINDOW = "3600"
# Secrets (set via `wrangler secret put`)
# API_KEY, DATABASE_URL, etc.
# Cron triggers
[triggers]
crons = ["0 */6 * * *"] # Every 6 hours
# Custom routes
# routes = [{ pattern = "api.example.com/*", zone_name = "example.com" }]
KV Storage Patterns
Basic KV Operations
// Write with TTL
await env.CACHE.put('key', JSON.stringify(data), {
expirationTtl: 86400, // 24 hours in seconds
});
// Write with metadata
await env.CACHE.put('key', value, {
expirationTtl: 3600,
metadata: { createdAt: Date.now(), source: 'api' },
});
// Read
const value = await env.CACHE.get('key');
const parsed = await env.CACHE.get('key', 'json');
// Read with metadata
const { value, metadata } = await env.CACHE.getWithMetadata('key', 'json');
// Delete
await env.CACHE.delete('key');
// List keys
const { keys, cursor } = await env.CACHE.list({ prefix: 'meetings:' });
Geohash-Based Caching
import Geohash from 'latlon-geohash';
function getCacheKey(lat: number, lng: number, radius: number): string {
// 3-char geohash = ~150km cells, good for metro areas
const geohash = Geohash.encode(lat, lng, 3);
return `meetings:${geohash}:${radius}`;
}
async function getMeetingsWithCache(
lat: number,
lng: number,
radius: number,
env: Env
): Promise<{ data: Meeting[]; cached: boolean; geohash: string }> {
const geohash = Geohash.encode(lat, lng, 3);
const cacheKey = `meetings:${geohash}:${radius}`;
// Try cache first
const cached = await env.MEETING_CACHE.get(cacheKey, 'json');
if (cached) {
return { data: cached, cached: true, geohash };
}
// Fetch fresh data
const data = await fetchMeetings(lat, lng, radius);
// Cache in background (don't await)
env.ctx.waitUntil(
env.MEETING_CACHE.put(cacheKey, JSON.stringify(data), {
expirationTtl: 86400,
metadata: { cachedAt: Date.now(), geohash },
})
);
return { data, cached: false, geohash };
}
Response Headers for Cache Debugging
function meetingsResponse(data: Meeting[], cached: boolean, geohash: string): Response {
return new Response(JSON.stringify(data), {
headers: {
...CORS_HEADERS,
'Content-Type': 'application/json',
'X-Cache': cached ? 'HIT' : 'MISS',
'X-Geohash': geohash,
'Cache-Control': 'public, max-age=3600',
Установить cloudflare-worker-dev в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
ReadWriteEditBashGrepGlobВложенные файлы
FAQ
Что делает скилл cloudflare-worker-dev?
Cloudflare Workers, KV, Durable Objects, and edge computing development. Use for serverless APIs, caching, rate limiting, real-time features. Activate on "Workers", "KV", "Durable Objects", "wrangler", "edge function", "Cloudflare". NOT for Cloudflare Pages configuration (use deployment docs), DNS management, or general CDN settings.
Как установить скилл cloudflare-worker-dev?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл cloudflare-worker-dev запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
theme-factory
Toolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-set themes with…
от Anthropicaccess
Manage Discord channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropicconfigure
Set up the Discord channel — save the bot token and review access policy. Use when the user pastes a Discord bot token, asks to configure Discord, asks "how…
от Anthropicaccess
Manage iMessage channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropic