@@ -22,36 +22,53 @@ class Storage<T> {
2222 if ( value ) {
2323 return JSON . parse ( value )
2424 } else if ( SESSION_FILE_PATH ) {
25- // optionally read from file as a fallback to localstorage
26- const sessionFile = await readFile ( SESSION_FILE_PATH )
2725 try {
26+ // optionally read from file as a fallback to local storage
27+ const sessionFile = await readFile ( SESSION_FILE_PATH )
28+ if ( ! sessionFile ) {
29+ throw new Error ( 'No session file found' )
30+ }
2831 const session = JSON . parse ( sessionFile )
29- if ( session && session [ this . key ] ) {
30- // TODO: validate session
31- return session [ this . key ]
32+
33+ if ( session ) {
34+ const keys = Object . keys ( session )
35+ // validate session
36+ if ( keys . length ) {
37+ // should only be one
38+ this . key = keys [ 0 ]
39+ return session [ this . key ]
40+ }
3241 }
3342 } catch ( err ) {
34- console . error ( `Failed to parse session file: ${ SESSION_FILE_PATH } ` )
43+ console . warn ( `Failed to read or parse session file: ${ SESSION_FILE_PATH } ` )
3544 }
3645 }
3746 return this . defaultValue
3847 }
3948 public set = ( value : T ) : void => {
4049 const stringValue = JSON . stringify ( value )
4150 this . storage . update ( this . key , stringValue )
51+ this . writeToSessionFile ( stringValue )
4252 }
4353 public update = async ( value : T ) : Promise < void > => {
4454 const current = await this . get ( )
4555 const next = JSON . stringify ( {
4656 ...current ,
4757 ...value ,
4858 } )
49- this . storage . update ( this . key , next ) . then ( ( ) => {
50- // optionally write to file
51- if ( SESSION_FILE_PATH ) {
52- writeFile ( this . storage , SESSION_FILE_PATH )
59+ await this . storage . update ( this . key , next )
60+
61+ this . writeToSessionFile ( next )
62+ }
63+ public writeToSessionFile ( data : string ) {
64+ // optionally write to file
65+ if ( SESSION_FILE_PATH ) {
66+ try {
67+ writeFile ( { [ this . key ] : data } , SESSION_FILE_PATH )
68+ } catch ( err : any ) {
69+ console . warn ( `Failed to write coderoad session to path: ${ SESSION_FILE_PATH } ` )
5370 }
54- } )
71+ }
5572 }
5673 public reset = ( ) => {
5774 this . set ( this . defaultValue )
0 commit comments