From b986f1c585991b1c9921ed69d74f8363c3b93861 Mon Sep 17 00:00:00 2001 From: Jan Date: Sat, 16 Jul 2022 20:25:13 +0200 Subject: [PATCH] create database indexes --- bot/src/bot/db.ts | 32 +++++++++++++++++++++++++++++++- bot/src/index.ts | 5 ++++- 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/bot/src/bot/db.ts b/bot/src/bot/db.ts index 510a803..73ecb32 100644 --- a/bot/src/bot/db.ts +++ b/bot/src/bot/db.ts @@ -1,4 +1,5 @@ -import Monk, { IMonkManager } from 'monk'; +import Monk, { ICollection, IMonkManager } from 'monk'; +import { dbs } from '..'; import logger from './logger'; export default (): IMonkManager => { @@ -27,3 +28,32 @@ function getDBUrl() { return dburl; } + +async function databaseMigrations() { + async function setIndexes(collection: ICollection, toIndex: string[]) { + try { + const indexes = await collection.indexes(); + for (const index of toIndex) { + if (!Object.values(indexes).find(v => v[0][0] == index)) { + logger.info(`Creating index ${index} on ${collection.name}`); + await collection.createIndex(index); + } + } + } catch(e) { + logger.warn(`Failed to run migrations for ${collection.name}: ${e}`); + } + } + + await setIndexes(dbs.BRIDGE_CONFIG, [ 'discord', 'revolt' ]); + await setIndexes(dbs.BRIDGE_REQUESTS, [ 'id', 'revolt' ]); + await setIndexes(dbs.BRIDGED_MESSAGES, [ 'discord.messageId', 'revolt.messageId', 'revolt.nonce' ]); + await setIndexes(dbs.INFRACTIONS, [ 'createdBy', 'user', 'server' ]); + await setIndexes(dbs.PENDING_LOGINS, [ 'code', 'user' ]); + await setIndexes(dbs.SERVERS, [ 'id' ]); + await setIndexes(dbs.SESSIONS, [ 'user', 'token' ]); + await setIndexes(dbs.TEMPBANS, [ 'id', 'until' ]); + await setIndexes(dbs.USERS, [ 'id' ]); + await setIndexes(dbs.VOTEKICKS, [ 'id', 'server', 'target' ]); +} + +export { databaseMigrations } diff --git a/bot/src/index.ts b/bot/src/index.ts index 9920d40..0e453a0 100644 --- a/bot/src/index.ts +++ b/bot/src/index.ts @@ -3,7 +3,7 @@ config(); import logger from './bot/logger'; import AutomodClient, { login } from './struct/AutomodClient'; -import MongoDB from './bot/db'; +import MongoDB, { databaseMigrations } from './bot/db'; import DbUser from 'automod/dist/types/DbUser'; import ServerConfig from 'automod/dist/types/ServerConfig'; import Infraction from 'automod/dist/types/antispam/Infraction'; @@ -56,6 +56,9 @@ logger.info(`\ await db.get('servers').findOne({}); logger.done('DB ready!'); + logger.info('Running database migrations...'); + await databaseMigrations(); + // Load modules import('./bot/modules/command_handler'); import('./bot/modules/mod_logs');