首頁  >  文章  >  web前端  >  帶有事件發射器的 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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn