/
baseChild.ts
80 lines (66 loc) · 2.11 KB
/
baseChild.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import type { Client } from '../client/mod.ts'
import { Base } from '../structures/base.ts'
import { Collection } from '../utils/collection.ts'
import { BaseManager } from './base.ts'
/** Child Managers validate data from their parents i.e. from Managers */
export class BaseChildManager<T, T2> extends Base {
/** Parent Manager */
parent: BaseManager<T, T2>
constructor(client: Client, parent: BaseManager<T, T2>) {
super(client)
this.parent = parent
}
get cacheName(): string {
return typeof this.parent === 'undefined'
? 'unknown_parent'
: this.parent.cacheName
}
async get(key: string): Promise<T2 | undefined> {
return this.parent.get(key)
}
async set(key: string, value: T): Promise<void> {
return this.parent.set(key, value)
}
async delete(_: string): Promise<boolean> {
return false
}
async array(): Promise<T2[]> {
return this.parent.array()
}
async collection(): Promise<Collection<string, T2>> {
const arr = (await this.array()) as undefined | T2[]
if (arr === undefined) return new Collection()
const collection = new Collection()
for (const elem of arr) {
collection.set((elem as unknown as { id: string }).id, elem)
}
return collection
}
async *[Symbol.asyncIterator](): AsyncIterableIterator<T2> {
for (const data of (await this.array()) ?? []) {
yield data
}
}
async fetch(...args: unknown[]): Promise<T2 | undefined> {
return this.parent.fetch(...args)
}
/** 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
}
}
/** Gets number of values stored in Cache */
async size(): Promise<number> {
return this.parent.size()
}
async keys(): Promise<string[]> {
return this.parent.keys()
}
[Symbol.for('Deno.customInspect')](): string {
return `ChildManager(${this.cacheName})`
}
}