>  기사  >  웹 프론트엔드  >  이벤트 이미터가 있는 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으로 문의하세요.