Use Cases

Claude Code के साथ Cloudflare Workers

Claude Code का उपयोग करके Cloudflare Workers सीखें। Practical tips और code examples शामिल हैं।

Claude Code से Cloudflare Workers Development को तेज़ करें

Cloudflare Workers, Cloudflare के global network पर JavaScript/TypeScript run करने वाला serverless platform है। V8 engine पर आधारित, zero cold start के साथ तेज़ response देता है। Claude Code का उपयोग करके, Workers-specific APIs और bindings को भी efficiently handle किया जा सकता है।

Project Setup

> Cloudflare Workers का project बनाओ।
> Hono framework और D1 database use करने वाला setup।
npm create cloudflare@latest my-worker -- --template=hello-world
cd my-worker
npm install hono
# wrangler.toml
name = "my-api"
main = "src/index.ts"
compatibility_date = "2024-12-01"

[[d1_databases]]
binding = "DB"
database_name = "my-database"
database_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"

[[kv_namespaces]]
binding = "CACHE"
id = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

[[r2_buckets]]
binding = "STORAGE"
bucket_name = "my-bucket"

Hono से API Implementation

> Hono framework से CRUD API बनाओ।
> D1 database के साथ integration भी implement करो।
// src/index.ts
import { Hono } from 'hono';
import { cors } from 'hono/cors';
import { jwt } from 'hono/jwt';

type Bindings = {
  DB: D1Database;
  CACHE: KVNamespace;
  STORAGE: R2Bucket;
  JWT_SECRET: string;
};

const app = new Hono<{ Bindings: Bindings }>();

app.use('/api/*', cors());

// Articles की list
app.get('/api/posts', async (c) => {
  const { results } = await c.env.DB.prepare(
    'SELECT * FROM posts ORDER BY created_at DESC LIMIT 20'
  ).all();

  return c.json({ posts: results });
});

// Article बनाना
app.post('/api/posts', async (c) => {
  const { title, content } = await c.req.json();

  const result = await c.env.DB.prepare(
    'INSERT INTO posts (title, content, created_at) VALUES (?, ?, datetime())'
  )
    .bind(title, content)
    .run();

  // Cache clear करें
  await c.env.CACHE.delete('posts:latest');

  return c.json({ id: result.meta.last_row_id }, 201);
});

// Image upload (R2)
app.post('/api/upload', async (c) => {
  const formData = await c.req.formData();
  const file = formData.get('file') as File;

  if (!file) {
    return c.json({ error: 'File required' }, 400);
  }

  const key = `uploads/${Date.now()}-${file.name}`;
  await c.env.STORAGE.put(key, file.stream(), {
    httpMetadata: { contentType: file.type },
  });

  return c.json({ key, url: `/api/files/${key}` });
});

export default app;

D1 Database Migration

-- migrations/0001_create_tables.sql
CREATE TABLE IF NOT EXISTS posts (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  title TEXT NOT NULL,
  content TEXT NOT NULL,
  slug TEXT UNIQUE,
  published BOOLEAN DEFAULT FALSE,
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
);

CREATE INDEX idx_posts_slug ON posts(slug);
CREATE INDEX idx_posts_published ON posts(published, created_at);
# Migration चलाएं
npx wrangler d1 migrations apply my-database

# Local development
npx wrangler d1 migrations apply my-database --local
npx wrangler dev

KV Cache का उपयोग

// src/cache.ts
export async function getCachedData<T>(
  kv: KVNamespace,
  key: string,
  fetcher: () => Promise<T>,
  ttl = 3600
): Promise<T> {
  const cached = await kv.get(key, 'json');
  if (cached) return cached as T;

  const data = await fetcher();
  await kv.put(key, JSON.stringify(data), { expirationTtl: ttl });
  return data;
}

// Usage example
app.get('/api/stats', async (c) => {
  const stats = await getCachedData(
    c.env.CACHE,
    'stats:daily',
    async () => {
      const { results } = await c.env.DB.prepare(
        'SELECT COUNT(*) as count FROM posts WHERE published = TRUE'
      ).all();
      return results[0];
    },
    300 // 5 minute cache
  );

  return c.json(stats);
});

Deploy और Monitoring

# Deploy
npx wrangler deploy

# Logs देखें
npx wrangler tail

# Secrets set करें
npx wrangler secret put JWT_SECRET

Summary

Cloudflare Workers की rich bindings और Claude Code को मिलाकर, edge पर चलने वाली full-stack API efficiently बना सकते हैं। Serverless functions guide और edge computing introduction भी reference के लिए देखें।

Cloudflare Workers के details के लिए Cloudflare Workers official documentation देखें।

#Claude Code #Cloudflare Workers #edge computing #serverless #API