0Pricing
Edge Computing with Cloudflare Workers & Deno · บทเรียน

การผสาน Deno กับพื้นที่จัดเก็บใกล้ผู้ใช้

พัฒนาฟังก์ชัน Deno ที่โต้ตอบกับ Cloudflare KV และ Durable Objects เพื่อจัดการข้อมูล

การผสาน Deno กับพื้นที่จัดเก็บใกล้ผู้ใช้ เป็นบทเรียน Edge Computing with Cloudflare Workers & Deno ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Edge Computing with Cloudflare Workers & Deno และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Edge Computing with Cloudflare Workers & Deno มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Deno & Edge Storage Integration

Welcome! In previous lessons, we learned about Cloudflare KV and Durable Objects for storing data at the edge. Now, let's explore how Deno applications can interact with these powerful edge storage solutions.

Since Deno typically runs outside the Cloudflare Workers environment, we'll focus on how Deno can act as a client, communicating with Cloudflare Workers that then manage interactions with KV and Durable Objects.

Deno's Role: The Proxy Pattern

Deno applications, whether running locally or deployed on platforms like Deno Deploy, don't directly access Cloudflare's KV or Durable Objects.

Instead, Deno acts as a client, making standard HTTP requests to a Cloudflare Worker. This Worker then serves as a proxy, handling the actual interactions with KV or Durable Objects on the Cloudflare edge network.

  • Deno App: Sends HTTP requests (e.g., GET, POST).
  • Cloudflare Worker: Receives requests, accesses KV/DO, and sends responses.

Cloudflare KV: Quick Review

Remember, Cloudflare KV is a global, low-latency key-value store perfect for caching, configuration, and user preferences.

Workers interact with KV using simple APIs like KV.put() to store data and KV.get() to retrieve it. Our Deno client will send requests to a Worker, which will then use these KV operations.

Storing Data from Deno to KV

To store data from your Deno application into a Cloudflare KV namespace, the process typically involves these steps:

  1. Your Deno app sends an HTTP POST request to a specific endpoint on your Cloudflare Worker.
  2. The Worker receives this request, extracts the key and value from the request body.
  3. The Worker uses its bound KV namespace (e.g., MY_KV.put(key, value)) to store the data.
  4. The Worker sends an HTTP response back to the Deno app, confirming the operation.

Worker Proxy for KV Write

Here's a simple Cloudflare Worker that accepts POST requests to store data in a KV namespace named MY_KV. Remember to bind MY_KV in your wrangler.toml.

Try running this example:

export default {
  async fetch(request, env) {
    const url = new URL(request.url);
    if (request.method === "POST" && url.pathname === "/put") {
      try {
        const { key, value } = await request.json();
        if (!key || !value) {
          return new Response("Missing key or value", { status: 400 });
        }
        await env.MY_KV.put(key, value);
        return new Response(`Stored key: ${key}`, { status: 200 });
      } catch (error) {
        return new Response(`Error: ${error.message}`, { status: 500 });
      }
    }
    return new Response("Not found", { status: 404 });
  },
};

Deno Client Writing to KV

Now, let's create a Deno script that acts as the client. It will send a JSON payload to our Cloudflare Worker proxy to store data in KV.

You'll need to replace YOUR_WORKER_URL with your deployed Worker's URL.

Try running this example:

// main.ts
const workerUrl = "YOUR_WORKER_URL"; // e.g., "https://your-worker.your-account.workers.dev"

async function putDataToKv(key: string, value: string) {
  try {
    const response = await fetch(`${workerUrl}/put`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ key, value }),
    });

    if (response.ok) {
      console.log(`Successfully stored: ${await response.text()}`);
    } else {
      console.error(`Failed to store: ${response.status} ${response.statusText}`);
      console.error(await response.text());
    }
  } catch (error) {
    console.error("Network error:", error.message);
  }
}

// Example usage:
if (import.meta.main) {
  await putDataToKv("myKey", "myValue from Deno!");
  await putDataToKv("anotherKey", "Hello Edge!");
}

Retrieving Data from KV to Deno

Reading data follows a similar proxy pattern:

  1. Your Deno app sends an HTTP GET request to your Cloudflare Worker, usually including the key in the URL path or query parameters.
  2. The Worker receives this request, extracts the key.
  3. The Worker uses env.MY_KV.get(key) to retrieve the data.
  4. The Worker sends the retrieved value (or an error) as an HTTP response back to the Deno app.

Worker Proxy for KV Read

Let's add a GET endpoint to our Worker to fetch data from KV. This could be integrated into the previous Worker example.

