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

พร็อกซีฐานข้อมูลด้วย Deno

สร้างพร็อกซีฐานข้อมูลที่มีประสิทธิภาพด้วย Deno และ Workers เพื่อเชื่อมต่อกับฐานข้อมูลแบบดั้งเดิมหรือแบบไร้เซิร์ฟเวอร์

พร็อกซีฐานข้อมูลด้วย 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 บทเรียน

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

What are Database Proxies?

Welcome to our lesson on Deno database proxies! An edge database proxy acts as an intermediary layer between your application (like a Cloudflare Worker) and your database.

Instead of your edge function connecting directly to the database, it talks to the proxy. The proxy then handles the actual database connection.

  • Why use them? They centralize connection management, enhance security, and enable data transformation before reaching your database.

Why Deno for Proxies?

Deno is an excellent choice for building these database proxies at the edge. Here's why:

  • Native HTTP Server: Deno has a powerful, built-in web server, perfect for handling proxy requests.
  • Security Model: Its granular permission system means you explicitly grant network or file access, enhancing security.
  • Performance: Deno's fast startup times and efficient runtime make it suitable for responsive proxy services.
  • TypeScript First: Built-in TypeScript support helps you write more robust and maintainable code for your proxy logic.

Your First Deno Proxy Server

Let's start by creating a basic Deno HTTP server. This server will listen for incoming requests and respond with a simple message, acting as the foundation for our proxy.

Try running this example:

Deno.serve(async (req) => {
  const url = new URL(req.url);
  if (url.pathname === "/") {
    return new Response("Deno Proxy is running!", { status: 200 });
  }
  return new Response("Not Found", { status: 404 });
}, { port: 8000 });

console.log("Deno proxy listening on http://localhost:8000");

Forwarding Requests to DB

Now, let's modify our Deno proxy to forward incoming requests to a 'mock' database endpoint. In a real scenario, this would be your actual database API or a service that interacts with it.

Here, we use a public JSONPlaceholder API to simulate a database call.

Deno.serve(async (req) => {
  // Mock database endpoint (e.g., a public API)
  const mockDbApi = "https://jsonplaceholder.typicode.com/posts";
  const url = new URL(req.url);

  // Construct the target URL for the actual database call
  let targetUrl = mockDbApi;
  if (url.pathname !== "/") {
    targetUrl += url.pathname; // Append path for specific resources
  }

  const proxyReq = new Request(targetUrl, {
    method: req.method,
    headers: req.headers, // Pass original headers
    body: req.body,       // Pass original body
  });

  try {
    const dbResponse = await fetch(proxyReq);
    // Add a custom header to indicate proxy processing
    const newResponse = new Response(dbResponse.body, dbResponse);
    newResponse.headers.set("X-Proxy-By", "Deno");
    return newResponse;
  } catch (error) {
    return new Response(`Proxy Error: ${error.message}`, { status: 500 });
  }
}, { port: 8000 });

console.log("Deno proxy forwarding on http://localhost:8000");

The Need for Connection Pooling

Database connections are expensive to establish. Serverless functions, like Cloudflare Workers, are often short-lived and stateless. If each Worker instance opens a new connection, you can quickly exhaust database connection limits.

Connection pooling is a technique where a pool of open, reusable database connections is maintained. When a request comes in, a connection is borrowed from the pool instead of creating a new one.

Proxy's Role in Pooling

A Deno database proxy can effectively manage connection pooling. Unlike ephemeral Workers, a Deno proxy (e.g., deployed on Deno Deploy or a persistent server) can be a long-lived process.

This allows it to maintain and manage a pool of database connections, serving multiple requests from various Workers without constantly opening and closing connections. This significantly reduces overhead and improves database performance and stability.

Secure Your Database Proxy

Security is paramount. Your Deno proxy acts as a gateway to your database, so it must be secured:

  • Hide Credentials: Never expose raw database credentials in your Worker code. The proxy should store and use these securely.
  • Authentication for Proxy: Implement authentication (e.g., API keys, JWTs) for your Workers to access the proxy itself. This ensures only authorized edge functions can send requests.
  • Permissions: Deno's explicit permission model helps. Only grant the proxy network access to your database, not arbitrary internet access.

Transforming Data at the Edge

Beyond just forwarding, a Deno proxy can transform data. This means modifying request bodies before sending them to the database or altering responses before returning them to the Worker.

This is useful for adding metadata, filtering sensitive information, or normalizing data formats.

Deno.serve(async (req) => {
  const mockDbApi = "https://jsonplaceholder.typicode.com/posts";
  const url = new URL(req.url);
  let targetUrl = mockDbApi;

  // Only transform POST requests for simplicity
  if (req.method === "POST") {
    let requestBody = await req.json(); // Assuming JSON body
    requestBody.processedAt = new Date().toISOString(); // Add a timestamp
    requestBody.source = "edge-proxy"; // Add a source identifier

    const proxyReq = new Request(targetUrl, {
      method: req.method,
      headers: {
        ...req.headers,
        "Content-Type": "application/json" // Ensure correct type
      },
      body: JSON.stringify(requestBody), // Send modified body
    });
    const dbResponse = await fetch(proxyReq);
    return new Response(dbResponse.body, dbResponse);
  } else {
    // For other methods, just forward
    const dbResponse = await fetch(new Request(targetUrl, req));
    return new Response(dbResponse.body, dbResponse);
  }
}, { port: 8000 });

console.log("Deno proxy with data transformation on http://localhost:8000");

Worker to Deno Proxy Flow

How would a Cloudflare Worker interact with this Deno proxy?

The Worker would simply make a standard HTTP fetch request to the Deno proxy's endpoint. If your Deno proxy is deployed on a platform like Deno Deploy, it will have a public URL.

The Worker sends its request, the Deno proxy processes it (e.g., handles pooling, adds security, transforms data), and then forwards it to the actual database, returning the database's response to the Worker.

Deno Proxy Benefits?

Which of the following are benefits of using a Deno-based database proxy at the edge?

Lesson Summary

In this lesson, we explored how to create efficient database proxies using Deno. We learned that Deno's native HTTP server and security model make it ideal for this task.

  • We built a basic proxy that forwards requests.
  • Understood the importance of connection pooling and the proxy's role in it.
  • Discussed securing your proxy and transforming data at the edge.
  • Finally, we saw how Cloudflare Workers can interact with such a proxy.

This pattern provides a powerful way to manage database interactions from your edge applications.

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

บทเรียน “พร็อกซีฐานข้อมูลด้วย Deno” ฟรีหรือไม่

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

คุณจะเรียนรู้อะไรในบทเรียน “พร็อกซีฐานข้อมูลด้วย Deno”

สร้างพร็อกซีฐานข้อมูลที่มีประสิทธิภาพด้วย Deno และ Workers เพื่อเชื่อมต่อกับฐานข้อมูลแบบดั้งเดิมหรือแบบไร้เซิร์ฟเวอร์ คุณปฏิบัติ 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. Workers Sites และ Pages
  2. การผสานเฟรมเวิร์กส่วนหน้า
  3. พร็อกซีฐานข้อมูลด้วย Deno
  4. การเรนเดอร์ฝั่งเซิร์ฟเวอร์ที่เอดจ์
← กลับไปที่ Edge Computing with Cloudflare Workers & Deno