Almacenamiento en caché del kit de herramientas de Microsoft GraphMicrosoft Graph Toolkit caching
El kit de herramientas de Microsoft Graph admite el almacenamiento en caché de llamadas a la API de Microsoft Graph.The Microsoft Graph Toolkit supports caching of select Microsoft Graph API calls. Actualmente, las llamadas a los puntos de conexión de usuarios, personas, contactos y fotos se almacenan en caché de forma predeterminada en tres almacenes de IndexedDB.Currently, calls to the users, person, contact, and photo endpoints are cached by default in three IndexedDB stores.
Puede ver la memoria caché en el panel del programador.You can view the cache on the developer panel. En la pestaña aplicación , en el panel de almacenamiento , vaya a la pestaña IndexedDB .On the Application tab, in the Storage pane, go to the IndexedDB tab.
Configuración de la memoria cachéCache configuration
Puede leer y escribir las opciones de caché a través del objeto de clase estático CacheService.config
.You can read and write the cache options through the static class CacheService.config
object. Tiene el formato que se muestra.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
},
};
Los períodos de invalidación de la memoria caché individuales se predeterminan null
en el objeto de configuración y de forma predeterminada se el defaultInvalidationPeriod
valor general de 3,6 millones 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). Cualquier valor pasado config.x.invalidationPeriod
se reemplazará defaultInvalidationPeriod
.Any value passed into config.x.invalidationPeriod
will override defaultInvalidationPeriod
.
El almacén de presencia es la única excepción y tiene un valor predeterminado de 300000 MS o 5 minutos.The presence store is the only exception, and has a default value of 300000 ms, or 5 minutes.
EjemplosExamples
Para deshabilitar un almacén, simplemente establezca el valor de isEnabled
en las propiedades de configuración de ese almacén en 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;
La deshabilitación de la memoria caché no borra la memoria caché.Disabling the cache does not clear the cache.
Cambiar el período de invalditation es similar:Changing the invalditation period is similar:
import { CacheService } from '@microsoft/mgt';
CacheService.config.users.invalidationPeriod = 1800000;
Borrar la memoria cachéClearing the cache
La memoria caché se borra automáticamente cuando el usuario cierra sesión. También se puede borrar de forma manual.The cache is automatically cleared when the user signs out. It can also be cleared manually.
La eliminación de todos los almacenes de la memoria caché, el clearCaches()
método de la CacheService
clase borrará todos los almacenes mantenidos por el 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();
Crear sus propios almacenes de cachéCreating your own cache stores
Si desea crear y rellenar sus propios almacenes de caché para los componentes personalizados, puede usar la CacheService
clase 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);
Nota: La
storeName
referencia a la que se hace la llamadagetCache()
debe coincidir con uno de los almacenes que aparecen en elCacheSchema
objeto.Note: ThestoreName
you reference in the call togetCache()
must match one of the stores listed in yourCacheSchema
object.
El CacheSchema
objeto es un diccionario con los pares clave/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
};
En el ejemplo siguiente se muestra la implementación de la memoria caché.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) });
}