Try running this example:

export default {
  async fetch(request, env) {
    const url = new URL(request.url);
    // Handle POST for putting data
    if (request.method === "POST" && url.pathname === "/put") {
      try {
        const { key, value } = await request.json();
        if (!key || !value) {
          return new Response("Missing key or value", { status: 400 });
        }
        await env.MY_KV.put(key, value);
        return new Response(`Stored key: ${key}`, { status: 200 });
      } catch (error) {
        return new Response(`Error: ${error.message}`, { status: 500 });
      }
    }
    // Handle GET for getting data
    if (request.method === "GET" && url.pathname.startsWith("/get/")) {
      const key = url.pathname.substring(5); // "/get/myKey" -> "myKey"
      if (!key) {
        return new Response("Missing key", { status: 400 });
      }
      const value = await env.MY_KV.get(key);
      if (value === null) {
        return new Response("Key not found", { status: 404 });
      }
      return new Response(value, { status: 200 });
    }
    return new Response("Not found", { status: 404 });
  },
};

Deno Client Reading from KV

Here's a Deno script to fetch data from the Worker's GET endpoint. This assumes you've already stored "myKey" and "anotherKey" using the previous Deno script.

Try running this example:

// main.ts
const workerUrl = "YOUR_WORKER_URL"; // e.g., "https://your-worker.your-account.workers.dev"

async function getDataFromKv(key: string) {
  try {
    const response = await fetch(`${workerUrl}/get/${key}`);

    if (response.ok) {
      console.log(`Value for '${key}': ${await response.text()}`);
    } else {
      console.error(`Failed to get data: ${response.status} ${response.statusText}`);
      console.error(await response.text());
    }
  } catch (error) {
    console.error("Network error:", error.message);
  }
}

// Example usage:
if (import.meta.main) {
  await getDataFromKv("myKey");
  await getDataFromKv("anotherKey");
  await getDataFromKv("nonExistentKey"); // Will show "Key not found"
}

Deno & Durable Objects

Durable Objects provide consistent state for individual users or entities at the edge. Just like KV, Deno applications interact with Durable Objects indirectly through a Cloudflare Worker.

The Worker will instantiate or get a reference to a Durable Object, call its methods, and then return the result to the Deno client. This pattern allows your Deno app to leverage stateful edge logic.

  • Deno App: Sends requests to a Worker.
  • Cloudflare Worker: Routes to a specific Durable Object instance, invokes methods.
  • Durable Object: Manages its internal state and responds.

Edge Storage Integration Check

Considering how Deno applications integrate with Cloudflare's edge storage services (KV and Durable Objects), what is the primary mechanism for this interaction?

Integrating Deno & Edge Storage

Great job! In this lesson, you've learned how to integrate Deno applications with Cloudflare KV and Durable Objects.

  • Deno acts as a client, sending HTTP requests.
  • Cloudflare Workers function as proxies, handling the actual storage operations.
  • This pattern allows Deno apps to leverage the power of edge data persistence securely and efficiently.

This integration opens up possibilities for building powerful full-stack applications with Deno on the client/server and Workers managing edge data.

คำถามที่พบบ่อย

บทเรียน “การผสาน Deno กับพื้นที่จัดเก็บใกล้ผู้ใช้” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การผสาน Deno กับพื้นที่จัดเก็บใกล้ผู้ใช้” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Edge Computing with Cloudflare Workers & Deno ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Edge Computing with Cloudflare Workers & Deno มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การผสาน Deno กับพื้นที่จัดเก็บใกล้ผู้ใช้”

พัฒนาฟังก์ชัน Deno ที่โต้ตอบกับ Cloudflare KV และ Durable Objects เพื่อจัดการข้อมูล คุณปฏิบัติ Edge Computing with Cloudflare Workers & Deno ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Edge Computing with Cloudflare Workers & Deno หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน Edge Computing with Cloudflare Workers & Deno บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน

บทเรียน “การผสาน Deno กับพื้นที่จัดเก็บใกล้ผู้ใช้” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน Edge Computing with Cloudflare Workers & Deno นี้ได้ไหม

ได้ บทเรียน Edge Computing with Cloudflare Workers & Deno ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. คลังข้อมูล Cloudflare KV
  2. อธิบาย Durable Objects
  3. การผสาน Deno กับพื้นที่จัดเก็บใกล้ผู้ใช้
  4. สืบค้นด้วย D1 SQL ที่เอดจ์
← กลับไปที่ Edge Computing with Cloudflare Workers & Deno