You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
apl-nuke/src/index.js

56 lines
1.4 KiB
JavaScript

const mongoose = require('mongoose')
const WebSocket = require('ws')
const url = require('url')
const app = require('./app')
const { get } = require('./uuids')
const handler = require('./ws/handler')
const { subscribe } = require('./ws/streams')
mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
})
const db = mongoose.connection
db.once('open', () => console.log('Connected to mongodb instance!'))
const port = process.env.PORT || 5000;
wss1 = new WebSocket.Server({
noServer: true,
})
wss2 = new WebSocket.Server({
noServer: true,
})
wss1.on('connection', (ws, req) => {
const id = req.id
handler(ws, id)
})
wss2.on('connection', (ws, req) => {
const id = req.id
subscribe(ws, id)
})
const server = app.listen(port, () => {
console.log(`Express listening: http://localhost:${port}`)
})
server.on('upgrade', (req, socket, head) => {
const pathname = url.parse(req.url).pathname.split('/')
const token = pathname[2]
if (pathname[1] === 'ws' && get(token)) {
wss1.handleUpgrade(req, socket, head, (socket) => {
req.id = token
wss1.emit('connection', socket, req);
})
} else if (pathname[1] === 'stream') {
wss2.handleUpgrade(req, socket, head, (socket) => {
req.id = token
wss2.emit('connection', socket, req);
})
}
})