harmony/src/managers/baseChild.ts

64 lines
1.8 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'
import { BaseManager } from './base.ts'
2020-12-03 04:06:41 +00:00
/** Child Managers validate data from their parents i.e. from Managers */
export class BaseChildManager<T, T2> {
client: Client
2020-12-03 04:06:41 +00:00
/** Parent Manager */
parent: BaseManager<T, T2>
constructor(client: Client, parent: BaseManager<T, T2>) {
this.client = 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()
arr.forEach((el: unknown) => writable.getWriter().write(el))
yield* readable.getIterator()
}
2021-03-19 11:48:37 +00:00
async fetch(...args: unknown[]): Promise<T2 | undefined> {
return undefined
}
/** 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
}
}
2020-12-02 12:29:52 +00:00
}