From: Ben Beltran Date: Mon, 28 Nov 2016 08:27:19 +0000 (-0600) Subject: Fetch random record in record_fetcher X-Git-Url: https://git.r.bdr.sh/rbdr/lgtm/commitdiff_plain/a2a2b553f69a66f1825347abde4f0028773bdbdb?ds=inline Fetch random record in record_fetcher --- diff --git a/lib/record_fetcher.js b/lib/record_fetcher.js index 5bc4caf..a506fe7 100644 --- a/lib/record_fetcher.js +++ b/lib/record_fetcher.js @@ -1,16 +1,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 Promise.resolve({ - looks: 'Looks', - good: 'Good', - to: 'To', - me: 'Me', - emoji: '👍' + 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 + }); + }); }); } };