Skip to content

Instantly share code, notes, and snippets.

@acidjazz
Created March 19, 2023 00:36
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 acidjazz/d26fad865d719e0f60214dcc4a5db109 to your computer and use it in GitHub Desktop.
Save acidjazz/d26fad865d719e0f60214dcc4a5db109 to your computer and use it in GitHub Desktop.
simple text string storage in ts
import fs from 'node:fs'
interface StoreInterface {
uuid: string
text: string
expires: Date
}
export default class Store {
private store: StoreInterface[]
constructor() {
this.store = this.load()
return this
}
private static current = (entry: StoreInterface): boolean => new Date(entry.expires) > new Date()
private load(): StoreInterface[] {
if (!fs.existsSync('/tmp/store.json')) return []
return JSON.parse(fs.readFileSync('/tmp/store.json', 'utf-8')) as StoreInterface[]
}
add(uuid: string, text: string) {
this.store.push({ uuid, text, expires: new Date(Date.now() + 4 * 60 * 60 * 1000) })
this.save()
}
get(uuid: string): StoreInterface | undefined {
return this.store.filter(Store.current).find(entry => entry.uuid === uuid)
}
save() {
fs.writeFileSync('/tmp/store.json', JSON.stringify(this.store.filter(Store.current)), 'utf-8')
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment