1
+ /*
2
+ * Copyright (c) Microsoft Corporation. All rights reserved.
3
+ * Licensed under the MIT License.
4
+ */
5
+
1
6
import { Storage } from './Storage' ;
2
7
import {
3
8
Serializer ,
@@ -78,19 +83,20 @@ export class CacheManager {
78
83
*/
79
84
async writeToPersistence ( ) : Promise < void > {
80
85
if ( this . persistence ) {
81
- this . cacheSnapshot = await this . persistence . readFromStorage ( ) ;
86
+ let cache = Serializer . serializeAllCache ( this . storage . getCache ( ) ) ;
82
87
83
- let finalState = Serializer . serializeAllCache ( this . storage . getCache ( ) ) ;
88
+ const getMergedState = ( stateFromDisk : string ) => {
84
89
85
- // if cacheSnapshot not null or empty, merge
86
- if ( ! StringUtils . isEmpty ( this . cacheSnapshot ) ) {
87
- finalState = this . mergeState (
88
- JSON . parse ( this . cacheSnapshot ) ,
89
- Serializer . serializeAllCache ( this . storage . getCache ( ) ) ) ;
90
- }
91
- this . hasChanged = false ;
90
+ if ( ! StringUtils . isEmpty ( stateFromDisk ) ) {
91
+ this . cacheSnapshot = stateFromDisk ;
92
+ cache = this . mergeState ( JSON . parse ( stateFromDisk ) , cache ) ;
93
+ }
94
+
95
+ return JSON . stringify ( cache ) ;
96
+ } ;
92
97
93
- await this . persistence . writeToStorage ( JSON . stringify ( finalState ) ) ;
98
+ await this . persistence . writeToStorage ( getMergedState ) ;
99
+ this . hasChanged = false ;
94
100
} else {
95
101
throw ClientAuthError . createCachePluginError ( ) ;
96
102
}
@@ -102,10 +108,11 @@ export class CacheManager {
102
108
*/
103
109
async readFromPersistence ( ) : Promise < void > {
104
110
if ( this . persistence ) {
105
- const cache = await this . persistence . readFromStorage ( ) ;
111
+ this . cacheSnapshot = await this . persistence . readFromStorage ( ) ;
106
112
107
- if ( ! StringUtils . isEmpty ( cache ) ) {
108
- const deserializedCache = Deserializer . deserializeAllCache ( this . overlayDefaults ( JSON . parse ( cache ) ) ) ;
113
+ if ( ! StringUtils . isEmpty ( this . cacheSnapshot ) ) {
114
+ const cache = this . overlayDefaults ( JSON . parse ( this . cacheSnapshot ) ) ;
115
+ const deserializedCache = Deserializer . deserializeAllCache ( cache ) ;
109
116
this . storage . setCache ( deserializedCache ) ;
110
117
}
111
118
} else {
0 commit comments