Created
January 5, 2022 12:49
-
-
Save ambrizals/337bc19c8d76c40c1ae435c96cf47644 to your computer and use it in GitHub Desktop.
Create like some cache function with JSON file.
This file contains 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 Application from '@ioc:Adonis/Core/Application' | |
import fs from 'fs' | |
export default class CacheService { | |
private jsonPath: string | |
public static initialize(key: string): CacheService { | |
const instance = new CacheService() | |
instance.jsonPath = `${Application.tmpPath('cache')}/${key}.json` | |
return instance | |
} | |
private checkCacheExists() { | |
if (!fs.existsSync(Application.tmpPath('cache'))) { | |
fs.mkdirSync(Application.tmpPath('cache')) | |
} | |
return fs.existsSync(this.jsonPath) | |
} | |
public async get() { | |
if (this.checkCacheExists()) { | |
const data = fs.readFileSync(this.jsonPath, 'utf8') | |
return JSON.parse(data) | |
} else { | |
return null | |
} | |
} | |
public async put(payload: any) { | |
fs.writeFileSync(this.jsonPath, JSON.stringify(payload)) | |
return payload | |
} | |
public async flush() { | |
fs.rmSync(this.jsonPath) | |
return true | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment