Cấp độ: intermediate45 phútminMiễn phíFreeBuilder & EntrepreneurBuilder & Entrepreneur

Cloudflare Workers: Edge ComputingCloudflare Workers: Edge computing

API edge function trên Cloudflare WorkersAn edge API function on Cloudflare Workers

Bạn sẽ học gìWhat you will learn

  • Tạo Worker xử lý HTTP requestCreate a Worker handling HTTP requests
  • Dùng KV để lưu dữ liệuUse KV to store data
  • Deploy và monitor WorkerDeploy and monitor the Worker

Bạn sẽ tạo gìWhat you will build

API edge function trên Cloudflare WorkersAn edge API function on Cloudflare Workers

Nội dung bài họcLesson content

Edge computing là gì?What is edge computing?

Edge computing là chạy code tại các máy chủ gần user nhất (toàn cầu), thay vì 1 server trung tâm. Cloudflare Workers chạy code JavaScript trên 300+ location toàn cầu. Latency thấp (<50ms), tự động scale, không cần quản server. Lý tưởng cho API, redirect, A/B test.Edge computing is running code at servers closest to the user (globally), instead of 1 central server. Cloudflare Workers runs JavaScript code across 300+ global locations. Low latency (<50ms), auto-scaling, no server management. Ideal for APIs, redirects, A/B testing.

Tạo Worker đầu tiênCreating your first Worker

Worker là 1 file JavaScript export default object với method fetch. Mỗi request đến sẽ gọi fetch(request, env, ctx). Trả về Response. Cài wrangler: npm install -g wrangler. Tạo: wrangler generate my-worker. Deploy: wrangler deploy.A Worker is 1 JavaScript file exporting a default object with a fetch method. Each incoming request calls fetch(request, env, ctx). Returns a Response. Install wrangler: npm install -g wrangler. Create: wrangler generate my-worker. Deploy: wrangler deploy.

javascript
                      
                        // src/index.js — Cloudflare Worker
export default {
  async fetch(request, env) {
    const url = new URL(request.url);
    
    if (url.pathname === '/api/hello') {
      return Response.json({
        message: 'Xin chào từ Edge! / Hello from Edge!',
        region: request.cf?.country ?? 'unknown',
        timestamp: new Date().toISOString()
      });
    }
    
    if (url.pathname === '/api/echo' && request.method === 'POST') {
      const body = await request.json();
      return Response.json({ you_sent: body });
    }
    
    return new Response('Not found', { status: 404 });
  }
};
                      
                    

KV: Key-Value storageKV: Key-Value storage

KV (Workers KV) là database key-value toàn cầu, đọc nhanh. Lý tưởng cho config, session, cache. Tạo KV namespace trong wrangler.toml. Dùng env.KV_NAMESPACE.get(key) / put(key, value). Lưu ý: KV là eventually consistent — không dùng cho dữ liệu cần nhất quán ngay.KV (Workers KV) is a global key-value database with fast reads. Ideal for config, sessions, cache. Create a KV namespace in wrangler.toml. Use env.KV_NAMESPACE.get(key) / put(key, value). Note: KV is eventually consistent — don't use for data needing immediate consistency.

javascript
                      
                        // wrangler.toml
# [[kv_namespaces]]
# binding = "MY_KV"
# id = "abc123..."

// src/index.js
export default {
  async fetch(request, env) {
    const url = new URL(request.url);
    
    // Lưu giá trị
    if (url.pathname === '/set') {
      await env.MY_KV.put('greeting', 'Xin chào từ KV!');
      return new Response('Đã lưu');
    }
    
    // Đọc giá trị
    if (url.pathname === '/get') {
      const value = await env.MY_KV.get('greeting');
      return Response.json({ greeting: value });
    }
    
    return new Response('Not found', { status: 404 });
  }
};
                      
                    

D1: SQL database trên EdgeD1: SQL database on the Edge

D1 là SQLite-based database của Cloudflare. ACID, SQL đầy đủ. Tạo: wrangler d1 create my-db. Bind trong wrangler.toml. Dùng env.DB.prepare(sql).bind(...).run/all/first. D1 phù hợp cho dữ liệu cần query phức tạp, transaction.D1 is Cloudflare's SQLite-based database. ACID, full SQL. Create: wrangler d1 create my-db. Bind in wrangler.toml. Use env.DB.prepare(sql).bind(...).run/all/first. D1 suits data needing complex queries, transactions.

javascript
                      
                        // wrangler.toml
# [[d1_databases]]
# binding = "DB"
# database_name = "my-db"
# database_id = "abc123..."

// src/index.js
export default {
  async fetch(request, env) {
    const url = new URL(request.url);
    
    if (url.pathname === '/users') {
      const users = await env.DB.prepare(
        'SELECT id, name, email FROM users ORDER BY name'
      ).all();
      return Response.json({ users: users.results });
    }
    
    if (url.pathname === '/users' && request.method === 'POST') {
      const { name, email } = await request.json();
      await env.DB.prepare(
        'INSERT INTO users (name, email) VALUES (?, ?)'
      ).bind(name, email).run();
      return Response.json({ success: true }, { status: 201 });
    }
    
    return new Response('Not found', { status: 404 });
  }
};
                      
                    

Bài tập thực hànhHands-on exercises

1Tạo Worker với endpoint GET /api/time trả về thời gian hiện tại và country của request.Create a Worker with endpoint GET /api/time returning current time and the request's country.

Gợi ýHint

Dùng new Date().toISOString() và request.cf?.country.Use new Date().toISOString() and request.cf?.country.

Lời giảiSolution
javascript
                      
                        export default {
  async fetch(request, env) {
    const url = new URL(request.url);
    if (url.pathname === '/api/time') {
      return Response.json({
        time: new Date().toISOString(),
        country: request.cf?.country ?? 'unknown'
      });
    }
    return new Response('Not found', { status: 404 });
  }
};
                      
                    

2Thêm endpoint POST /api/visit lưu visit count vào KV, mỗi request tăng 1. GET /api/visits trả về count.Add endpoint POST /api/visit saving visit count to KV, incrementing by 1 each request. GET /api/visits returns the count.

Gợi ýHint

env.MY_KV.get('count') → parseInt → +1 → env.MY_KV.put('count', ...).env.MY_KV.get('count') → parseInt → +1 → env.MY_KV.put('count', ...).

Lời giảiSolution
javascript
                      
                        export default {
  async fetch(request, env) {
    const url = new URL(request.url);
    
    if (url.pathname === '/api/visit' && request.method === 'POST') {
      const current = parseInt(await env.MY_KV.get('count') || '0');
      await env.MY_KV.put('count', (current + 1).toString());
      return Response.json({ count: current + 1 });
    }
    
    if (url.pathname === '/api/visits') {
      const count = await env.MY_KV.get('count') || '0';
      return Response.json({ count: parseInt(count) });
    }
    
    return new Response('Not found', { status: 404 });
  }
};
                      
                    

Kiểm traQuiz

Chọn đáp án đúng cho mỗi câu. Nhấn để xem giải thích.Choose the correct answer for each question. Click to see explanation.

Câu 1: Edge computing có lợi ích gì?Q1: What is the benefit of edge computing?

Câu 2: Worker export default object cần method nào?Q2: Which method does a Worker's default export object need?

Câu 3: KV (Workers KV) là gì?Q3: What is KV (Workers KV)?

Câu 4: D1 dựa trên database engine nào?Q4: Which database engine is D1 based on?

Code mẫuSample code

javascript
                // Cloudflare Worker
export default {
  async fetch(request, env) {
    const url = new URL(request.url);
    
    if (url.pathname === '/api/hello') {
      return Response.json({
        message: 'Xin chào từ Edge! / Hello from Edge!',
        region: request.cf?.country ?? 'unknown',
      });
    }
    
    return new Response('Not found', { status: 404 });
  },
};