import { Level } from "level"; export interface KeyProfile { ip: string; keys: string[]; limit: 1; admin: boolean; [key: string]: any; } export class Data { public static db = new Level('./keys.db'); public static async addKey(ip: string, key: string) { let prof: KeyProfile | undefined = undefined; while (!prof) { try { prof = JSON.parse(await this.db.get(ip)); } catch (err) { this.insertKeyProfile(ip); } } // while (prof.keys.length >= prof.limit) { // prof.keys.pop(); // } if (prof.keys.length >= prof.limit) { throw `too many keys`; } prof.keys.push(key); await this.saveKeyProfile(prof); return (await this.getKeyProfile(ip)).keys; } public static async getKeyProfile(ip: string): Promise { return JSON.parse(await this.db.get(ip)); } public static async insertKeyProfile(ip: string, defaultKeys?: string[]) { return await this.db.put(ip, JSON.stringify({ ip: ip, keys: defaultKeys || [], limit: 1, admin: false})); } public static async saveKeyProfile(profile: KeyProfile) { return await this.db.put(profile.ip, JSON.stringify(profile)); } public static async setProfileValue(prof: KeyProfile, key: string, value: any) { prof[key] = value; try { await this.saveKeyProfile(prof); return true; } catch (err) { return false; } } public static async deleteKeyProfile(ip: string) { await this.db.del(ip); } public static async resetKeyProfile(ip: string) { try { await this.deleteKeyProfile(ip); await this.insertKeyProfile(ip); return true; } catch (err) { return false } } }