Skip to content
This repository has been archived by the owner on Jun 22, 2023. It is now read-only.

Commit

Permalink
Initial version using pub/sub
Browse files Browse the repository at this point in the history
  • Loading branch information
moonglum committed Jul 15, 2018
0 parents commit 3585efd
Show file tree
Hide file tree
Showing 8 changed files with 2,260 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"extends": "standard"
}
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/dump.rdb
/node_modules
15 changes: 15 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# SSE Events with Node.js and Redis Streams

Goals:

* Demonstrate SSEs and how they are simpler than WebSockets
* Demonstrate the power of Redis and Redis Streams
* Show Progressive Enhancement with Custom Elements for a Chat App

## Setup

* `docker run --name chat -p 127.0.0.1:6379:6379/tcp --rm redis:5.0-rc3`
* `npm i`
* `npm start`

TODO: Docker Compose Setup
56 changes: 56 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
// TODO: Switch from pub/sub to Redis Streams
// TODO: Render all existing messages in the index action
let path = require('path')

let express = require('express')
let app = express()
let bodyParser = require('body-parser')
let cons = require('consolidate')

let Redis = require('ioredis')

app.set('views', path.resolve('views'))
app.engine('mustache', cons.mustache)
app.set('view engine', 'mustache')
app.use(bodyParser.urlencoded({ extended: false }))
app.use(express.static(path.resolve('public')))

app.get('/', function (req, res) {
res.render('index')
})

let publisher = new Redis()
app.post('/messages', function (req, res) {
let { message } = req.body
publisher.publish('updates', message)
res.redirect('/')
})

app.get('/update-stream', function (req, res) {
let messageCount = 0
let subscriber = new Redis()

subscriber.subscribe('updates')

subscriber.on('message', (channel, message) => {
messageCount++
res.write(`id: ${messageCount}\n`)
// We will use the same partial here that we use to render the items on the server side
res.write(`data: <strong>Unknown User:</strong> ${message} \n\n`)
})

res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
})
res.write('\n')

res.on('close', () => {
subscriber.unsubscribe()
subscriber.disconnect()
})
})

app.listen(8000)
console.log('App listening on 8000')
Loading

0 comments on commit 3585efd

Please sign in to comment.