A Twitch.tv viewer reward and games system.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

69 lines
2.9 KiB

  1. var http = require('http');
  2. //---- Construct ----
  3. function API(db, currency, options) {
  4. var __self = this;
  5. __self.db = db;
  6. __self.currency = currency;
  7. __self.port = options.port || 9000;
  8. }
  9. // ---- Methods ----
  10. API.prototype.start = function () {
  11. var __self = this;
  12. __self.srv = http.createServer( function(req, res) {
  13. if (req.method == "GET") {
  14. if (req.url == "/api/ladder/all") {
  15. // Returns the entire ladder from top to bottom
  16. sql = 'SELECT * FROM viewers ORDER BY points DESC;';
  17. __self.db.execute(sql, function(rows) {
  18. var data = new Object();
  19. data['viewers'] = rows;
  20. data['total'] = rows.length;
  21. res.writeHead(200, {'Content-Type': 'application/json'});
  22. res.end(JSON.stringify(data));
  23. });
  24. } else if (/^\/api\/ladder\/[0-9]+$/.test(req.url)) {
  25. // Returns top X users from the ladder
  26. sql = 'SELECT * FROM viewers ORDER BY points DESC LIMIT '+req.url.match(/\d+/g)+';';
  27. __self.db.execute(sql, function(rows) {
  28. var data = new Object();
  29. data['viewers'] = rows;
  30. data['total'] = rows.length;
  31. res.writeHead(200, {'Content-Type': 'application/json'});
  32. res.end(JSON.stringify(data));
  33. });
  34. } else if (req.url == "/api/bet") {
  35. // Returns all of the bet data together
  36. data = new Object();
  37. data['status'] = __self.currency.bets_status;
  38. data['board'] = __self.currency.bets_board;
  39. data['viewers'] = __self.currency.bets_viewers;
  40. data['total_viewers'] = __self.currency.bets_viewers.length;
  41. res.writeHead(200, {'Content-Type': 'application/json'});
  42. res.end(JSON.stringify(data));
  43. } else if (req.url == "/api/bet/status") {
  44. res.writeHead(200, {'Content-Type': 'application/json'});
  45. res.end(JSON.stringify(__self.currency.bets_status));
  46. } else if (req.url == "/api/bet/board") {
  47. res.writeHead(200, {'Content-Type': 'application/json'});
  48. res.end(JSON.stringify(__self.currency.bets_board));
  49. } else if (req.url == "/api/bet/viewers") {
  50. res.writeHead(200, {'Content-Type': 'application/json'});
  51. res.end(JSON.stringify(__self.currency.bets_viewers));
  52. } else {
  53. res.writeHead(404, {'Content-Type': 'application/json'});
  54. res.end("404");
  55. }
  56. }
  57. });
  58. __self.srv.listen(__self.port, '0.0.0.0');
  59. console.log('Serving api data at '+__self.port);
  60. };
  61. module.exports = function (db, currency, options) {
  62. return new API(db, currency, options);
  63. };