0Pricing
Edge Computing with Cloudflare Workers & Deno · レッスン

共有ロジックとユーティリティ

Deno環境とWorker環境で再利用できる共有ユーティリティ関数とビジネスロジックを実装します

「共有ロジックとユーティリティ」はCoddyKit上の無料Edge Computing with Cloudflare Workers & Denoレッスンです。 これはレッスン3/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応の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!

よくある質問

「共有ロジックとユーティリティ」レッスンは無料ですか?

はい。「共有ロジックとユーティリティ」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Edge Computing with Cloudflare Workers & Denoコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Edge Computing with Cloudflare Workers & Denoコースには全4レッスンが含まれています。

「共有ロジックとユーティリティ」で何を学びますか?

Deno環境とWorker環境で再利用できる共有ユーティリティ関数とビジネスロジックを実装します ブラウザで直接実行するハンズオンコードでEdge Computing with Cloudflare Workers & Denoを演習し、24時間対応の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に戻る