Skip to content

Instantly share code, notes, and snippets.

@lightningspirit
Created April 29, 2022 16:54
Show Gist options
  • Save lightningspirit/68917ced12f08af23a015af779f3fc57 to your computer and use it in GitHub Desktop.
Save lightningspirit/68917ced12f08af23a015af779f3fc57 to your computer and use it in GitHub Desktop.
ContentDB - A tiny JS cache-in-disk database for embeddable systems
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