import fs from 'fs' ; import { NotFoundError } from '@sqltools/util/exception' ; export default class SerializableStorage < Item , Key = string | number | Symbol > { public encoding : BufferEncoding = 'utf8' ; public storagePath : string = null ; protected defaultSerializable : string = '{}' ; protected items : any = { } ; constructor ( storagePath , defaultSerializable = { } ) { this . defaultSerializable = JSON . stringify ( defaultSerializable ) ; this . storagePath = storagePath ; this . items = defaultSerializable ; this . read ( ) ; } public read ( ) { try { const content = fs . readFileSync ( this . storagePath , { encoding : this . encoding } ) ; if ( content && content . length > 0 ) { this . items = JSON . parse ( content ) ; } else { this . reset ( ) . save ( ) ; } } catch ( e ) { this . reset ( ) . save ( ) ; } return this ; } private serializeContent ( ) { return new Buffer ( JSON . stringify ( this . items , null , 2 ) , 'utf8' ) ; } public save ( ) { return this . write ( ) ; } private write ( ) { fs . writeFileSync ( this . storagePath , this . serializeContent ( ) ) ; return this ; } public reset ( ) { this . items = JSON . parse ( this . defaultSerializable ) ; return this ; } public set ( key , query ) { this . items [ key ] = query ; return this . save ( ) ; } public get ( key ) { if ( ! this . items [ key ] ) { throw new NotFoundError ( 'Query not found!' ) ; } return this . items [ key ] ; } public delete ( key ) { this . get ( key ) ; delete this . items [ key ] ; return this . save ( ) ; } public content ( content ) { this . items = content ; return this ; } public getContent ( ) { return this . items ; } }