aboutsummaryrefslogtreecommitdiff
path: root/lib/record_fetcher.js
blob: a506fe7a9d1a84fa3a0ee5d10d59c464fcd72f97 (plain)
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
'use strict';

const Config = require('../config/config');
const Mysql = require('mysql2');

const internals = {};

module.exports = internals.Record = class {

  constructor() {

    this.connection = Mysql.createConnection(Config.mysql);
  }

  fetch() {

    return new Promise((resolve, reject) => {
      this.connection.query(`SELECT * FROM ${Config.mysql.tableName} ORDER BY RAND() LIMIT 1`, (err, results) => {

        if (err) {
          console.error('Error while fetching row');
          console.error(err.message);
          return reject(err);
        }

        if (results.length === 0) {
          const error = new Error('No rows found.');
          console.error('Error while fetching row');
          console.error(error.message);
          return reject(err);
        }

        const row = results[0];

        return resolve({
          looks: row.l,
          good: row.g,
          to: row.t,
          me: row.m,
          emoji: row.emoji
        });
      });
    });
  }
};