Created
September 20, 2019 07:54
-
-
Save lifez/11721ceb27e2ce1cf126bcd261591667 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const EventEmitter = require("eventemitter3") | |
const emitter = new EventEmitter() | |
const express = require("express") | |
const cors = require("cors") | |
var app = express() | |
const subscribe = (req, res) => { | |
res.writeHead(200, { | |
"Content-Type": "text/event-stream", | |
"Cache-Control": "no-cache", | |
Connection: "keep-alive" | |
}) | |
const onMessage = data => { | |
res.write(`data: ${JSON.stringify(data)}\n\n`) | |
} | |
emitter.on("message", onMessage) | |
req.on("close", function() { | |
emitter.removeListener("message", onMessage) | |
}) | |
} | |
const publish = (req, res) => { | |
emitter.emit("message", req.body) | |
res.json({ message: "success" }) | |
} | |
app.use(cors()) | |
app.use(express.json()) | |
app.post("/", publish) | |
app.get("/", subscribe) | |
app.listen(3000, () => {}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment