This repository has been archived by the owner on Sep 11, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
68 lines (55 loc) · 1.74 KB
/
index.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
const path = require('path').resolve()
const dataRoot = path + '/extensions/CodeQuiz/data/'
// if database is not connected, use this object
const fallback = {}
class CodeQuiz {
/**
* @param {import('../../classes/SeoaClient')} seoa
*/
constructor (seoa) {
this.client = seoa
/**
* @typedef {{language: string, question: string, explanation: string, answer: boolean, point: number, image?: string}} quiz
* @type {quiz[]}
*/
this.quizData = require(dataRoot + 'quizs.json')
}
getQuiz (id = Math.floor(Math.random() * this.quizData.length)) {
return { ...this.quizData[id], id }
}
async getScore (id) {
let dbData
try {
dbData = await this.client.db('user').select('score', 'solve').where('id', id)
} catch (err) { console.error(err.stack); return fallback[id] || 0 }
if (dbData.length < 1) return 0
else return dbData[0]
}
async getLeaderboard () {
return await this.client.db('user').select('*').orderBy('score', 'desc').limit(31)
}
async addScore (n, id) {
let dbData
try {
dbData = await this.client.db('user').select('score', 'solved').where('id', id)
} catch (err) {
console.error(err.stack)
if (!fallback[id]) fallback[id] = {}
dbData = [fallback[id]]
}
if (dbData.length < 1) {
try {
await this.client.db('user').insert({ id, score: 0, solved: 0 })
} catch (err) { console.error(err.stack) }
dbData[0].score = 0
dbData[0].solved = 0
}
const score = dbData[0].score + n
const solved = dbData[0].solved + 1
try {
await this.client.db('user').update({ score, solved }).where('id', id)
} catch (err) { console.error(err.stack) }
return score
}
}
module.exports = CodeQuiz