generated from djyde/nextjs-saas-starter
-
Notifications
You must be signed in to change notification settings - Fork 14
/
cache.ts
40 lines (35 loc) · 955 Bytes
/
cache.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import { Low, JSONFile, JSONFileSync } from "lowdb";
import path from 'path'
import fs from 'fs'
export class Cache {
private cachePath = path.join(process.cwd(), 'cache.json')
private adapter = new JSONFile(this.cachePath)
private db = new Low(this.adapter)
constructor(private cacheName: string) {
}
async prepare() {
await this.db.read()
this.db.data = this.db.data || {}
await this.db.write()
}
async get(key: string) {
await this.prepare()
await this.db.read()
if (!this.db.data[this.cacheName]) {
return null
}
return this.db.data[this.cacheName][key];
}
async set(key: string, value: any) {
await this.prepare()
await this.db.read()
if (!this.db.data[this.cacheName]) {
this.db.data[this.cacheName] = {}
await this.db.write()
console.log('write')
}
await this.db.read()
this.db.data[this.cacheName][key] = value
await this.db.write()
}
}