Skip to content

Instantly share code, notes, and snippets.

@rm-rf-etc
Last active March 30, 2020 08:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rm-rf-etc/26dce8c9dc4e93ffe157a52b54ed6553 to your computer and use it in GitHub Desktop.
Save rm-rf-etc/26dce8c9dc4e93ffe157a52b54ed6553 to your computer and use it in GitHub Desktop.
Database-to-JSON Adapter
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