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-03 09:21:29 +00:00
|
|
|
async array(): Promise<undefined | T2[]> {
|
|
|
|
const arr = await (this.client.cache.array(this.cacheName) as T[])
|
2020-11-03 05:19:57 +00:00
|
|
|
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>> {
|
2020-11-03 09:21:29 +00:00
|
|
|
const arr = await this.array()
|
2020-11-01 13:42:00 +00:00
|
|
|
if(arr === undefined) return new Collection()
|
2020-11-03 09:21:29 +00:00
|
|
|
const collection = new Collection()
|
2020-11-01 13:42:00 +00:00
|
|
|
for (const elem of arr) {
|
2020-11-03 09:21:29 +00:00
|
|
|
// @ts-expect-error
|
2020-11-01 13:42:00 +00:00
|
|
|
collection.set(elem.id, elem)
|
|
|
|
}
|
|
|
|
return collection
|
|
|
|
}
|
2020-11-02 12:08:38 +00:00
|
|
|
|
2020-11-03 09:21:29 +00:00
|
|
|
flush(): any {
|
2020-11-02 12:08:38 +00:00
|
|
|
return this.client.cache.deleteCache(this.cacheName)
|
|
|
|
}
|
2020-11-02 06:58:23 +00:00
|
|
|
}
|