harmony/src/managers/baseChild.ts

70 lines
2.0 KiB
TypeScript
Raw Normal View History

2021-04-04 09:29:56 +00:00
import type { Client } from '../client/mod.ts'
2021-04-30 12:37:01 +00:00
import { Base } from '../structures/base.ts'
2020-11-08 07:57:24 +00:00
import { Collection } from '../utils/collection.ts'
import { BaseManager } from './base.ts'
2020-12-03 04:06:41 +00:00
/** Child Managers validate data from their parents i.e. from Managers */
2021-04-30 12:37:01 +00:00
export class BaseChildManager<T, T2> extends Base {
2020-12-03 04:06:41 +00:00
/** Parent Manager */
parent: BaseManager<T, T2>
constructor(client: Client, parent: BaseManager<T, T2>) {
2021-04-30 12:37:01 +00:00
super(client)
this.parent = parent
}
2020-11-03 09:21:29 +00:00
async get(key: string): Promise<T2 | undefined> {
return this.parent.get(key)
}
2020-11-03 09:21:29 +00:00
async set(key: string, value: T): Promise<void> {
return this.parent.set(key, value)
}
async delete(key: string): Promise<any> {
return false
}
async array(): Promise<any> {
2020-11-03 09:21:29 +00:00
return this.parent.array()
}
async collection(): Promise<Collection<string, T2>> {
2020-12-02 12:29:52 +00:00
const arr = (await this.array()) as undefined | T2[]
2020-11-03 23:00:03 +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-12-03 04:06:41 +00:00
// any is required here. Else you would need ts-ignore or expect-error.
collection.set((elem as any).id, elem)
}
return collection
}
async *[Symbol.asyncIterator](): AsyncIterableIterator<T2> {
const arr = (await this.array()) ?? []
const { readable, writable } = new TransformStream()
2021-04-04 13:46:34 +00:00
const writer = writable.getWriter()
arr.forEach((el: unknown) => writer.write(el))
writer.close()
2021-03-19 11:54:48 +00:00
yield* readable
}
2021-03-19 11:48:37 +00:00
async fetch(...args: unknown[]): Promise<T2 | undefined> {
2021-03-19 11:50:46 +00:00
return this.parent.fetch(...args)
2021-03-19 11:48:37 +00:00
}
/** Try to get value from cache, if not found then fetch */
async resolve(key: string): Promise<T2 | undefined> {
const cacheValue = await this.get(key)
if (cacheValue !== undefined) return cacheValue
else {
const fetchValue = await this.fetch(key).catch(() => undefined)
if (fetchValue !== undefined) return fetchValue
}
}
2021-04-30 12:37:01 +00:00
[Deno.customInspect](): string {
return `ChildManager(${this.parent.cacheName})`
}
2020-12-02 12:29:52 +00:00
}