Cache do Microsoft Graph ToolkitMicrosoft Graph Toolkit caching
O Microsoft Graph Toolkit oferece suporte a cache de chamadas de API SELECT do Microsoft Graph.The Microsoft Graph Toolkit supports caching of select Microsoft Graph API calls. Atualmente, as chamadas para os pontos de extremidade de usuários, pessoas, contatos e fotos são armazenadas em cache por padrão em três repositórios do IndexedDB.Currently, calls to the users, person, contact, and photo endpoints are cached by default in three IndexedDB stores.
Você pode exibir o cache no painel de desenvolvedor.You can view the cache on the developer panel. Na guia aplicativo , no painel armazenamento , vá para a guia IndexedDB .On the Application tab, in the Storage pane, go to the IndexedDB tab.
Configuração de cacheCache configuration
Você pode ler e gravar as opções de cache por meio do objeto de classe estática CacheService.config
.You can read and write the cache options through the static class CacheService.config
object. Ele é formatado como mostrado.It is formatted as shown.
let config = {
defaultInvalidationPeriod: number,
isEnabled: boolean,
people: {
invalidationPeriod: number,
isEnabled: boolean
},
photos: {
invalidationPeriod: number,
isEnabled: boolean
},
users: {
invalidationPeriod: number,
isEnabled: boolean
},
presence: {
invalidationPeriod: number,
isEnabled: boolean
},
groups: {
invalidationPeriod: number,
isEnabled: boolean
},
};
Os períodos de invalidação de cache individual são padronizados para null
o objeto config e o padrão é o defaultInvalidationPeriod
valor geral 3,6 milhões ms (60 minutos).Individual cache invalidation periods are defaulted to null
in the config object, and default to the general defaultInvalidationPeriod
value of 3,600,000 ms (60 minutes). Qualquer valor passado para config.x.invalidationPeriod
será substituído defaultInvalidationPeriod
.Any value passed into config.x.invalidationPeriod
will override defaultInvalidationPeriod
.
O repositório de presença é a única exceção e tem um valor padrão de 300000 MS ou 5 minutos.The presence store is the only exception, and has a default value of 300000 ms, or 5 minutes.
ExemplosExamples
Para desabilitar individualmente um repositório, basta definir o valor das isEnabled
Propriedades de config da loja como false:To individual disable a store simply set the value of isEnabled
in that store's config properties to false:
import { CacheService } from '@microsoft/mgt';
CacheService.config.users.isEnabled = false;
Desabilitar o cache não limpa o cache.Disabling the cache does not clear the cache.
Alterar o período de invalditation é semelhante:Changing the invalditation period is similar:
import { CacheService } from '@microsoft/mgt';
CacheService.config.users.invalidationPeriod = 1800000;
Limpando o cacheClearing the cache
O cache é automaticamente limpo quando o usuário se desconecta. Ela também pode ser limpa manualmente.The cache is automatically cleared when the user signs out. It can also be cleared manually.
Limpar todas as lojas no cache, o clearCaches()
método da CacheService
classe limpará todos os repositórios mantidos pelo CacheService.The clear all the stores in the cache, the clearCaches()
method of the CacheService
class will clear every store maintained by the CacheService.
import { CacheService } from '@microsoft/mgt';
CacheService.clearCaches();
Criar seus próprios repositórios de cacheCreating your own cache stores
Se você deseja criar e preencher seus próprios repositórios de cache para seus componentes personalizados, você pode usar a CacheService
classe estática.If you want to create and populate your own cache stores for your custom components, you can use the CacheService
static class.
CacheService.getCache(schema: CacheSchema, storeName: String);
Observação: A
storeName
referência que você faz na chamadagetCache()
deve corresponder a uma das lojas listadas em seuCacheSchema
objeto.Note: ThestoreName
you reference in the call togetCache()
must match one of the stores listed in yourCacheSchema
object.
O CacheSchema
objeto é um dicionário com os pares chave/valor.The CacheSchema
object is a dictionary with the key/value pairs.
import { CacheSchema } from '@microsoft/mgt';
const cacheSchema: CacheSchema = {
name: string,
stores: {
store1: {},
store2: {},
...
},
version: number
};
O exemplo a seguir mostra a implementação de cache.The following example shows the cache implementation.
import { CacheItem, CacheSchema, CacheService, CacheStore } from '@microsoft/mgt';
const cacheSchema: CacheSchema = {
name: 'users',
stores: {
users: {},
usersQuery: {}
},
version: 1
};
interface CacheUser extends CacheItem {
user?: string;
}
// retrieves invalidation time from cache config
const getUserInvalidationTime = (): number =>
CacheService.config.users.invalidationPeriod || CacheService.config.defaultInvalidationPeriod;
// checks for if cache is enabled
const usersCacheEnabled = (): boolean => CacheService.config.users.isEnabled && CacheService.config.isEnabled;
// declare the desired cache store
let cache: CacheStore<CacheUser>
// check if the cache is enabled
if (usersCacheEnabled()) {
cache = CacheService.getCache<CacheUser>(cacheSchema, 'users');
const user = await cache.getValue(query);
// check if an item is retrieved, and if it's not expired
if (user && getUserInvalidationTime() > Date.now() - user.timeCached) {
return JSON.parse(user.user);
}
}
// graph call
const graphRes = graph
.api('me')
.middlewareOptions(prepScopes('user.read'))
.get();
// store graph result into the cache if cache is enabled
if (usersCacheEnabled()) {
cache.putValue(userId, { user: JSON.stringify(graphRes) });
}