StorageBase

This commit is contained in:
2022-05-26 18:49:49 -05:00
commit 94126fe5f9
12 changed files with 666 additions and 0 deletions

52
src/main.ts Normal file
View File

@@ -0,0 +1,52 @@
/*
initGlobalStorage()
initChannelStorage(channel/channels)
channelStorage(channel) => Storage
Storage {
get() => string
set(string | json)
getJson() => json
}
*/
import { JSONObject } from './util'
class StorageBase {
val: string
fallbackJSON: JSONObject
constructor(val: string | JSONObject, fallbackJSON?: JSONObject) {
if (typeof val !== 'string') {
val = JSON.stringify(val)
}
if (fallbackJSON === undefined) {
fallbackJSON = val.constructor() as JSONObject
}
this.val = val
this.fallbackJSON = fallbackJSON
}
set(val: string | JSONObject) {
if (typeof val !== 'string') {
val = JSON.stringify(val)
}
this.val = val
}
get(): string {
return this.val
}
getJson(): JSONObject {
let val
try {
val = JSON.parse(this.val)
} catch (e) {
val = {}
}
return val
}
}

4
src/util.ts Normal file
View File

@@ -0,0 +1,4 @@
export type JSONDataTypes = string | number | boolean
export type JSONObject<Value = JSONDataTypes, Key extends string = string> = {
[key in Key]: Value
}