该介绍目前仅提供英文版本。
Overview
This advanced course by Christian Freeman, a Cloudflare Developer Advocate, builds upon the foundational knowledge from “Workers 101”. The focus is on implementing state management and data persistence in Cloudflare Workers applications, addressing the challenge of data loss during application refreshes or restarts.
Prerequisites
- Completion of “Workers 101” video
- Familiarity with Wrangler CLI
- Basic understanding of Cloudflare Workers
State Management Solutions
1. Cloudflare Workers KV
A globally distributed key-value store that provides:
- Simple key-value storage with support for various data types
- Ideal for read-heavy workloads and caching
- Global deployment for low-latency access
Key Features
- Data Types: Supports strings, numbers, images, and JSON
- Size Limits: Has file size restrictions for values
- Use Cases: Perfect for caching API responses and frequently accessed data
Implementation
// Creating a KV namespace
npx wrangler kv:namespace create
// Accessing KV in Workers
const value = await c.env.CACHE.get('key', 'json')
await c.env.CACHE.put('key', JSON.stringify(data))
// Example: Caching GitHub API response
async function getGitHubData(username) {
const cacheKey = `github:${username}`
const cached = await c.env.CACHE.get(cacheKey, 'json')
if (cached) {
return cached
}
const response = await fetch(`https://api.github.com/users/${username}/repos`)
const data = await response.json()
await c.env.CACHE.put(cacheKey, JSON.stringify(data), {
expirationTtl: 3600 // Cache for 1 hour
})
return data
}
2. Cloudflare D1
A serverless SQL database offering:
- Full SQL support for structured data
- ACID compliance
- Schema management through migrations
Key Features
- SQL Support: Complete SQL functionality
- Schema Management: Structured data modeling
- Migrations: Version-controlled database changes
Implementation
// Creating a D1 database
npx wrangler d1 create
// Example: Movie database schema
// migrations/0000_create_movies.sql
CREATE TABLE movies (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
rating INTEGER,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
// Working with D1
const result = await c.env.DB.prepare('SELECT * FROM movies').all()
// Example: Movie API endpoints
app.get('/movies', async (c) => {
const movies = await c.env.DB.prepare('SELECT * FROM movies').all()
return c.json(movies)
})
app.post('/movies', async (c) => {
const { title, rating } = await c.req.json()
const result = await c.env.DB.prepare(
'INSERT INTO movies (title, rating) VALUES (?, ?)'
).bind(title, rating).run()
return c.json(result)
})
3. External Services Integration
Options for connecting with external services:
- Direct API integration using
fetch - ORM integration (e.g., Prisma)
- Custom service connections
Implementation with Prisma
// prisma/schema.prisma
datasource db {
provider = "sqlite"
url = env("DATABASE_URL")
}
model Movie {
id Int @id @default(autoincrement())
title String
rating Int?
createdAt DateTime @default(now())
}
// Using Prisma in Workers
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
const movies = await prisma.movie.findMany()
Development Tools
Hono Framework
- Modern web framework for Workers
- Built-in routing and middleware
- TypeScript support
Implementation
import { Hono } from 'hono'
import { cors } from 'hono/cors'
const app = new Hono()
app.use('*', cors())
app.get('/', (c) => c.text('Hello Hono!'))
app.get('/api/movies', async (c) => {
const movies = await c.env.DB.prepare('SELECT * FROM movies').all()
return c.json(movies)
})
export default app
HonoX
- Extension for full-stack applications
- Combines backend APIs with frontend UIs
- Enhanced development experience
Best Practices
-
Data Storage Selection
- Use KV for caching and simple key-value storage
- Choose D1 for structured, relational data
- Consider external services for specialized needs
-
Performance Optimization
- Implement caching strategies
- Use appropriate data structures
- Optimize database queries
-
Development Workflow
- Use migrations for database changes
- Implement proper error handling
- Follow security best practices
