ホームページ  >  記事  >  ウェブフロントエンド  >  イベントエミッターを使用した EDD

イベントエミッターを使用した EDD

DDD
DDDオリジナル
2024-10-25 05:42:29233ブラウズ

EDD with event emitters

イベント エミッターを使用して、node.js でイベント駆動型アプリケーションを構築します。 Node.js アーキテクチャの中核となる組み込みモジュール。 EventEmitter は、node.js でパブリッシャーとサブスクライバーのパターンを作成するのに役立つクラスです。

ユーザーがバスの座席を予約し、予約が成功したときに電子メール通知を受け取ることができるバス予約アプリケーションを構築することによって、EventEmitter を使用する方法を見ていきます。まず、/book ルートを使用して簡単な Express アプリケーションをセットアップします。

index.js

import express from "express"
import { addTrip } from "./utils"

const app = express()

app.post("/book", (req, res) = {
    const {origin, destination, date} = req.body;

    if (!(origin && destination && date)) {
        res.status(400).send("Invalid request")
    }

    addTrip({
        origin, destination, date
    }).then((response) => {
        if (response.status) {
            // send notification to user
            // we can make a request to an email service (like resend) 
            // to send the user the notification. But this will mean we'll have
            // to wait for a response from resend before sending a response to the client.
            // This makes the response time a bit longer
        } else {
            // somehting went wrong
        }
    }).catch((error) => {
        // an error occured
        res.status(400).send(error.message)
    }).finally(() => {
        res.status(200).send("Request Received")
    })
})

app.listen(3000)

この単純なルートでは、電子メール通知を直接送信するロジックを追加すると、API が少し遅くなります。したがって、私たちができることは、旅行をデータベースに追加した後、名前付きイベントを発行するときに EventEmitter を使用することであり、リスターがイベントを選択して通知を送信します。これを追加する方法は次のとおりです。

import express from "express"
import EventEmitter from "node:events" // import the EventEmitter class
import { addTrip } from "./utils"

const app = express();
const myEmitter = new EventEmitter(); // We create an instance of the EventEmitter class

// Let's setup a listener to listen for a named event, in this case 'booking'
myEmitter.on("booking", (trip) => {
    // Make the call to your email service to send the email
    console.log(trip)
})

app.post("/book", (req, res) = {
    const {origin, destination, date} = req.body;

    if (!(origin && destination && date)) {
        res.status(400).send("Invalid request")
    }

    addTrip({
        origin, destination, date
    }).then((response) => {
        if (response.status) {
            // emit an event and the listener will pick it up
            let trip = response.data
            myEmitter.emit("book", trip)
        } else {
            // somehting went wrong
        }
    }).catch((error) => {
        // an error occured
        res.status(400).send(error.message)
    }).finally(() => {
        res.status(200).send("Request Received")
    })
})

app.listen(3000)

以上がイベントエミッターを使用した EDDの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。