MusicServer/database.ts

68 lines
2.2 KiB
TypeScript

import fs from 'fs';
function createTableIfNotExists(table: string) {
if (!fs.existsSync(`./data/${table}/`)) fs.mkdirSync(`./data/${table}/`);
}
function dbRead(table: string, key: string) {
createTableIfNotExists(table);
if (fs.existsSync(`./data/${table}/${key}`)) return JSON.parse(fs.readFileSync(`./data/${table}/${key}`, 'utf-8'));
if (!fs.existsSync(`./data/${table}/${encodeURIComponent(key)}`)) return null;
return JSON.parse(fs.readFileSync(`./data/${table}/${encodeURIComponent(key)}`, 'utf-8'));
}
function dbExists(table: string, key: string) {
createTableIfNotExists(table);
if (fs.existsSync(`./data/${table}/${key}`)) return true;
if (!fs.existsSync(`./data/${table}/${encodeURIComponent(key)}`)) return null;
return true;
}
function dbStore(table: string, key: string, value: any) {
createTableIfNotExists(table);
fs.writeFileSync(`./data/${table}/${encodeURIComponent(key)}`, JSON.stringify(value));
}
function dbDelete(table: string, key: string) {
createTableIfNotExists(table);
fs.rmSync(`./data/${table}/${encodeURIComponent(key)}`);
}
function dbSearch(table: string, condition: (v: any) => boolean) {
createTableIfNotExists(table);
const values: Record<string, any> = {};
for (const key of fs.readdirSync('./data/' + table + '/')) {
const value = dbRead(table, decodeURIComponent(key));
if (condition(value)) values[decodeURIComponent(key)] = value;
}
return values;
}
function dbAll(table: string) {
createTableIfNotExists(table);
const values: Record<string, any> = {};
for (const key of fs.readdirSync('./data/' + table + '/')) {
const value = dbRead(table, decodeURIComponent(key));
values[decodeURIComponent(key)] = value;
}
return values;
}
function dbFind(table: string, condition: (v: any) => boolean) {
createTableIfNotExists(table);
for (const key of fs.readdirSync('./data/' + table + '/')) {
const value = dbRead(table, decodeURIComponent(key));
if (condition(value)) return { key: decodeURIComponent(key), value };
}
return null;
}
export {
dbAll,
dbDelete,
dbExists,
dbFind,
dbRead,
dbSearch,
dbStore
};