Skip to content

Instantly share code, notes, and snippets.

@ambrizals
Created January 5, 2022 12:49
Show Gist options
  • Save ambrizals/337bc19c8d76c40c1ae435c96cf47644 to your computer and use it in GitHub Desktop.
Save ambrizals/337bc19c8d76c40c1ae435c96cf47644 to your computer and use it in GitHub Desktop.
Create like some cache function with JSON file.
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