Created
March 20, 2019 02:03
-
-
Save receptor/915513c2ab979537978a66bcb08a1e01 to your computer and use it in GitHub Desktop.
Publish HTTP request to Redis channel
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
process.on("SIGINT", () => process.exit()); | |
import * as bodyParser from "body-parser"; | |
import express from "express"; | |
import redis from "redis"; | |
// logger | |
const now = () => new Date().toISOString(); | |
const loggerFacility = console; | |
const logger = { | |
error: (...args: any[]) => loggerFacility.error(now(), ...args), | |
log: (...args: any[]) => loggerFacility.log(now(), ...args), | |
}; | |
// publisher | |
const publisher = redis.createClient(); | |
publisher.on("ready", () => logger.log("publisher ready")); | |
publisher.on("connect", () => logger.log("publisher connected to", publisher.address)); | |
publisher.on("error", logger.error); | |
// server | |
const server = express(); | |
server.use(bodyParser.json()); | |
server.get("/:channel/:message", (req, res) => { | |
try { | |
const { channel, message } = req.params; | |
publisher.publish(channel, message, () => logger.log({channel, message})); | |
res.send("OK"); | |
} catch (e) { | |
logger.error(e); | |
res.sendStatus(500); | |
} | |
}); | |
server.post("/:channel", (req, res) => { | |
try { | |
const [ channel, message ] = [ req.params.channel, JSON.stringify(req.body) ]; | |
publisher.publish(channel, message, () => logger.log(now(), {channel, message})); | |
res.send("OK"); | |
} catch (e) { | |
logger.error(e); | |
res.sendStatus(500); | |
} | |
}); | |
server.listen(3333, () => logger.log("server listening on", 3333)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment