create database indexes

This commit is contained in:
Jan 2022-07-16 20:25:13 +02:00
parent b3692542b3
commit b986f1c585
Signed by: Lea
GPG key ID: 5D5E18ACB990F57A
2 changed files with 35 additions and 2 deletions

View file

@ -1,4 +1,5 @@
import Monk, { IMonkManager } from 'monk'; import Monk, { ICollection, IMonkManager } from 'monk';
import { dbs } from '..';
import logger from './logger'; import logger from './logger';
export default (): IMonkManager => { export default (): IMonkManager => {
@ -27,3 +28,32 @@ function getDBUrl() {
return dburl; 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 }

View file

@ -3,7 +3,7 @@ config();
import logger from './bot/logger'; import logger from './bot/logger';
import AutomodClient, { login } from './struct/AutomodClient'; 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 DbUser from 'automod/dist/types/DbUser';
import ServerConfig from 'automod/dist/types/ServerConfig'; import ServerConfig from 'automod/dist/types/ServerConfig';
import Infraction from 'automod/dist/types/antispam/Infraction'; import Infraction from 'automod/dist/types/antispam/Infraction';
@ -56,6 +56,9 @@ logger.info(`\
await db.get('servers').findOne({}); await db.get('servers').findOne({});
logger.done('DB ready!'); logger.done('DB ready!');
logger.info('Running database migrations...');
await databaseMigrations();
// Load modules // Load modules
import('./bot/modules/command_handler'); import('./bot/modules/command_handler');
import('./bot/modules/mod_logs'); import('./bot/modules/mod_logs');