space-smasher-9001/server/Database.js

98 lines
2.1 KiB
JavaScript
Raw Permalink Normal View History

2021-10-17 20:55:00 +02:00
import { join, dirname } from 'path'
import { Low, JSONFile } from 'lowdb'
import { fileURLToPath } from 'url'
const __dirname = dirname(fileURLToPath(import.meta.url));
class Database {
constructor() {
const file = join(__dirname, 'storage', 'db.json')
const adapter = new JSONFile(file)
this.db = new Low(adapter)
}
async read() {
await this.db.read();
this.db.data = this.db.data || {
2021-10-17 23:00:29 +02:00
users: []
2021-10-17 20:55:00 +02:00
}
}
userExists(name) {
return this.db.data.users.find(user => user.name == name) !== undefined
}
async addUser(user) {
this.db.data.users.push(user)
await this.db.write()
return user
}
2021-10-17 21:12:42 +02:00
2021-10-18 02:33:29 +02:00
getUserByName(username) {
return this.db.data.users.find(user => user.name === username)
}
2021-10-17 21:12:42 +02:00
getUserByPassword(password) {
return this.db.data.users.find(user => user.password === password)
}
2021-10-17 23:00:29 +02:00
async updateRecord(username, record) {
const user = this.db.data.users.find(user => user.name == username)
if (record > user.record) {
user.record = record
await this.db.write()
}
}
2021-10-17 23:55:58 +02:00
getTop(amount = 15) {
return this.db.data.users
.filter(user => user.record)
.map(user => { return { name: user.name, record: user.record } })
.sort((a, b) => a.record > b.record ? -1 : 1)
.slice(0, amount)
}
2021-10-18 00:44:02 +02:00
getRank(username) {
const users = this.db.data.users
.filter(user => user.record)
.sort((a, b) => a.record > b.record ? -1 : 1)
for (let i = 0; i < users.length; ++i) {
if (users[i].name == username)
return i + 1
}
return 0
}
2021-10-18 01:53:50 +02:00
foreseeRank(record) {
const users = this.db.data.users
.filter(user => user.record)
.sort((a, b) => a.record > b.record ? -1 : 1)
for (let i = 0; i < users.length; ++i) {
if (users[i].record < record)
return i + 1
}
return 0
}
2021-10-18 02:33:29 +02:00
getLastPlayed(username) {
const user = this.getUserByName(username)
return user.lastPlayed
}
async setLastPlayedToNow(username) {
const user = this.getUserByName(username)
user.lastPlayed = Date.now()
await this.db.write()
return user.lastPlayed
}
2021-10-17 20:55:00 +02:00
}
export default new Database