首页  >  文章  >  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