wangzhibo
2026-05-09 53418655c061ac26f66058253f39200aced1ab1d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/*
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License.
 */
 
import {
    AccountEntity,
    ICachePlugin,
    AccountEntityUtils,
    TokenCacheContext,
} from "@azure/msal-common/node";
import { TokenCache } from "../TokenCache.js";
import { IPartitionManager } from "./IPartitionManager.js";
import { ICacheClient } from "./ICacheClient.js";
 
/**
 * Cache plugin that serializes data to the cache and deserializes data from the cache
 * @public
 */
export class DistributedCachePlugin implements ICachePlugin {
    private client: ICacheClient;
    private partitionManager: IPartitionManager;
 
    constructor(client: ICacheClient, partitionManager: IPartitionManager) {
        this.client = client;
        this.partitionManager = partitionManager;
    }
 
    /**
     * Deserializes the cache before accessing it
     * @param cacheContext - TokenCacheContext
     */
    public async beforeCacheAccess(
        cacheContext: TokenCacheContext
    ): Promise<void> {
        const partitionKey = await this.partitionManager.getKey();
        const cacheData = await this.client.get(partitionKey);
        cacheContext.tokenCache.deserialize(cacheData);
    }
 
    /**
     * Serializes the cache after accessing it
     * @param cacheContext - TokenCacheContext
     */
    public async afterCacheAccess(
        cacheContext: TokenCacheContext
    ): Promise<void> {
        if (cacheContext.cacheHasChanged) {
            const kvStore = (
                cacheContext.tokenCache as TokenCache
            ).getKVStore();
            const accountEntities = Object.values(kvStore).filter((value) =>
                AccountEntityUtils.isAccountEntity(value as object)
            );
 
            let partitionKey: string;
            if (accountEntities.length > 0) {
                const accountEntity = accountEntities[0] as AccountEntity;
                partitionKey = await this.partitionManager.extractKey(
                    accountEntity
                );
            } else {
                partitionKey = await this.partitionManager.getKey();
            }
 
            await this.client.set(
                partitionKey,
                cacheContext.tokenCache.serialize()
            );
        }
    }
}