optional type specification

This commit is contained in:
2022-05-26 20:55:12 -05:00
parent 61fd30003d
commit 61b8924122
3 changed files with 37 additions and 20 deletions

View File

@@ -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<guild id, stringified data> */
@@ -10,7 +10,7 @@ const GuildCache = new Map<string, string>()
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))
}
}

View File

@@ -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 = JSONObject>(): T {
let val
getJson<T = JSONObject>(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
}
}

View File

@@ -3,10 +3,25 @@ export type JSONObject<Value = JSONDataTypes, Key extends string = string> = {
[key in Key]: Value
}
export function defaultJson(
export function defaultJson<T>(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) {