import lowdb from 'lowdb' ; import lodashId from 'lodash-id' ; import FileSync from 'lowdb/adapters/FileSync' ; import json from 'comment-json' ; import { IConfig , IPicGo } from '../types' ; class DB { private readonly ctx : IPicGo ; private readonly db : lowdb . LowdbSync < any > ; constructor ( ctx ) { this . ctx = ctx ; const adapter = new FileSync ( this . ctx . configPath , { serialize ( obj ) { return json . stringify ( obj , null , 2 ) ; } , deserialize : json . parse } ) ; this . db = lowdb ( adapter ) ; this . db . _ . mixin ( lodashId ) ; if ( ! this . db . has ( 'picBed' ) . value ( ) ) { try { this . db . set ( 'picBed' , { uploader : 'smms' , current : 'smms' } ) . write ( ) ; } catch ( e ) { this . ctx . log . error ( e ) ; throw e ; } } if ( ! this . db . has ( 'picgoPlugins' ) . value ( ) ) { try { this . db . set ( 'picgoPlugins' , { } ) . write ( ) ; } catch ( e ) { this . ctx . log . error ( e ) ; throw e ; } } } read ( ) { return this . db . read ( ) ; } get ( key = '' ) { return this . read ( ) . get ( key ) . value ( ) ; } set ( key , value ) { return this . read ( ) . set ( key , value ) . write ( ) ; } has ( key ) { return this . read ( ) . has ( key ) . value ( ) ; } insert ( key , value ) { return this . read ( ) . get ( key ) . insert ( value ) . write ( ) ; } unset ( key , value ) { return this . read ( ) . get ( key ) . unset ( value ) . write ( ) ; } saveConfig ( config ) { Object . keys ( config ) . forEach ( ( name ) => { this . set ( name , config [ name ] ) ; } ) ; } removeConfig ( config ) { Object . keys ( config ) . forEach ( ( name ) => { this . unset ( name , config [ name ] ) ; } ) ; } } export default DB ;