Created
April 29, 2022 16:54
-
-
Save lightningspirit/68917ced12f08af23a015af779f3fc57 to your computer and use it in GitHub Desktop.
ContentDB - A tiny JS cache-in-disk database for embeddable systems
This file contains hidden or 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 { promises as fs } from "fs" | |
import path from "path" | |
export interface NodeItem { | |
id: string | |
data: any | |
} | |
const cache: NodeItem[] = [] | |
const contentdb = { | |
list: async () => { | |
return cache | |
}, | |
get: async (id: NodeItem["id"]) => { | |
const node = cache.find((node) => node.id === id)?.data | |
if (!node) { | |
try { | |
const data = await fs.readFile(path.join(process.cwd(), "content.db")) | |
;(JSON.parse(data as unknown as string) as NodeItem[])?.forEach( | |
(node) => cache.push(node), | |
) | |
return cache.find((node) => node.id === id)?.data | |
} catch (err) { | |
console.warn(`Warn: content.db not present`) | |
} | |
} | |
}, | |
set: async (node: NodeItem) => { | |
return cache.push(node) | |
}, | |
save: async () => { | |
return fs.writeFile( | |
path.join(process.cwd(), "content.db"), | |
JSON.stringify(cache), | |
) | |
}, | |
} | |
export default contentdb |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment