diff --git a/src/storage.ts b/src/storage.ts index a07bce6..0aa863f 100644 --- a/src/storage.ts +++ b/src/storage.ts @@ -1,7 +1,7 @@ import { Guild } from 'discord.js' import { readFile, writeFile } from './fs' import { GlobalStorage, GuildStorage } from './storageclass' -import { defaultJson, JSONObject } from './util' +import { defaultJsonString, JSONObject } from './util' var GlobalCache = '' /** Map */ @@ -10,7 +10,7 @@ const GuildCache = new Map() export function initGlobalCache(defaultValue?: string | JSONObject) { if (GlobalCache.length === 0) { let data = readFile('global') - GlobalCache = defaultJson(data, defaultValue) + GlobalCache = defaultJsonString(data, defaultValue) } } @@ -20,7 +20,7 @@ export function initGuildCache( ) { if (!GuildCache.has(guild.id)) { let data = readFile(guild) - GuildCache.set(guild.id, defaultJson(data, defaultValue)) + GuildCache.set(guild.id, defaultJsonString(data, defaultValue)) } } diff --git a/src/storageclass.ts b/src/storageclass.ts index 580ac05..4a198cc 100644 --- a/src/storageclass.ts +++ b/src/storageclass.ts @@ -1,4 +1,4 @@ -import { JSONObject } from './util' +import { defaultJson, JSONObject } from './util' import { Guild } from 'discord.js' export interface StorageValue { @@ -23,14 +23,24 @@ export class StorageBase { return this.val.get() } - getJson(): T { - let val + getJson(defaultValue?: T): T | {} { try { - val = JSON.parse(this.val.get()) + + let val = JSON.parse(this.val.get()) + if (defaultValue) { + val = defaultJson(val, defaultValue) + } + return val; + } catch (e) { - val = {} + + if (defaultValue) { + return defaultValue + } + + return {} + } - return val } } diff --git a/src/util.ts b/src/util.ts index 3557d30..43d014b 100644 --- a/src/util.ts +++ b/src/util.ts @@ -3,10 +3,25 @@ export type JSONObject = { [key in Key]: Value } -export function defaultJson( +export function defaultJson(data: any, defaultValue: T): T { + if (typeof data !== 'object') { + return defaultValue + } + + for (let key in defaultValue) { + if (!(key in data) || typeof data[key] !== typeof defaultValue[key]) { + //key doesnt exist OR key exists, but type is incorrect + data[key] = defaultValue[key] + } + } + + return data as T +} + +export function defaultJsonString( data: string, defaultValue: string | JSONObject = '' -) { +): string { if (data.length === 0) { //no existing data, give the default value instead @@ -22,15 +37,7 @@ export function defaultJson( try { let foundJson = JSON.parse(data) - for (let key in defaultValue) { - if ( - !(key in foundJson) || - typeof foundJson[key] !== typeof defaultValue[key] - ) { - //key doesnt exist OR key exists, but type is incorrect - foundJson[key] = defaultValue[key] - } - } + foundJson = defaultJson(foundJson, defaultValue) return JSON.stringify(foundJson) } catch (e) {