Deno와 엣지 저장소 통합
데이터 관리를 위해 Cloudflare KV 및 Durable Objects와 상호작용하는 Deno 함수를 개발합니다.
Deno와 엣지 저장소 통합은(는) CoddyKit의 무료 Edge Computing with Cloudflare Workers & Deno 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 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:
- Your Deno app sends an HTTP POST request to a specific endpoint on your Cloudflare Worker.
- The Worker receives this request, extracts the key and value from the request body.
- The Worker uses its bound KV namespace (e.g.,
MY_KV.put(key, value)) to store the data. - 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:
- Your Deno app sends an HTTP GET request to your Cloudflare Worker, usually including the key in the URL path or query parameters.
- The Worker receives this request, extracts the key.
- The Worker uses
env.MY_KV.get(key)to retrieve the data. - 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.
AI 튜터와 함께 Edge Computing with Cloudflare Workers & Deno을(를) 배우세요 — 무료
브라우저에서 실제 코드를 작성하고 실행하며, 24/7 AI 튜터로부터 즉각적인 도움을 받고, 웹이나 앱에서 중단한 부분부터 계속 학습하세요.
- 코스
- 12
- 레슨
- 47
자주 묻는 질문
“Deno와 엣지 저장소 통합” 강의는 무료인가요?
네 — “Deno와 엣지 저장소 통합” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Edge Computing with Cloudflare Workers & Deno 강의 전체를 잠금 해제할 수 있습니다. Edge Computing with Cloudflare Workers & Deno 강의에는 총 4개의 강의가 포함되어 있습니다.
“Deno와 엣지 저장소 통합”에서 뭘 배우나요?
데이터 관리를 위해 Cloudflare KV 및 Durable Objects와 상호작용하는 Deno 함수를 개발합니다. 브라우저에서 직접 실행하는 실습 코드로 Edge Computing with Cloudflare Workers & Deno을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Edge Computing with Cloudflare Workers & Deno을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Edge Computing with Cloudflare Workers & Deno은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“Deno와 엣지 저장소 통합” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Edge Computing with Cloudflare Workers & Deno 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Edge Computing with Cloudflare Workers & Deno 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- Cloudflare KV 저장소
- Durable Objects 이해하기
- Deno와 엣지 저장소 통합
- 엣지에서 D1 SQL로 질의하기