import { inject , injectable } from "inversify" ; import { TYPES } from "../../utils/constants" ; import { FsProxy } from "../../moduleproxies/fs-proxy" ; import { PathProxy } from "../../moduleproxies/path-proxy" ; @ injectable ( ) export class FileTokenStorage { private filename : string ; private fs : FsProxy ; private path : PathProxy ; constructor ( @ inject ( TYPES . FsProxy ) fs , @ inject ( TYPES . FsProxy ) path ) { this . fs = fs ; this . path = path ; } public setFilename ( filename ) { this . filename = filename ; } public addEntries ( newEntries , existingEntries ) { const entries = existingEntries . concat ( newEntries ) ; return this . saveEntries ( entries ) ; } public clear ( ) { return this . saveEntries ( [ ] ) ; } public loadEntries ( ) { return this . tryLoadEntries ( ) ; } private async tryLoadEntries ( ) { try { const content = await this . fs . readFileAsync ( this . filename , { encoding : "utf8" , flag : "r" } ) ; return JSON . parse ( content ) ; } catch ( ex ) { if ( ex . code !== "ENOENT" ) { throw new Error ( ex ) ; } return [ ] ; } } public keepEntries ( entriesToKeep ) { return this . saveEntries ( entriesToKeep ) ; } private async saveEntries ( entries ) { const RW_GRANT_FOR_OWNER_ONLY = 384 ; await this . createFolderIfNotExist ( ) ; return this . fs . writeFileAsync ( this . filename , JSON . stringify ( entries ) , { encoding : "utf8" , mode : RW_GRANT_FOR_OWNER_ONLY , flag : "w" } ) ; } private async createFolderIfNotExist ( ) { const folder = this . path . dirname ( this . filename ) ; const isFolderExist = await this . fs . existsAsync ( folder ) ; if ( ! isFolderExist ) { await this . fs . mkdirAsync ( folder ) ; } } }