@@ -8,25 +8,38 @@ import { Memento } from 'vscode';
88import { GLOBAL_MEMENTO , IMemento , IPersistentState , IPersistentStateFactory , WORKSPACE_MEMENTO } from './types' ;
99
1010class PersistentState < T > implements IPersistentState < T > {
11- constructor ( private storage : Memento , private key : string , private defaultValue : T ) { }
11+ constructor ( private storage : Memento , private key : string , private defaultValue ? : T , private expiryDurationMs ?: number ) { }
1212
1313 public get value ( ) : T {
14- return this . storage . get < T > ( this . key , this . defaultValue ) ;
14+ if ( this . expiryDurationMs ) {
15+ const cachedData = this . storage . get < { data ?: T ; expiry ?: number } > ( this . key , { data : this . defaultValue ! } ) ;
16+ if ( ! cachedData || ! cachedData . expiry || cachedData . expiry < Date . now ( ) ) {
17+ return this . defaultValue ! ;
18+ } else {
19+ return cachedData . data ! ;
20+ }
21+ } else {
22+ return this . storage . get < T > ( this . key , this . defaultValue ! ) ;
23+ }
1524 }
1625
1726 public async updateValue ( newValue : T ) : Promise < void > {
18- await this . storage . update ( this . key , newValue ) ;
27+ if ( this . expiryDurationMs ) {
28+ await this . storage . update ( this . key , { data : newValue , expiry : Date . now ( ) + this . expiryDurationMs } ) ;
29+ } else {
30+ await this . storage . update ( this . key , newValue ) ;
31+ }
1932 }
2033}
2134
2235@injectable ( )
2336export class PersistentStateFactory implements IPersistentStateFactory {
24- constructor ( @inject ( IMemento ) @named ( GLOBAL_MEMENTO ) private globalState : Memento ,
37+ constructor ( @inject ( IMemento ) @named ( GLOBAL_MEMENTO ) private globalState : Memento ,
2538 @inject ( IMemento ) @named ( WORKSPACE_MEMENTO ) private workspaceState : Memento ) { }
26- public createGlobalPersistentState < T > ( key : string , defaultValue : T ) : IPersistentState < T > {
27- return new PersistentState < T > ( this . globalState , key , defaultValue ) ;
39+ public createGlobalPersistentState < T > ( key : string , defaultValue ? : T , expiryDurationMs ?: number ) : IPersistentState < T > {
40+ return new PersistentState < T > ( this . globalState , key , defaultValue , expiryDurationMs ) ;
2841 }
29- public createWorkspacePersistentState < T > ( key : string , defaultValue : T ) : IPersistentState < T > {
30- return new PersistentState < T > ( this . workspaceState , key , defaultValue ) ;
42+ public createWorkspacePersistentState < T > ( key : string , defaultValue ? : T , expiryDurationMs ?: number ) : IPersistentState < T > {
43+ return new PersistentState < T > ( this . workspaceState , key , defaultValue , expiryDurationMs ) ;
3144 }
3245}
0 commit comments