/
scoring.js
71 lines (62 loc) · 1.9 KB
/
scoring.js
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
const Database = require('better-sqlite3');
const config = require('./config').getConfig();
const db = new Database(config.ScoreDatabase);
db.pragma('journal_mode = WAL');
/**
* Runs the schema creation commands;
*
* @param {Database} db the datbase.
*/
function createSchema(db) {
db.prepare('CREATE TABLE IF NOT EXISTS scoring (timestamp INT NULL, message TEXT NULL, author TEXT NULL, phrase TEXT NOT NULL, score NUMBER NOT NULL);').run();
db.prepare('CREATE INDEX IF NOT EXISTS IX_scoring_phrase ON scoring(phrase COLLATE NOCASE);').run();
}
/**
* Get the score for a phrase.
*
* @param {string} phrase the phrase.
* @param {function(int)} callback A function that has the total as a parameter.
*
* @returns {Number} the total score for the phrase.
*/
function getScore(phrase, callback) {
createSchema(db);
const selectStmt = db.prepare('SELECT COALESCE(SUM(score), 0) as total FROM scoring WHERE phrase = ? COLLATE NOCASE;');
const row = selectStmt.get(phrase);
if (callback != null) {
callback(row.total);
}
return row.total;
}
/**
* Processes scoring in messages
*
* @param {{ content: string; author: any }} message
* @return {Promise<void>}
*/
function processScores(message) {
const lines = message.content.split(/[\r\n]+/);
lines.map(line => {
let score = 0;
if (line.endsWith('++'))
{
score = 1;
}
else if (line.endsWith('--'))
{
score = -1;
}
else
{
return;
}
const phrase = line.replace(/\W*[+-]$/, '');
createSchema(db);
const insertStmt = db.prepare('INSERT INTO scoring (timestamp, message, author, phrase, score) VALUES (?, ?, ?, ?, ?)');
insertStmt.run(Date.now(), message.content, message.author?.toString(), phrase, score);
});
}
module.exports = {
getScore,
processScores
};