forked from redis-developer/banking-on-redis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
89 lines (72 loc) · 2.58 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import 'dotenv/config.js'
import * as cron from 'node-cron'
import express from 'express'
import serveStatic from 'serve-static'
import bodyParser from 'body-parser'
import session from 'express-session'
import { RedisStackStore } from 'connect-redis-stack'
import { createBankTransaction } from './transactions/transactionsGenerator.js'
import { config } from './config.js'
import { redis, redis2 } from './om/client.js'
import { accountRouter } from './routers/account-router.js'
import { transactionRouter } from './routers/transaction-router.js'
import { WebSocketServer } from 'ws';
/* configure your session store */
const store = new RedisStackStore({
client: redis,
prefix: 'redisBank:',
ttlInSeconds: 3600
})
const app = express();
app.use(bodyParser.urlencoded({extended:true}));
app.use(express.json())
app.use(session({
store: store,
resave: false,
saveUninitialized: false,
secret: '5UP3r 53Cr37'
}))
// set up a basic web sockect server and a set to hold all the sockets
const wss = new WebSocketServer({ port: config.websocketPort})
const sockets = new Set()
// when someone connects, add their socket to the set of all sockets
// and remove them if they disconnect
wss.on('connection', socket => {
sockets.add(socket)
socket.on('close', () => sockets.delete(socket))
})
const streamKey = 'transactions'
let currentId = '$'
cron.schedule('*/10 * * * * *', async () => {
createBankTransaction()
const result = await redis2.xRead({ key: streamKey, id: currentId }, { COUNT: 1, BLOCK: 10000 });
// pull the values for the event out of the result
const [ { messages } ] = result
const [ { id, message } ] = messages
const event = { ...message }
sockets.forEach(socket => socket.send(JSON.stringify(event)))
// update the current id so we get the next event next time
currentId = id
});
app.use(serveStatic('static', { index: ['auth-login.html'] }))
/* bring in some routers */
app.use('/account', accountRouter)
app.use('/transaction', transactionRouter)
/* websocket poll response */
app.get('/api/config/ws', (req, res) => {
res.json({"protocol":"ws","host":"localhost", "port": config.websocketPort, "endpoint":"/websocket"})
})
app.post('/perform_login', (req, res) => {
let session = req.session
console.log(session)
if(req.body.username == 'bob' &&
req.body.password == 'foobared') {
session=req.session;
session.userid=req.body.username;
res.redirect('/index.html')
} else {
res.redirect('/auth-login.html')
}
})
/* start the server */
app.listen(config.expressPort, () => console.log(`Listening on port ${config.expressPort}`))