harmony/src/managers/base.ts

56 lines
1.5 KiB
TypeScript
Raw Normal View History

2020-11-08 07:57:24 +00:00
import { Client } from '../models/client.ts'
import { Collection } from '../utils/collection.ts'
export class BaseManager<T, T2> {
client: Client
/** Cache Name or Key used to differentiate caches */
cacheName: string
/** Which data type does this cache have */
DataType: any
constructor (client: Client, cacheName: string, DataType: any) {
this.client = client
this.cacheName = cacheName
this.DataType = DataType
}
async _get (key: string): Promise<T | undefined> {
return this.client.cache.get(this.cacheName, key)
}
async get (key: string): Promise<T2 | undefined> {
const raw = await this._get(key)
if (raw === undefined) return
return new this.DataType(this.client, raw)
}
async set (key: string, value: T): Promise<any> {
return this.client.cache.set(this.cacheName, key, value)
}
async delete (key: string): Promise<boolean> {
return this.client.cache.delete(this.cacheName, key)
}
2020-11-03 15:19:20 +00:00
async array (): Promise<undefined | T2[]> {
2020-11-25 11:53:40 +00:00
let arr = await (this.client.cache.array(this.cacheName) as T[])
if (arr === undefined) arr = []
2020-11-03 05:19:57 +00:00
return arr.map(e => new this.DataType(this.client, e)) as any
}
2020-11-03 15:19:20 +00:00
async collection (): Promise<Collection<string, T2>> {
2020-11-03 09:21:29 +00:00
const arr = await this.array()
2020-11-03 15:19:20 +00:00
if (arr === undefined) return new Collection()
2020-11-03 09:21:29 +00:00
const collection = new Collection()
for (const elem of arr) {
2020-11-03 09:21:29 +00:00
// @ts-expect-error
collection.set(elem.id, elem)
}
return collection
}
2020-11-25 11:53:40 +00:00
flush (): any {
return this.client.cache.deleteCache(this.cacheName)
}
}