-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathGuildConfigCache.js
106 lines (95 loc) · 2.86 KB
/
GuildConfigCache.js
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
import LRUCache from './../../Utility/External/LRUCache';
import Store from '../../Utility/Store';
import AxonError from '../../Errors/AxonError';
/**
* @typedef {import('../../AxonClient').default} AxonClient
*/
/**
* Handles GuildConfigs cache.
* Can be extended to a redis or memcached cache easily for instance.
*
* @author KhaaZ
*
* @class GuildConfigsCache
* @extends Store<GuildConfig>
* @prop {AxonClient} _axon
* @prop {LRUCache<GuildConfig>} guildConfigs
*/
class GuildConfigsCache extends Store {
/**
* Creates an instance of GuildConfigsCache.
*
* @param {AxonClient} axonClient
* @param {Number} limit - The limit of item in the LRUCache
* @memberof GuildConfigsCache
*/
constructor(axonClient, limit) {
super(new LRUCache(limit || 1000, { base: axonClient.extensions.guildConfig } ) );
this._axon = axonClient;
}
/**
* Returns the cache
*
* @readonly
* @type {LRUCache<GuildConfig>}
* @memberof GuildConfigsCache
*/
get guildConfigs() {
return this.cache;
}
/**
* Get a GuildConfig from the cache or from the DB if not in the cache.
*
* @param {String} key
* @returns {Promise<GuildConfig|null>}
* @memberof GuildConfigsCache
*/
async getOrFetch(key) {
let guildConfig = this.get(key);
if (!guildConfig) {
try {
guildConfig = await this.fetch(key);
} catch (err) {
throw new AxonError(`Cannot retrieve guildConfig from the DB: Guild: ${key}\n${err.stack}`, 'AxonClient', 'GuildConfigsCache');
}
}
return guildConfig;
}
/**
* Fetches and resolves the guild config of the given ID from the DB, creates a schema if none was found or there was an error.
*
* @param {String} gID - The guild ID to fetch the DB
* @returns {Promise<GuildConfig|null>} Guild schema from the DB / Error
* @memberof GuildConfigsCache
*/
async fetch(gID) {
let guildConfig;
try {
guildConfig = await this._axon.DBProvider.fetchGuild(gID);
if (!guildConfig) {
guildConfig = await this._axon.DBProvider.initGuild(gID);
}
} catch (_) {
guildConfig = await this._axon.DBProvider.initGuild(gID);
}
this.set(gID, guildConfig);
return guildConfig;
}
/**
* Refresh the element by supressing it, fetching and caching it again
*
* @param {String} gID
* @returns {Boolean} Whether it worked
* @memberof GuildConfigsCache
*/
async refresh(gID) {
this.delete(gID);
const guildConfig = await this.fetch(gID);
if (!guildConfig) {
return false;
}
this.set(gID, guildConfig);
return true;
}
}
export default GuildConfigsCache;