Skip to content

Commit 99236b6

Browse files
author
Santiago Gonzalez
committed
Add callback to writeToStorage
1 parent 40598e8 commit 99236b6

File tree

2 files changed

+28
-14
lines changed

2 files changed

+28
-14
lines changed

lib/msal-node/src/cache/CacheManager.ts

Lines changed: 20 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,8 @@
1+
/*
2+
* Copyright (c) Microsoft Corporation. All rights reserved.
3+
* Licensed under the MIT License.
4+
*/
5+
16
import { Storage } from './Storage';
27
import {
38
Serializer,
@@ -78,19 +83,20 @@ export class CacheManager {
7883
*/
7984
async writeToPersistence(): Promise<void> {
8085
if (this.persistence) {
81-
this.cacheSnapshot = await this.persistence.readFromStorage();
86+
let cache = Serializer.serializeAllCache(this.storage.getCache());
8287

83-
let finalState = Serializer.serializeAllCache(this.storage.getCache());
88+
const getMergedState = (stateFromDisk: string) => {
8489

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+
};
9297

93-
await this.persistence.writeToStorage(JSON.stringify(finalState));
98+
await this.persistence.writeToStorage(getMergedState);
99+
this.hasChanged = false;
94100
} else {
95101
throw ClientAuthError.createCachePluginError();
96102
}
@@ -102,10 +108,11 @@ export class CacheManager {
102108
*/
103109
async readFromPersistence(): Promise<void> {
104110
if (this.persistence) {
105-
const cache = await this.persistence.readFromStorage();
111+
this.cacheSnapshot = await this.persistence.readFromStorage();
106112

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);
109116
this.storage.setCache(deserializedCache);
110117
}
111118
} else {
Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,11 @@
1+
/*
2+
* Copyright (c) Microsoft Corporation. All rights reserved.
3+
* Licensed under the MIT License.
4+
*/
5+
16
export interface ICachePlugin {
27
readFromStorage: () => Promise<string>;
3-
writeToStorage: (cache: string) => Promise<void>;
8+
writeToStorage: (
9+
getMergedState: (oldState: string) => string
10+
) => Promise<void>;
411
}

0 commit comments

Comments
 (0)