Counters-API/src/utils/database/json.ts
2022-08-14 14:20:53 -06:00

73 lines
No EOL
2 KiB
TypeScript

import { databaseOptions } from "$/types/config";
import { DatabaseHandler } from "../Database";
import fs from "fs";
export class JSONDatabase extends DatabaseHandler {
private data: any = {};
private conf: databaseOptions;
constructor(conf: databaseOptions) {
super();
this.conf = conf;
if (!fs.existsSync(conf.uri)) {
console.error(`Can't find database file, creating default`);
try {
fs.writeFileSync(conf.uri, `{}`);
} catch (_) {
console.log(`Couldn't create database file, ensure the uri is a valid filepath`);
};
};
this.data = JSON.parse(fs.readFileSync(conf.uri, `utf-8`));
};
public shutdown() {
fs.writeFileSync(this.conf.uri, JSON.stringify(this.data));
};
public async channelExists(channel: string) {
return this.data[channel] != null;
};
public async counterExists(channel: string, counter: string) {
return await this.channelExists(channel) && this.data[channel].counters[counter] != null;
};
public async isUserIgnored(channel: string, user: string) {
return this.data[channel].ignored_users.includes(user);
};
public async getMessage(channel: string, counter: string) {
return this.data[channel].counters[counter].message;
};
public async addChannel(channel: string) {
if (await this.channelExists(channel)) {
throw new Error("Channel already exists");
};
this.data[channel] = {
ignored_users: [],
counters: {}
};
};
public async addCounter(channel: string, counter: string) {
if (await this.counterExists(channel, counter)) {
throw new Error(`Counter already exists`);
};
this.data[channel].counters[counter] = {
value: 0,
message: `$(value)`,
};
};
public async changeCount(channel: string, counter: string, delta: number) {
if (!await this.channelExists(channel)) {
throw new Error("Channel not found");
};
if (!await this.counterExists(channel, counter)) {
throw new Error("Counter doesn't exist on that channel");
};
return this.data[channel].counters[counter].value += delta;
};
};