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-01 11:22:09 +00:00
|
|
|
dataType: any
|
2020-10-31 11:45:33 +00:00
|
|
|
|
2020-11-01 11:22:09 +00:00
|
|
|
constructor(client: Client, cacheName: string, dataType: any) {
|
2020-10-31 11:45:33 +00:00
|
|
|
this.client = client
|
|
|
|
this.cacheName = cacheName
|
|
|
|
this.dataType = dataType
|
|
|
|
}
|
|
|
|
|
2020-11-01 11:22:09 +00:00
|
|
|
_get(key: string): Promise<T> {
|
|
|
|
return this.client.cache.get(this.cacheName, key) as Promise<T>
|
2020-10-31 11:45:33 +00:00
|
|
|
}
|
|
|
|
|
2020-11-01 11:22:09 +00:00
|
|
|
async get(key: string): Promise<T2 | void> {
|
|
|
|
const raw = await this._get(key)
|
2020-10-31 11:45:33 +00:00
|
|
|
if(!raw) return
|
|
|
|
return new this.dataType(this.client, raw) as any
|
|
|
|
}
|
|
|
|
|
2020-11-01 13:42:00 +00:00
|
|
|
set(key: string, value: T) {
|
2020-10-31 11:45:33 +00:00
|
|
|
return this.client.cache.set(this.cacheName, key, value)
|
|
|
|
}
|
|
|
|
|
2020-11-01 13:42:00 +00:00
|
|
|
delete(key: string) {
|
2020-10-31 11:45:33 +00:00
|
|
|
return this.client.cache.delete(this.cacheName, key)
|
|
|
|
}
|
2020-11-01 13:42:00 +00:00
|
|
|
|
|
|
|
array(): Promise<void | T2[]> {
|
|
|
|
return (this.client.cache.array(this.cacheName) as T[]).map(e => new this.dataType(this.client, e)) as any
|
|
|
|
}
|
|
|
|
|
|
|
|
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-10-31 11:45:33 +00:00
|
|
|
}
|