summaryrefslogtreecommitdiff
path: root/src/database/structures/SettingsProvider.ts
blob: 8ca6b92fb5dfca95a3f2986de019e5dc20b3667c (plain) (blame)
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
import { Collection } from 'discord.js';
import { connect, Model, connection, Connection } from 'mongoose';
import { Logger } from 'winston';
import ReactionModel, { Reaction } from '../models/Reaction';
import GuildModel, { Guild } from '../models/Guild';
import { MONGO_EVENTS } from '../util/constants';
import ReactionClient from '../../bot/client/ReactionClient';

let i = 0;

/**
 * The key, model and cached collection of a database model.
 * @interface
 */
interface Combo {
	key: string;
	model: Model<any>;
	cache: Collection<string, any>;
}

/**
 * The Settings Provider that handles all database reads and rights.
 * @private
 */
export default class SettingsProvider {
	protected readonly client: ReactionClient;

	protected readonly guilds: Collection<string, Guild> = new Collection();
	protected readonly reactions: Collection<string, Reaction> = new Collection();

	protected readonly GuildModel = GuildModel;
	protected readonly ReactionModel = ReactionModel;

	/**
	 *
	 * @param {GiveawayClient} client - The extended Akairo Client
	 */
	public constructor(client: ReactionClient) {
		this.client = client;
	}

	/**
	 * Retuns all the collection caches.
	 * @returns {Object}
	 */
	public get cache() {
		return {
			guilds: this.guilds,
			reactions: this.reactions,
		};
	}

	/**
	 * Returns the database combos
	 * @returns {Combo[]}
	 */
	public get combos(): Combo[] {
		return [
			{
				key: 'guild',
				model: this.GuildModel,
				cache: this.guilds,
			},
			{
				key: 'reaction',
				model: this.ReactionModel,
				cache: this.reactions,
			},
		];
	}

	/**
	 * Creates a new database document with the provided collection name and data.
	 * @param {string} type - The collection name
	 * @param {object} data - The data for the new document
	 * @returns {Docuement}
	 */
	public async new(type: 'guild', data: Partial<Guild>): Promise<Guild>;
	public async new(type: 'reaction', data: Partial<Reaction>): Promise<Reaction>;
	public async new(type: string, data: object): Promise<object> {
		const combo = this.combos.find(c => c.key === type);
		if (combo) {
			const document = new combo.model(data);
			await document.save();
			this.client.logger.data(`[DATABASE] Made new ${combo.model.modelName} document with ID of ${document._id}.`);
			combo.cache.set(document.id, document);
			return document;
		}
		throw Error(`"${type}" is not a valid model key.`);
	}

	/**
	 * Updates the a database document's data.
	 * @param {Types} type - The collection name
	 * @param {object} key - The search paramaters for the document
	 * @param {object} data - The data you wish to overwrite in the update
	 * @returns {Promise<Faction | Guild | null>}
	 */
	public async set(type: 'guild', key: Partial<Guild>, data: Partial<Guild>): Promise<Guild | null>;
	public async set(type: 'reaction', key: Partial<Reaction>, data: Partial<Reaction>): Promise<Reaction | null>;
	public async set(type: string, key: object, data: object): Promise<object | null> {
		const combo = this.combos.find(c => c.key === type);
		if (combo) {
			const document = await combo.model.findOneAndUpdate(key, { $set: data }, { new: true });
			if (document) {
				this.client.logger.verbose(`[DATABASE] Edited ${combo.model.modelName} document with ID of ${document._id}.`);
				combo.cache.set(document.id, document);
				return document;
			}
			return null;
		}
		throw Error(`"${type}" is not a valid model key.`);
	}

	/**
	 * Removes a database document.
	 * @param {Types} type - The collection name
	 * @param {object} data - The search paramaters for the document
	 * @returns {Promise<Faction | Guild | null>>} The document that was removed, if any.
	 */
	public async remove(type: 'guild', data: Partial<Guild>): Promise<Guild | null>;
	public async remove(type: 'user', data: Partial<Reaction>): Promise<Reaction | null>;
	public async remove(type: string, data: object): Promise<object | null> {
		const combo = this.combos.find(c => c.key === type);
		if (combo) {
			const document = await combo.model.findOneAndRemove(data);
			if (document) {
				this.client.logger.verbose(`[DATABASE] Edited ${combo.model.modelName} document with ID of ${document._id}.`);
				combo.cache.delete(document.id);
				return document;
			}
			return null;
		}
		throw Error(`"${type}" is not a valid model key.`);
	}

	/**
	 * Caching all database documents.
	 * @returns {number} The amount of documents cached total.
	 * @private
	 */
	private async _cacheAll(): Promise<number> {
		for (const combo of this.combos) await this._cache(combo);
		return i;
	}

	/**
	 * Caching each collection's documents.
	 * @param {Combo} combo - The combo name
	 * @returns {number} The amount of documents cached from that collection.
	 * @private
	 */
	private async _cache(combo: Combo): Promise<any> {
		const items = await combo.model.find();
		for (const i of items) combo.cache.set(i.id, i);
		this.client.logger.verbose(
			`[DATABASE]: Cached ${items.length.toLocaleString('en-US')} items from ${combo.model.modelName}.`,
		);
		return (i += items.length);
	}

	/**
	 * Connect to the database
	 * @param {string} url - the mongodb uri
	 * @returns {Promise<number | Logger>} Returns a
	 */
	private async _connect(url: string | undefined): Promise<Logger | number> {
		if (url) {
			const start = Date.now();
			try {
				await connect(url, {
					useCreateIndex: true,
					useNewUrlParser: true,
					useFindAndModify: false,
					useUnifiedTopology: true,
				});
			} catch (err) {
				this.client.logger.error(`[DATABASE] Error when connecting to MongoDB:\n${err.stack}`);
				process.exit(1);
			}
			return this.client.logger.verbose(`[DATABASE] Connected to MongoDB in ${Date.now() - start}ms.`);
		}
		this.client.logger.error('[DATABASE] No MongoDB url provided!');
		return process.exit(1);
	}

	/**
	 * Adds all the listeners to the mongo connection.
	 * @param connection - The mongoose connection
	 * @returns {void}
	 * @private
	 */
	private _addListeners(connection: Connection): void {
		for (const [event, msg] of Object.entries(MONGO_EVENTS)) {
			connection.on(event, () => this.client.logger.data(`[DATABASE]: ${msg}`));
		}
	}

	/**
	 * Starts the Settings Provider
	 * @returns {SettingsProvider}
	 */
	public async init(): Promise<this> {
		this._addListeners(connection);
		await this._connect(process.env.MONGO);
		this.client.logger.verbose(`[DATABASE]: Now caching ${this.combos.length} schema documents.`);
		await this._cacheAll();
		this.client.logger.info(`[DATABASE] [LAUNCHED] Successfully connected and cached ${i} documents.`);
		return this;
	}
}