1
\$\begingroup\$

This is a simple app, made with koa, that grabs a question from a database of questions and sends them over websocket. It feels really messy to me.

'use strict'

var koa = require('koa')
var route = require('koa-route')
var kws = require('koa-websocket')
var sqlite3 = require('sqlite3')

var app = kws(koa())

var userList = []

function remove (ws) {
  userList.splice(userList.indexOf(ws), 1)
}

app.ws.use(route.all('/ws', function* (next) {
  this.websocket.on('message', msg => this.websocket.send(msg))
  userList.push(this.websocket)
  this.websocket.room = 'lobby' // Set everyone to lobby (for now)
  this.websocket.onclose = () => { remove(this.websocket) }
  yield next
}))

;(function () {
  var curQuestion = 0
  var qArray = []
  var db = new sqlite3.Database('db.sqlite')
  ;(function doLoop () {
    if (qArray.length > 0) {
      var word = qArray.shift()
      userList.forEach(i => i.readyState === 1 ? i.send(i.room + '|' + word) : remove(i))
    } else {
      db.get('SELECT * FROM tossupsdbnew ORDER BY RANDOM() LIMIT 1;', (err, row) => {
        if (err) throw err
        qArray = row.Question.split(' ')
        qArray.unshift(curQuestion.Answer)
        curQuestion = row
      })
    }
    setTimeout(doLoop, qArray.length ? 200 : 1000)
  })()
})()
// Some code that serves some basic html templates...
app.listen(8080, '0.0.0.0')

tossupsdbnew table schema:

CREATE TABLE `tossupsdbnew` (`ID` integer NOT NULL PRIMARY KEY AUTOINCREMENT, `Answer` text NOT NULL, `Category` varchar(255) NOT NULL, `Subcategory` varchar(255) NOT NULL, `Difficulty` text NOT NULL, `Question #` integer NOT NULL, `Question` varchar(21000) NOT NULL, `Round` text NOT NULL, `Tournament` varchar(225) NOT NULL, `Year` integer NOT NULL);
\$\endgroup\$
  • \$\begingroup\$ Tell us more about what the tossupsdbnew table looks like? (Schema and sample data) \$\endgroup\$ – 200_success Jan 4 '17 at 18:33
  • \$\begingroup\$ edited in schema \$\endgroup\$ – alchzh Jan 4 '17 at 19:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.