Last active
March 30, 2020 08:53
-
-
Save rm-rf-etc/26dce8c9dc4e93ffe157a52b54ed6553 to your computer and use it in GitHub Desktop.
Database-to-JSON Adapter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { sha256 } from "sha.js"; | |
type Data = { | |
[k: string]: { | |
[k: string]: string | number | boolean, | |
} | |
}; | |
const data: Data = {}; | |
const getRealId = (id: string) => `<${id.replace(/^<|>$/g, "")}>`; | |
export const dump = () => data; | |
export const set = (id: string, obj: { [k: string]: any }) => { | |
const realId = getRealId(id); | |
data[realId] = data[realId] || {}; | |
Object.keys(obj).forEach((key) => { | |
if (typeof obj[key] !== "object") { | |
data[realId][key] = obj[key]; | |
} else { | |
const newKey = new sha256().update(`${id}:${key}`).digest("hex"); | |
data[realId][key] = `<${newKey}>`; | |
set(newKey, obj[key]); | |
} | |
}) | |
}; | |
export const get = (id: string): { [k: string]: any } => { | |
const realId = getRealId(id); | |
if (data.hasOwnProperty(realId)) { | |
const result = Object.assign({}, data[realId]) as { [k: string]: any }; | |
Object.keys(result).forEach((key) => { | |
if (typeof result[key] === "string" && /^<[\w\d]+>$/.test(result[key] as string)) { | |
result[key] = get(result[key]); | |
} | |
}); | |
return result; | |
} | |
else { | |
return {}; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment