2020-10-31 11:45:33 +00:00
|
|
|
import { Client } from "../models/client.ts";
|
2020-11-01 13:42:00 +00:00
|
|
|
import { Collection } from "../utils/collection.ts";
|
2020-10-31 11:45:33 +00:00
|
|
|
|
|
|
|
export class BaseManager<T, T2> {
|
|
|
|
client: Client
|
|
|
|
cacheName: string
|
2020-11-02 06:58:23 +00:00
|
|
|
DataType: any
|
2020-10-31 11:45:33 +00:00
|
|
|
|
2020-11-02 06:58:23 +00:00
|
|
|
constructor (client: Client, cacheName: string, DataType: any) {
|
2020-10-31 11:45:33 +00:00
|
|
|
this.client = client
|
|
|
|
this.cacheName = cacheName
|
2020-11-02 06:58:23 +00:00
|
|
|
this.DataType = DataType
|
2020-10-31 11:45:33 +00:00
|
|
|
}
|
|
|
|
|
2020-11-02 06:58:23 +00:00
|
|
|
async _get (key: string): Promise<T | undefined> {
|
|
|
|
return this.client.cache.get(this.cacheName, key)
|
2020-10-31 11:45:33 +00:00
|
|
|
}
|
|
|
|
|
2020-11-02 06:58:23 +00:00
|
|
|
async get (key: string): Promise<T2 | undefined> {
|
2020-11-01 11:22:09 +00:00
|
|
|
const raw = await this._get(key)
|
2020-11-02 06:58:23 +00:00
|
|
|
if (raw === undefined) return
|
|
|
|
return new this.DataType(this.client, raw)
|
2020-10-31 11:45:33 +00:00
|
|
|
}
|
|
|
|
|
2020-11-02 06:58:23 +00:00
|
|
|
async set (key: string, value: T): Promise<any> {
|
2020-10-31 11:45:33 +00:00
|
|
|
return this.client.cache.set(this.cacheName, key, value)
|
|
|
|
}
|
|
|
|
|
2020-11-02 06:58:23 +00:00
|
|
|
async delete (key: string): Promise<boolean> {
|
2020-10-31 11:45:33 +00:00
|
|
|
return this.client.cache.delete(this.cacheName, key)
|
|
|
|
}
|
2020-11-01 13:42:00 +00:00
|
|
|
|
2020-11-02 12:08:38 +00:00
|
|
|
async array(): Promise<void | T2[]> {
|
|
|
|
let arr = await (this.client.cache.array(this.cacheName) as T[])
|
|
|
|
return arr.map(e => new this.dataType(this.client, e)) as any
|
2020-11-01 13:42:00 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
async collection(): Promise<Collection<string, T2>> {
|
|
|
|
const arr = await this.array() as void | T2[]
|
|
|
|
if(arr === undefined) return new Collection()
|
|
|
|
let collection = new Collection()
|
|
|
|
for (const elem of arr) {
|
|
|
|
// @ts-ignore
|
|
|
|
collection.set(elem.id, elem)
|
|
|
|
}
|
|
|
|
return collection
|
|
|
|
}
|
2020-11-02 12:08:38 +00:00
|
|
|
|
|
|
|
flush() {
|
|
|
|
return this.client.cache.deleteCache(this.cacheName)
|
|
|
|
}
|
2020-11-02 06:58:23 +00:00
|
|
|
}
|