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.

80 lines
2.5 KiB

12 years ago
  1. /**
  2. * api:
  3. * DB([required options])
  4. * required options - {host, user, password, database}
  5. *
  6. * example:
  7. * var db = require('./lib/plugins/db.js')({
  8. * host : 'localhost',
  9. * user : 'user',
  10. * password : 'password',
  11. * database : 'database',
  12. * });
  13. */
  14. var mysql = require('mysql'),
  15. file = require('fs');
  16. //-------- Construct ---------
  17. function DB(options) {
  18. var __self = this;
  19. // config
  20. __self.host = options.host || '';
  21. __self.user = options.user || '';
  22. __self.password = options.password || '';
  23. __self.database = options.database || '';
  24. }
  25. //-------- Methods ---------
  26. DB.prototype.start = function() {
  27. var __self = this, commands ='', viewers = '';
  28. // table structure for table commands
  29. commands += 'CREATE TABLE IF NOT EXISTS `commands` (';
  30. commands += '`id` int(11) NOT NULL AUTO_INCREMENT,';
  31. commands += '`command` text COLLATE utf8_unicode_ci NOT NULL,';
  32. commands += '`text` longtext COLLATE utf8_unicode_ci NOT NULL,';
  33. commands += '`auth` int(11) NOT NULL DEFAULT \'1\',';
  34. commands += 'PRIMARY KEY (`id`)';
  35. commands += ') ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1';
  36. // table structure for table viewers
  37. viewers += 'CREATE TABLE IF NOT EXISTS `viewers` (';
  38. viewers += '`user` varchar(64) COLLATE utf8_unicode_ci NOT NULL,';
  39. viewers += '`points` int(11) NOT NULL,';
  40. viewers += 'PRIMARY KEY (`user`)';
  41. viewers += ') ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;';
  42. // execute sql, create tables if they don't exist
  43. __self.execute(commands + '; ' + viewers, function(){});
  44. };
  45. DB.prototype.execute = function(sql, callback) {
  46. var __self = this,
  47. connection = mysql.createConnection({
  48. host : __self.host,
  49. user : __self.user,
  50. password : __self.password,
  51. database : __self.database,
  52. multipleStatements : true
  53. });
  54. // execute query
  55. connection.query(sql, function (err, rows, fields) {
  56. // error handling
  57. if (err) {
  58. file.appendFile('./../logs/error-log.txt', err.message + '\r\n' + err.stack + '\r\n', function() {});
  59. return;
  60. }
  61. // close connection
  62. connection.end();
  63. // return results
  64. callback(rows, fields);
  65. });
  66. };
  67. module.exports = function (options) {
  68. return new DB(options);
  69. };