El caché es una capa de almacenamiento temporal que mantiene los datos frecuentemente accedidos disponibles para un acceso rápido. En Seyfert, el sistema de caché almacena los datos de Discord en memoria por defecto, aunque puede configurarse para usar otras soluciones de almacenamiento como Redis.
Resources (Recursos)
Todas las entidades soportadas por el caché de Seyfert son recursos, como canales, usuarios, miembros, etc. Cada uno de estos recursos se gestiona de la misma manera, pero pueden ser modificados y manejados de forma diferente según el Adaptador.
Deshabilitando
Seyfert permite deshabilitar estos recursos por separado.
El ejemplo anterior deshabilita el caché de baneos, y ese recurso no existiría en tiempo de ejecución.
Filtrando
Puedes filtrar qué datos se almacenan en un recurso. Por ejemplo, si tu aplicación no necesita almacenar en caché los canales de MD, puedes filtrarlos:
Seyfert te permite proporcionar tu propio adaptador para el caché, que puedes pensar como un controlador para permitir que Seyfert use una herramienta no soportada. Por defecto, Seyfert incluye MemoryAdapter y LimitedMemoryAdapter, ambos operan en RAM. Además, Seyfert tiene soporte oficial para Redis a través del Adaptador Redis.
Construyendo Tu Propio Caché
Recurso Personalizado
Un recurso personalizado es simplemente una nueva entidad de caché, por lo que integrarlo es relativamente simple. Tomemos como ejemplo el recurso Cooldown del paquete cooldown.
Es importante notar que Seyfert proporciona una base para tres tipos de recursos:
BaseResource: una entidad básica, que debe ser completamente independiente
GuildBaseResource: una entidad vinculada a un servidor (como los baneos)
GuildRelatedResource: una entidad que puede estar o no vinculada a un servidor (como los mensajes)
Ten en cuenta que un recurso personalizado es para uso del desarrollador; Seyfert no interactuará con él a menos que se especifique en el código de la aplicación.
¿No te gusta almacenar el caché en memoria o Redis? ¿O tal vez simplemente quieres hacerlo a tu manera?
Aquí aprenderás cómo crear tu propio adaptador de caché.
Antes de Empezar
Considera si tu adaptador podría ser asíncrono; si lo es, necesitarás especificarlo:
import {
(alias) interfaceAdapter
importAdapter
Adapter } from'seyfert';
class
classMiAdaptador
MiAdaptadorimplements
(alias) interfaceAdapter
importAdapter
Adapter {
MiAdaptador.isAsync: boolean
isAsync=true;
async
MiAdaptador.start(): Promise<void>
start() {
// Esta función se ejecutará antes de iniciar el bot
}
}
Esta guía es para crear un adaptador asíncrono. Si quieres uno síncrono, simplemente no devuelvas una promesa en ninguno de los métodos (el método start puede ser asíncrono).
Almacenando Datos
En el caché de Seyfert, hay relaciones, para que puedas saber a quién pertenece un recurso.
Hay cuatro métodos que debes implementar en tu adaptador para almacenar valores: set, patch, bulkPatch, y bulkSet.
Returns the elements of an array that meet the condition specified in a callback function.
@param ― predicate A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array.
@param ― thisArg An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.
filter(
value: any
value=>
value: any
value)
}
}
El método scan
Actualmente, estamos almacenando datos en este formato:
Split a string into substrings using the specified separator and return them as an array.
@param ― separator A string that identifies character or characters to use in separating the string. If omitted, a single-element array containing the entire string is returned.
@param ― limit A value used to limit the number of elements returned in the array.
split('.');
// Tu cliente probablemente tendrá una forma más optimizada de hacer esto.
Split a string into substrings using the specified separator and return them as an array.
@param ― separator A string that identifies character or characters to use in separating the string. If omitted, a single-element array containing the entire string is returned.
@param ― limit A value used to limit the number of elements returned in the array.
Determines whether all the members of an array satisfy the specified test.
@param ― predicate A function that accepts up to three arguments. The every method calls
the predicate function for each element in the array until the predicate returns a value
which is coercible to the Boolean value false, or until the end of the array.
@param ― thisArg An object to which the this keyword can refer in the predicate function.
If thisArg is omitted, undefined is used as the this value.
every((
value: string
value,
i: number
i) => (
constsq:string[]
sq[
i: number
i] ==='*'?!!
value: string
value:
constsq:string[]
sq[
i: number
i] ===
value: string
value));
if (
constmatch:boolean
match) {
constvalues:unknown[]
values.
Array<unknown>.push(...items: unknown[]): number
Appends new elements to the end of an array, and returns the new length of the array.
Calls a defined callback function on each element of an array, and returns an array that contains the results.
@param ― callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
@param ― thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
map(
key: string
key=>`${
to: string
to}.${
key: string
key}`);
}
async
MiAdaptador.values(to: string): Promise<any[]>
values(
to: string
to:string) {
const
constarray:any[]
array:any[] = [];
const
constkeys:string[]
keys=awaitthis.
MiAdaptador.keys(to: string): Promise<string[]>
keys(
to: string
to);
for (const
constkey:string
keyof
constkeys:string[]
keys) {
const
constcontent:any
content=awaitthis.
MiAdaptador.get(key: string): Promise<any>
get(
constkey:string
key);
if (
constcontent:any
content) {
constarray:any[]
array.
Array<any>.push(...items: any[]): number
Appends new elements to the end of an array, and returns the new length of the array.