0Pricing
Edge Computing with Cloudflare Workers & Deno · 课时

共享逻辑与实用工具

实现可在 Deno 与 Worker 环境之间复用的实用工具函数和业务逻辑

共享逻辑与实用工具 是 CoddyKit 上的免费 Edge Computing with Cloudflare Workers & Deno 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Edge Computing with Cloudflare Workers & Deno 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Edge Computing with Cloudflare Workers & Deno 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Introduction to Shared Logic

When building applications for both Deno and Cloudflare Workers, you often encounter code that performs similar tasks. This is where shared logic comes in handy!

Shared logic refers to writing common functions or modules once and reusing them across different parts of your application, regardless of the runtime environment.

Why Share Code?

Reusing code between Deno and Worker environments offers several key benefits:

  • Consistency: Ensures the same behavior and calculations everywhere.
  • Maintainability: Updates to logic only need to be made in one place.
  • Reduced Duplication: Avoids writing the same code multiple times, saving effort.
  • Faster Development: Leverage existing functions instead of starting from scratch.

What Can Be Shared?

Many types of code are perfect candidates for sharing:

  • Utility Functions: String formatting, date manipulation, mathematical helpers.
  • Data Validation: Ensuring input data meets specific criteria.
  • Business Logic: Core application rules or calculations.
  • Type Definitions: TypeScript interfaces or types for consistent data structures.

The best candidates are usually pure functions that don't rely heavily on environment-specific globals.

Deno's ES Module System

Deno embraces standard JavaScript ES Modules (ECMAScript Modules) with a URL-based import system. This means you can import modules using relative paths (e.g., ./myModule.ts) or full URLs.

This adherence to web standards is crucial because Cloudflare Workers also primarily use ES Modules, making Deno modules naturally compatible.

Developing a Core Utility

Let's create a simple utility function. We'll define a function formatGreeting that takes a name and returns a personalized greeting. This function is pure and doesn't rely on any Deno or Worker-specific APIs.

Imagine this code lives in a file like sharedUtils.ts.

export function formatGreeting(name: string): string {
  return `Hello, ${name}! Welcome to the Edge.`;
}

Running the Utility in Deno

Here's how you would use our formatGreeting utility within a Deno application. In a real project, you'd import it from ./sharedUtils.ts, but for this runnable example, we'll include it directly.

// This code would typically import from a shared file.
// For runnable demo, function is inline.

function formatGreeting(name: string): string {
  return `Hello, ${name}! Welcome from Deno.`;
}

// Use the shared utility
const userName = "Deno User";
console.log(formatGreeting(userName));

Workers & Shared Modules

Cloudflare Workers execute JavaScript and TypeScript at the edge. They support ES Modules, just like Deno.

This means a .ts or .js file containing shared utility functions can often be directly imported and used in your Worker code, assuming it doesn't contain Deno-specific runtime APIs.

Running the Utility in a Worker

Now, let's see our formatGreeting utility used inside a Cloudflare Worker. The Worker will respond with the formatted greeting, potentially using a name from the URL query parameters.

// This code would typically import from a shared file.
// For runnable demo, function is inline.

function formatGreeting(name: string): string {
  return `Hello, ${name}! Welcome from the Worker.`;
}

export default {
  async fetch(request: Request): Promise<Response> {
    const url = new URL(request.url);
    const name = url.searchParams.get('name') || 'Guest';

    // Use the shared utility
    return new Response(formatGreeting(name), {
      headers: { 'content-type': 'text/plain' },
    });
  },
};

Handling Environment Differences

While many utilities can be shared directly, some logic might need to adapt to its environment.

  • Environment Variables: Deno uses Deno.env.get(), Workers use the env object passed to fetch.
  • File System Access: Available in Deno, not directly in Workers.
  • Global Objects: Be mindful of differences in global APIs (though fetch is now widely available).

Use abstraction layers or conditional logic (e.g., if (typeof Deno !== 'undefined')) to manage these differences gracefully.

Check Your Understanding

Which of the following are primary benefits of implementing shared logic between Deno and Cloudflare Worker environments?

Recap & Next Steps

Great job! In this lesson, we explored how to create and manage shared utility functions and business logic that can be reused across both Deno and Cloudflare Worker environments.

  • We understood the benefits of code sharing, like consistency and maintainability.
  • We saw how ES Modules enable seamless integration.
  • We demonstrated a simple utility running in both Deno and a Cloudflare Worker.
  • We discussed strategies for handling environment-specific differences.

This approach is key to building robust and efficient edge applications!

常见问题解答

「共享逻辑与实用工具」课时是免费的吗?

是的 — 「共享逻辑与实用工具」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Edge Computing with Cloudflare Workers & Deno 课程的其余内容,请升级到 CoddyKit PRO。 Edge Computing with Cloudflare Workers & Deno 课程共包含 4 节课。

「共享逻辑与实用工具」这节课中我会学到什么?

实现可在 Deno 与 Worker 环境之间复用的实用工具函数和业务逻辑 你通过在浏览器中直接运行的动手代码来练习 Edge Computing with Cloudflare Workers & Deno,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Edge Computing with Cloudflare Workers & Deno 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Edge Computing with Cloudflare Workers & Deno 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。

「共享逻辑与实用工具」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Edge Computing with Cloudflare Workers & Deno 课中编写并运行代码吗?

能。每节 Edge Computing with Cloudflare Workers & Deno 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. Cloudflare Workers 中的 Deno
  2. Worker-Deno 项目设置
  3. 共享逻辑与实用工具
  4. 部署与调试集成技术栈
← 返回 Edge Computing with Cloudflare Workers & Deno