Use Cases

Cloudflare Workers com Claude Code

Aprenda sobre Cloudflare Workers usando o Claude Code. Dicas práticas e exemplos de código incluídos.

Acelerando o Desenvolvimento com Cloudflare Workers usando Claude Code

O Cloudflare Workers é uma plataforma serverless que permite executar JavaScript/TypeScript na rede global da Cloudflare. Baseado no engine V8, oferece respostas rápidas com zero cold start. Com o Claude Code, você pode trabalhar eficientemente com as APIs e bindings específicos dos Workers.

Iniciando o Projeto

> Crie um projeto Cloudflare Workers.
> Com configuração usando framework Hono e banco de dados D1.
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"

Implementação de API com Hono

> Crie uma API CRUD com o framework Hono.
> Implemente também a integração com banco de dados D1.
// 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());

// Lista de artigos
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 });
});

// Criação de artigo
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();

  // Limpar cache
  await c.env.CACHE.delete('posts:latest');

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

// Upload de imagem (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;

Migração do Banco de Dados D1

-- 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);
# Executar migrações
npx wrangler d1 migrations apply my-database

# Desenvolvimento local
npx wrangler d1 migrations apply my-database --local
npx wrangler dev

Utilizando Cache KV

// 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;
}

// Exemplo de uso
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 // Cache de 5 minutos
  );

  return c.json(stats);
});

Deploy e Monitoramento

# Deploy
npx wrangler deploy

# Verificar logs
npx wrangler tail

# Configurar secrets
npx wrangler secret put JWT_SECRET

Resumo

Combinando os bindings avançados do Cloudflare Workers com o Claude Code, você pode construir eficientemente APIs full-stack que rodam no edge. Consulte também o Guia de Funções Serverless e a Introdução ao Edge Computing.

Para mais detalhes sobre Cloudflare Workers, consulte a documentação oficial do Cloudflare Workers.

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