From 54a2072ca9078fe598b058b14ded5b336de9f625 Mon Sep 17 00:00:00 2001 From: Behzad Rabiei Date: Thu, 24 Oct 2024 15:13:21 +0400 Subject: [PATCH] format: format the code --- bot/.prettierrc | 10 +- bot/__tests__/fixtures/channel.fixture.ts | 9 +- bot/__tests__/fixtures/role.fixture.ts | 5 +- .../unit/database/services/channel.test.ts | 44 +--- .../database/services/guildMember.test.ts | 157 ++++------- .../unit/database/services/rawInfo.test.ts | 74 ++---- .../unit/database/services/role.test.ts | 39 +-- bot/__tests__/utils/setupTestDB.ts | 9 +- bot/src/commands/info/question.ts | 15 +- bot/src/config/index.ts | 45 +--- bot/src/config/pyroscope.ts | 10 +- bot/src/database/services/channel.service.ts | 72 +---- .../database/services/guildMember.service.ts | 78 ++---- bot/src/database/services/index.ts | 8 +- bot/src/database/services/platform.service.ts | 29 +- bot/src/database/services/rawInfo.service.ts | 70 +---- bot/src/database/services/role.service.ts | 69 +---- bot/src/events/channel/channelCreate.ts | 14 +- bot/src/events/channel/channelDelete.ts | 14 +- bot/src/events/channel/channelUpdate.ts | 11 +- bot/src/events/guild/guildCreate.ts | 3 +- bot/src/events/member/guildMemberAdd.ts | 3 +- bot/src/events/member/guildMemberUpdate.ts | 3 +- bot/src/functions/cronJon.ts | 15 +- bot/src/functions/fetchChannels.ts | 28 +- bot/src/functions/fetchMembers.ts | 28 +- bot/src/functions/fetchMessages.ts | 249 +++++------------- bot/src/functions/fetchRoles.ts | 24 +- bot/src/functions/guildExtraction.ts | 27 +- bot/src/functions/sendDirectMessage.ts | 5 +- .../migrations/utils/addChannelTypeLogic.ts | 3 +- bot/src/migrations/utils/isBotLogic.ts | 20 +- bot/src/migrations/utils/webhookLogic.ts | 115 +++----- .../queue/handlers/channelCreateHandler.ts | 5 +- .../queue/handlers/channelDeleteHandler.ts | 15 +- .../queue/handlers/channelUpdateHandler.ts | 5 +- .../queue/handlers/guildMemberAddHandler.ts | 10 +- .../handlers/guildMemberRemoveHandler.ts | 15 +- .../handlers/guildMemberUpdateHandler.ts | 10 +- bot/src/queue/handlers/roleCreateHandler.ts | 11 +- bot/src/queue/handlers/roleDeleteHandler.ts | 5 +- bot/src/queue/handlers/roleUpdateHandler.ts | 5 +- bot/src/queue/handlers/userUpdateHandler.ts | 4 +- bot/src/queue/queues/channelMessage.ts | 10 +- bot/src/queue/queues/guildExtraction.ts | 9 +- bot/src/queue/workers/channelMessageWorker.ts | 5 +- bot/src/queue/workers/directMessageWorker.ts | 5 +- bot/src/queue/workers/guildEventWorker.ts | 40 +-- bot/src/queue/workers/index.ts | 8 +- bot/src/rabbitmq/RabbitMQConnection.ts | 5 +- bot/src/rabbitmq/RabbitMQHandler.ts | 25 +- .../rabbitmq/events/FollowUpMessageCreate.ts | 15 +- bot/src/rabbitmq/events/fetchEvent.ts | 24 +- bot/src/rabbitmq/events/fetchMembersEvent.ts | 18 +- .../events/interactionResponseCreate.ts | 10 +- .../events/interactionResponseEdit.ts | 10 +- bot/src/rabbitmq/events/sendMessageEvent.ts | 3 +- bot/src/scripts/cleanupCompletedJobs.ts | 60 +---- bot/src/scripts/deleteRnDAOGuildCommands.ts | 13 +- bot/src/services/airflow.service.ts | 27 +- bot/src/services/channel.service.ts | 22 +- bot/src/services/command.service.ts | 4 +- bot/src/services/event.service.ts | 8 +- bot/src/services/guild.service.ts | 9 +- bot/src/services/interaction.service.ts | 39 +-- bot/src/services/module.service.ts | 4 +- bot/src/services/platform.service.ts | 4 +- bot/src/services/user.service.ts | 21 +- hivemind-adapter/.prettierrc | 2 +- .../src/bot-adapter/bot.adapter.service.ts | 9 +- hivemind-adapter/src/config/app.config.ts | 5 +- hivemind-adapter/src/config/index.ts | 11 +- hivemind-adapter/src/config/logger.config.ts | 4 +- hivemind-adapter/src/config/mongoDB.config.ts | 4 +- hivemind-adapter/src/config/pino.config.ts | 3 +- .../hivemind.adapter.service.ts | 11 +- .../src/platform/platform.module.ts | 6 +- .../src/platform/platform.service.ts | 8 +- 78 files changed, 421 insertions(+), 1430 deletions(-) diff --git a/bot/.prettierrc b/bot/.prettierrc index b3c8e148..f0db82f1 100644 --- a/bot/.prettierrc +++ b/bot/.prettierrc @@ -1,7 +1,7 @@ { - "trailingComma": "es5", - "tabWidth": 4, - "semi": false, - "singleQuote": true, - "printWidth": 80 + "trailingComma": "es5", + "tabWidth": 4, + "semi": false, + "singleQuote": true, + "printWidth": 120 } diff --git a/bot/__tests__/fixtures/channel.fixture.ts b/bot/__tests__/fixtures/channel.fixture.ts index 7074425d..1da7929f 100644 --- a/bot/__tests__/fixtures/channel.fixture.ts +++ b/bot/__tests__/fixtures/channel.fixture.ts @@ -36,11 +36,6 @@ export const channel3: IChannel = { type: 0, } -export const insertChannels = async function ( - channels: Array, - connection: Connection -) { - await connection.models.Channel.insertMany( - channels.map((channel) => channel) - ) +export const insertChannels = async function (channels: Array, connection: Connection) { + await connection.models.Channel.insertMany(channels.map((channel) => channel)) } diff --git a/bot/__tests__/fixtures/role.fixture.ts b/bot/__tests__/fixtures/role.fixture.ts index ca51a01d..7876a29e 100644 --- a/bot/__tests__/fixtures/role.fixture.ts +++ b/bot/__tests__/fixtures/role.fixture.ts @@ -19,9 +19,6 @@ export const role3: IRole = { color: 654321, } -export const insertRoles = async function ( - roles: Array, - connection: Connection -) { +export const insertRoles = async function (roles: Array, connection: Connection) { await connection.models.Role.insertMany(roles.map((role) => role)) } diff --git a/bot/__tests__/unit/database/services/channel.test.ts b/bot/__tests__/unit/database/services/channel.test.ts index 830855d7..9fb8d8b8 100644 --- a/bot/__tests__/unit/database/services/channel.test.ts +++ b/bot/__tests__/unit/database/services/channel.test.ts @@ -1,20 +1,14 @@ import { Connection } from 'mongoose' import { IChannelUpdateBody, DatabaseManager } from '@togethercrew.dev/db' import setupTestDB from '../../../utils/setupTestDB' -import { - channel1, - channel2, - channel3, - insertChannels, -} from '../../../fixtures/channel.fixture' +import { channel1, channel2, channel3, insertChannels } from '../../../fixtures/channel.fixture' import { channelService } from '../../../../src/database/services' setupTestDB() describe('channel service', () => { let connection: Connection beforeAll(async () => { - connection = - await DatabaseManager.getInstance().getGuildDb('connection-1') + connection = await DatabaseManager.getInstance().getGuildDb('connection-1') }) afterAll(async () => { await connection.close() @@ -29,10 +23,7 @@ describe('channel service', () => { }) test('should create a channel', async () => { - const result = await channelService.createChannel( - connection, - channel1 - ) + const result = await channelService.createChannel(connection, channel1) expect(result).toBeDefined() expect(result?.channelId).toEqual(channel1.channelId) @@ -55,10 +46,7 @@ describe('channel service', () => { await connection.collection('channels').deleteMany({}) }) test('should create channels', async () => { - const result = await channelService.createChannels(connection, [ - channel1, - channel2, - ]) + const result = await channelService.createChannels(connection, [channel1, channel2]) expect(result).toMatchObject([channel1, channel2]) const channelDoc1 = await channelService.getChannel(connection, { @@ -137,11 +125,7 @@ describe('channel service', () => { } test('should update an existing channel that match the filter criteria', async () => { await insertChannels([channel1], connection) - const result = await channelService.updateChannel( - connection, - { channelId: channel1.channelId }, - updateBody - ) + const result = await channelService.updateChannel(connection, { channelId: channel1.channelId }, updateBody) expect(result).toMatchObject(updateBody) const channelDoc1 = await channelService.getChannel(connection, { @@ -156,11 +140,7 @@ describe('channel service', () => { }) test('should return null when no channel match the filter criteria', async () => { - const result = await channelService.updateChannel( - connection, - { channelId: channel1.channelId }, - updateBody - ) + const result = await channelService.updateChannel(connection, { channelId: channel1.channelId }, updateBody) expect(result).toEqual(null) }) }) @@ -174,11 +154,7 @@ describe('channel service', () => { } test('should update channels that match the filter criteria', async () => { await insertChannels([channel1, channel2, channel3], connection) - const result = await channelService.updateChannels( - connection, - { parentId: channel2.parentId }, - updateBody - ) + const result = await channelService.updateChannels(connection, { parentId: channel2.parentId }, updateBody) expect(result).toEqual(2) const channelDoc1 = await channelService.getChannel(connection, { channelId: channel2.channelId, @@ -191,11 +167,7 @@ describe('channel service', () => { }) test('should return 0 when no channels match the filter criteria', async () => { - const result = await channelService.updateChannels( - connection, - { parentId: channel2.parentId }, - updateBody - ) + const result = await channelService.updateChannels(connection, { parentId: channel2.parentId }, updateBody) expect(result).toEqual(0) }) }) diff --git a/bot/__tests__/unit/database/services/guildMember.test.ts b/bot/__tests__/unit/database/services/guildMember.test.ts index b85da3bd..622d6538 100644 --- a/bot/__tests__/unit/database/services/guildMember.test.ts +++ b/bot/__tests__/unit/database/services/guildMember.test.ts @@ -1,19 +1,14 @@ import { Connection } from 'mongoose' import { IGuildMemberUpdateBody, DatabaseManager } from '@togethercrew.dev/db' import setupTestDB from '../../../utils/setupTestDB' -import { - guildMember1, - guildMember2, - guildMember3, -} from '../../../fixtures/guildMember.fixture' +import { guildMember1, guildMember2, guildMember3 } from '../../../fixtures/guildMember.fixture' import { guildMemberService } from '../../../../src/database/services' setupTestDB() describe('guildMember service', () => { let connection: Connection beforeAll(async () => { - connection = - await DatabaseManager.getInstance().getGuildDb('connection-2') + connection = await DatabaseManager.getInstance().getGuildDb('connection-2') }) afterAll(async () => { await connection.close() @@ -26,19 +21,13 @@ describe('guildMember service', () => { await connection.collection('guildmembers').deleteMany({}) }) test('should create a guild member', async () => { - const result = await guildMemberService.createGuildMember( - connection, - guildMember1 - ) + const result = await guildMemberService.createGuildMember(connection, guildMember1) expect(result).toBeDefined() expect(result?.discordId).toEqual(guildMember1.discordId) - const guildMemberDoc1 = await guildMemberService.getGuildMember( - connection, - { - discordId: guildMember1.discordId, - } - ) + const guildMemberDoc1 = await guildMemberService.getGuildMember(connection, { + discordId: guildMember1.discordId, + }) expect(guildMemberDoc1).toBeDefined() expect(guildMemberDoc1).toMatchObject({ @@ -53,25 +42,16 @@ describe('guildMember service', () => { await connection.collection('guildmembers').deleteMany({}) }) test('should create guild members', async () => { - const result = await guildMemberService.createGuildMembers( - connection, - [guildMember1, guildMember2] - ) + const result = await guildMemberService.createGuildMembers(connection, [guildMember1, guildMember2]) expect(result).toMatchObject([guildMember1, guildMember2]) - const guildMemberDoc1 = await guildMemberService.getGuildMember( - connection, - { - discordId: guildMember1.discordId, - } - ) + const guildMemberDoc1 = await guildMemberService.getGuildMember(connection, { + discordId: guildMember1.discordId, + }) - const guildMemberDoc2 = await guildMemberService.getGuildMember( - connection, - { - discordId: guildMember2.discordId, - } - ) + const guildMemberDoc2 = await guildMemberService.getGuildMember(connection, { + discordId: guildMember2.discordId, + }) expect(guildMemberDoc1).toBeDefined() expect(guildMemberDoc1).toMatchObject({ @@ -111,32 +91,18 @@ describe('guildMember service', () => { await connection.collection('guildmembers').deleteMany({}) }) test('should retrieve guild members that match the filter criteria', async () => { - await guildMemberService.createGuildMembers(connection, [ - guildMember1, - guildMember2, - guildMember3, - ]) - const result = await guildMemberService.getGuildMembers( - connection, - { - roles: guildMember2.roles, - } - ) + await guildMemberService.createGuildMembers(connection, [guildMember1, guildMember2, guildMember3]) + const result = await guildMemberService.getGuildMembers(connection, { + roles: guildMember2.roles, + }) expect(result).toMatchObject([guildMember1, guildMember2]) }) test('should return an empty array when no guild members match the filter criteria', async () => { - await guildMemberService.createGuildMembers(connection, [ - guildMember1, - guildMember2, - guildMember3, - ]) - const result = await guildMemberService.getGuildMembers( - connection, - { - roles: ['role8'], - } - ) + await guildMemberService.createGuildMembers(connection, [guildMember1, guildMember2, guildMember3]) + const result = await guildMemberService.getGuildMembers(connection, { + roles: ['role8'], + }) expect(result).toEqual([]) }) }) @@ -160,12 +126,9 @@ describe('guildMember service', () => { expect(result).toMatchObject(updateBody) - const guildMember1Doc = await guildMemberService.getGuildMember( - connection, - { - discordId: guildMember1.discordId, - } - ) + const guildMember1Doc = await guildMemberService.getGuildMember(connection, { + discordId: guildMember1.discordId, + }) expect(guildMember1Doc).toBeDefined() expect(guildMember1Doc).toMatchObject({ @@ -176,11 +139,7 @@ describe('guildMember service', () => { }) test('should return null when no guild member match the filter criteria', async () => { - const result = await guildMemberService.updateGuildMember( - connection, - { discordId: '1' }, - updateBody - ) + const result = await guildMemberService.updateGuildMember(connection, { discordId: '1' }, updateBody) expect(result).toEqual(null) }) }) @@ -193,29 +152,19 @@ describe('guildMember service', () => { avatar: 'new-avatar.png', } test('should update guild members that match the filter criteria', async () => { - await guildMemberService.createGuildMembers(connection, [ - guildMember1, - guildMember2, - guildMember3, - ]) + await guildMemberService.createGuildMembers(connection, [guildMember1, guildMember2, guildMember3]) const result = await guildMemberService.updateGuildMembers( connection, { roles: guildMember2.roles }, updateBody ) expect(result).toEqual(2) - const guildMember1Doc = await guildMemberService.getGuildMember( - connection, - { - discordId: guildMember1.discordId, - } - ) - const guildMember2Doc = await guildMemberService.getGuildMember( - connection, - { - discordId: guildMember2.discordId, - } - ) + const guildMember1Doc = await guildMemberService.getGuildMember(connection, { + discordId: guildMember1.discordId, + }) + const guildMember2Doc = await guildMemberService.getGuildMember(connection, { + discordId: guildMember2.discordId, + }) expect(guildMember1Doc?.avatar).toBe(updateBody.avatar) expect(guildMember2Doc?.avatar).toBe(updateBody.avatar) }) @@ -236,22 +185,16 @@ describe('guildMember service', () => { }) test('should delete guild member that match the filter criteria', async () => { await guildMemberService.createGuildMember(connection, guildMember1) - const result = await guildMemberService.deleteGuildMember( - connection, - { - discordId: guildMember1.discordId, - } - ) + const result = await guildMemberService.deleteGuildMember(connection, { + discordId: guildMember1.discordId, + }) expect(result).toEqual(true) }) test('should return false when no guild members match the filter criteria', async () => { - const result = await guildMemberService.deleteGuildMember( - connection, - { - discordId: guildMember1.discordId, - } - ) + const result = await guildMemberService.deleteGuildMember(connection, { + discordId: guildMember1.discordId, + }) expect(result).toEqual(false) }) }) @@ -261,27 +204,17 @@ describe('guildMember service', () => { await connection.collection('guildmembers').deleteMany({}) }) test('should delete guild members that match the filter criteria', async () => { - await guildMemberService.createGuildMembers(connection, [ - guildMember1, - guildMember2, - guildMember3, - ]) - const result = await guildMemberService.deleteGuildMembers( - connection, - { - roles: guildMember2.roles, - } - ) + await guildMemberService.createGuildMembers(connection, [guildMember1, guildMember2, guildMember3]) + const result = await guildMemberService.deleteGuildMembers(connection, { + roles: guildMember2.roles, + }) expect(result).toEqual(2) }) test('should return 0 when no guild members match the filter criteria', async () => { - const result = await guildMemberService.deleteGuildMembers( - connection, - { - roles: guildMember2.roles, - } - ) + const result = await guildMemberService.deleteGuildMembers(connection, { + roles: guildMember2.roles, + }) expect(result).toEqual(0) }) }) diff --git a/bot/__tests__/unit/database/services/rawInfo.test.ts b/bot/__tests__/unit/database/services/rawInfo.test.ts index 84c40e64..326f5282 100644 --- a/bot/__tests__/unit/database/services/rawInfo.test.ts +++ b/bot/__tests__/unit/database/services/rawInfo.test.ts @@ -9,8 +9,7 @@ setupTestDB() describe('rawInfo service', () => { let connection: Connection beforeAll(async () => { - connection = - await DatabaseManager.getInstance().getGuildDb('connection-3') + connection = await DatabaseManager.getInstance().getGuildDb('connection-3') }) afterAll(async () => { await connection.close() @@ -23,10 +22,7 @@ describe('rawInfo service', () => { await connection.collection('rawinfos').deleteMany({}) }) test('should create a rawInfo', async () => { - const result = await rawInfoService.createRawInfo( - connection, - rawInfo1 - ) + const result = await rawInfoService.createRawInfo(connection, rawInfo1) expect(result).toBeDefined() expect(result?.messageId).toEqual(rawInfo1.messageId) @@ -47,11 +43,7 @@ describe('rawInfo service', () => { await connection.collection('rawinfos').deleteMany({}) }) test('should create rawInfos (list of rawInfo)', async () => { - const result = await rawInfoService.createRawInfos(connection, [ - rawInfo1, - rawInfo2, - rawInfo3, - ]) + const result = await rawInfoService.createRawInfos(connection, [rawInfo1, rawInfo2, rawInfo3]) expect(result).toMatchObject([rawInfo1, rawInfo2, rawInfo3]) const rawInfoDoc1 = await rawInfoService.getRawInfo(connection, { @@ -106,11 +98,7 @@ describe('rawInfo service', () => { await connection.collection('rawinfos').deleteMany({}) }) test('should retrieve rawInfo that matches the filter criteria', async () => { - await rawInfoService.createRawInfos(connection, [ - rawInfo1, - rawInfo2, - rawInfo3, - ]) + await rawInfoService.createRawInfos(connection, [rawInfo1, rawInfo2, rawInfo3]) const result = await rawInfoService.getRawInfos(connection, { role_mentions: rawInfo2.role_mentions, }) @@ -119,11 +107,7 @@ describe('rawInfo service', () => { }) test('should return an empty array when no rawInfo matches the filter criteria', async () => { - await rawInfoService.createRawInfos(connection, [ - rawInfo1, - rawInfo2, - rawInfo3, - ]) + await rawInfoService.createRawInfos(connection, [rawInfo1, rawInfo2, rawInfo3]) const result = await rawInfoService.getRawInfos(connection, { role_mentions: ['role8'], }) @@ -143,20 +127,13 @@ describe('rawInfo service', () => { test('should update an existing rawInfo that matches the filter criteria', async () => { await rawInfoService.createRawInfo(connection, rawInfo1) - const result = await rawInfoService.updateRawInfo( - connection, - { messageId: rawInfo1.messageId }, - updateBody - ) + const result = await rawInfoService.updateRawInfo(connection, { messageId: rawInfo1.messageId }, updateBody) expect(result).toMatchObject(updateBody) - const updatedRawInfoDoc = await rawInfoService.getRawInfo( - connection, - { - channelId: updateBody.channelId, - } - ) + const updatedRawInfoDoc = await rawInfoService.getRawInfo(connection, { + channelId: updateBody.channelId, + }) expect(updatedRawInfoDoc).toBeDefined() expect(updatedRawInfoDoc).toMatchObject({ @@ -166,11 +143,7 @@ describe('rawInfo service', () => { }) test('should return null when no rawInfo matches the filter criteria', async () => { - const result = await rawInfoService.updateRawInfo( - connection, - { messageId: rawInfo1.messageId }, - updateBody - ) + const result = await rawInfoService.updateRawInfo(connection, { messageId: rawInfo1.messageId }, updateBody) expect(result).toBeNull() }) }) @@ -185,10 +158,7 @@ describe('rawInfo service', () => { } test('should update rawInfos that match the filter criteria', async () => { - await rawInfoService.createRawInfos(connection, [ - rawInfo1, - rawInfo2, - ]) + await rawInfoService.createRawInfos(connection, [rawInfo1, rawInfo2]) const result = await rawInfoService.updateManyRawInfo( connection, { role_mentions: rawInfo1.role_mentions }, @@ -196,14 +166,8 @@ describe('rawInfo service', () => { ) expect(result).toEqual(2) - const rawInfo1Doc = await rawInfoService.getRawInfo( - connection, - updateBody - ) - const rawInfo2Doc = await rawInfoService.getRawInfo( - connection, - updateBody - ) + const rawInfo1Doc = await rawInfoService.getRawInfo(connection, updateBody) + const rawInfo2Doc = await rawInfoService.getRawInfo(connection, updateBody) expect(rawInfo1Doc).toMatchObject({ channelId: updateBody.channelId, @@ -216,11 +180,7 @@ describe('rawInfo service', () => { }) test('should return 0 when no rawInfos match the filter criteria', async () => { - const result = await rawInfoService.updateManyRawInfo( - connection, - { content: rawInfo3.content }, - updateBody - ) + const result = await rawInfoService.updateManyRawInfo(connection, { content: rawInfo3.content }, updateBody) expect(result).toEqual(0) }) }) @@ -250,11 +210,7 @@ describe('rawInfo service', () => { await connection.collection('rawinfos').deleteMany({}) }) test('should delete rawInfo that matches the filter criteria', async () => { - await rawInfoService.createRawInfos(connection, [ - rawInfo1, - rawInfo2, - rawInfo3, - ]) + await rawInfoService.createRawInfos(connection, [rawInfo1, rawInfo2, rawInfo3]) const result = await rawInfoService.deleteManyRawInfo(connection, { content: rawInfo1.content, }) diff --git a/bot/__tests__/unit/database/services/role.test.ts b/bot/__tests__/unit/database/services/role.test.ts index 52583603..428281a2 100644 --- a/bot/__tests__/unit/database/services/role.test.ts +++ b/bot/__tests__/unit/database/services/role.test.ts @@ -1,20 +1,14 @@ import { Connection } from 'mongoose' import { IRoleUpdateBody, DatabaseManager } from '@togethercrew.dev/db' import setupTestDB from '../../../utils/setupTestDB' -import { - role1, - role2, - role3, - insertRoles, -} from '../../../fixtures/role.fixture' +import { role1, role2, role3, insertRoles } from '../../../fixtures/role.fixture' import { roleService } from '../../../../src/database/services' setupTestDB() describe('role service', () => { let connection: Connection beforeAll(async () => { - connection = - await DatabaseManager.getInstance().getGuildDb('connection-4') + connection = await DatabaseManager.getInstance().getGuildDb('connection-4') }) afterAll(async () => { await connection.close() @@ -49,10 +43,7 @@ describe('role service', () => { await connection.collection('roles').deleteMany({}) }) test('should create roles', async () => { - const result = await roleService.createRoles(connection, [ - role1, - role2, - ]) + const result = await roleService.createRoles(connection, [role1, role2]) expect(result).toMatchObject([role1, role2]) const roleDoc1 = await roleService.getRole(connection, { @@ -129,11 +120,7 @@ describe('role service', () => { } test('should update an existing role that match the filter criteria', async () => { await insertRoles([role1], connection) - const result = await roleService.updateRole( - connection, - { roleId: role1.roleId }, - updateBody - ) + const result = await roleService.updateRole(connection, { roleId: role1.roleId }, updateBody) expect(result).toMatchObject(updateBody) const roleDoc1 = await roleService.getRole(connection, { @@ -148,11 +135,7 @@ describe('role service', () => { }) test('should return null when no role match the filter criteria', async () => { - const result = await roleService.updateRole( - connection, - { roleId: role1.roleId }, - updateBody - ) + const result = await roleService.updateRole(connection, { roleId: role1.roleId }, updateBody) expect(result).toEqual(null) }) }) @@ -166,11 +149,7 @@ describe('role service', () => { } test('should update roles that match the filter criteria', async () => { await insertRoles([role1, role2, role3], connection) - const result = await roleService.updateRoles( - connection, - { color: role2.color }, - updateBody - ) + const result = await roleService.updateRoles(connection, { color: role2.color }, updateBody) expect(result).toEqual(2) const roleDoc1 = await roleService.getRole(connection, { roleId: role2.roleId, @@ -183,11 +162,7 @@ describe('role service', () => { }) test('should return 0 when no roles match the filter criteria', async () => { - const result = await roleService.updateRoles( - connection, - { color: role2.color }, - updateBody - ) + const result = await roleService.updateRoles(connection, { color: role2.color }, updateBody) expect(result).toEqual(0) }) }) diff --git a/bot/__tests__/utils/setupTestDB.ts b/bot/__tests__/utils/setupTestDB.ts index 14cd67b3..e12874d4 100644 --- a/bot/__tests__/utils/setupTestDB.ts +++ b/bot/__tests__/utils/setupTestDB.ts @@ -1,9 +1,6 @@ import mongoose from 'mongoose' import config from '../../src/config' -import RabbitMQ, { - MBConnection, - Queue, -} from '@togethercrew.dev/tc-messagebroker' +import RabbitMQ, { MBConnection, Queue } from '@togethercrew.dev/tc-messagebroker' const setupTestDB = () => { beforeAll(async () => { @@ -13,9 +10,7 @@ const setupTestDB = () => { beforeEach(async () => { await Promise.all( - Object.values(mongoose.connection.collections).map( - async (collection) => collection.deleteMany({}) - ) + Object.values(mongoose.connection.collections).map(async (collection) => collection.deleteMany({})) ) }) diff --git a/bot/src/commands/info/question.ts b/bot/src/commands/info/question.ts index cb7d217d..26071277 100644 --- a/bot/src/commands/info/question.ts +++ b/bot/src/commands/info/question.ts @@ -1,9 +1,6 @@ import { SlashCommandBuilder } from 'discord.js' import { interactionService } from '../../services' -import RabbitMQ, { - Event, - Queue as RabbitMQQueue, -} from '@togethercrew.dev/tc-messagebroker' +import RabbitMQ, { Event, Queue as RabbitMQQueue } from '@togethercrew.dev/tc-messagebroker' import { type ChatInputCommandInteraction_broker } from '../../interfaces/Hivemind.interface' import parentLogger from '../../config/logger' const logger = parentLogger.child({ command: 'question' }) @@ -13,17 +10,11 @@ export default { .setName('question') .setDescription('Ask a question and get an answer from Hivemind!') .addStringOption((option) => - option - .setName('question') - .setDescription('Your question to Hivemind') - .setRequired(true) + option.setName('question').setDescription('Your question to Hivemind').setRequired(true) ), async execute(interaction: ChatInputCommandInteraction_broker) { - logger.info( - { interaction_id: interaction.id, user: interaction.user }, - 'question command started' - ) + logger.info({ interaction_id: interaction.id, user: interaction.user }, 'question command started') try { await interactionService.createInteractionResponse(interaction, { diff --git a/bot/src/config/index.ts b/bot/src/config/index.ts index 891582ec..687bad37 100644 --- a/bot/src/config/index.ts +++ b/bot/src/config/index.ts @@ -3,9 +3,7 @@ import Joi from 'joi' const envVarsSchema = Joi.object() .keys({ - NODE_ENV: Joi.string() - .valid('production', 'development', 'test') - .required(), + NODE_ENV: Joi.string().valid('production', 'development', 'test').required(), DB_HOST: Joi.string().required().description('Mongo DB url'), DB_PORT: Joi.string().required().description('Mongo DB port'), DB_USER: Joi.string().required().description('Mongo DB username'), @@ -14,46 +12,25 @@ const envVarsSchema = Joi.object() RABBIT_HOST: Joi.string().required().description('RabbitMQ url'), RABBIT_PORT: Joi.string().required().description('RabbitMQ port'), RABBIT_USER: Joi.string().required().description('RabbitMQ username'), - RABBIT_PASSWORD: Joi.string() - .required() - .description('RabbitMQ password'), - DISCORD_CLIENT_ID: Joi.string() - .required() - .description('Discord clinet id'), - DISCORD_CLIENT_SECRET: Joi.string() - .required() - .description('Discord clinet secret'), - DISCORD_BOT_TOKEN: Joi.string() - .required() - .description('Discord bot token'), + RABBIT_PASSWORD: Joi.string().required().description('RabbitMQ password'), + DISCORD_CLIENT_ID: Joi.string().required().description('Discord clinet id'), + DISCORD_CLIENT_SECRET: Joi.string().required().description('Discord clinet secret'), + DISCORD_BOT_TOKEN: Joi.string().required().description('Discord bot token'), SENTRY_DSN: Joi.string().required().description('Sentry DSN'), - SENTRY_ENV: Joi.string() - .valid('production', 'development', 'local', 'test') - .required(), + SENTRY_ENV: Joi.string().valid('production', 'development', 'local', 'test').required(), REDIS_HOST: Joi.string().required().description('Reids host'), REDIS_PORT: Joi.string().required().description('Reids port'), - REDIS_PASSWORD: Joi.string() - .required() - .description('Reids password') - .allow(''), + REDIS_PASSWORD: Joi.string().required().description('Reids password').allow(''), LOG_LEVEL: Joi.string().required().description('Min allowed log level'), PORT: Joi.number().default(3000), PYROSCOPE_SERVER_ADDRESS: Joi.string(), - AIRFLOW_BASE_URL: Joi.string() - .required() - .description('Airflow base URL'), - AIRFLOW_USERNAME: Joi.string() - .required() - .description('Airflow username'), - AIRFLOW_PASSWORD: Joi.string() - .required() - .description('Airflow password'), + AIRFLOW_BASE_URL: Joi.string().required().description('Airflow base URL'), + AIRFLOW_USERNAME: Joi.string().required().description('Airflow username'), + AIRFLOW_PASSWORD: Joi.string().required().description('Airflow password'), }) .unknown() -const { value: envVars, error } = envVarsSchema - .prefs({ errors: { label: 'key' } }) - .validate(process.env) +const { value: envVars, error } = envVarsSchema.prefs({ errors: { label: 'key' } }).validate(process.env) if (error != null) { throw new Error(`Config validation error: ${error.message}`) diff --git a/bot/src/config/pyroscope.ts b/bot/src/config/pyroscope.ts index 5a3a6415..aa34fb75 100644 --- a/bot/src/config/pyroscope.ts +++ b/bot/src/config/pyroscope.ts @@ -9,14 +9,8 @@ export default function pyroscope(): void { appName: 'discord', }) Pyroscope.start() - logger.info( - { url: config.pyroscope.address }, - 'Connected to pyroscope.' - ) + logger.info({ url: config.pyroscope.address }, 'Connected to pyroscope.') } catch (error) { - logger.fatal( - { url: config.pyroscope.address, error }, - 'Failed to connect to pyroscope.' - ) + logger.fatal({ url: config.pyroscope.address, error }, 'Failed to connect to pyroscope.') } } diff --git a/bot/src/database/services/channel.service.ts b/bot/src/database/services/channel.service.ts index 573ffebe..fe1d8cc9 100644 --- a/bot/src/database/services/channel.service.ts +++ b/bot/src/database/services/channel.service.ts @@ -1,15 +1,7 @@ /* eslint-disable @typescript-eslint/strict-boolean-expressions */ import { type Connection } from 'mongoose' -import { - type IChannel, - type IChannelMethods, - type IChannelUpdateBody, -} from '@togethercrew.dev/db' -import { - type VoiceChannel, - type TextChannel, - type CategoryChannel, -} from 'discord.js' +import { type IChannel, type IChannelMethods, type IChannelUpdateBody } from '@togethercrew.dev/db' +import { type VoiceChannel, type TextChannel, type CategoryChannel } from 'discord.js' import parentLogger from '../../config/logger' const logger = parentLogger.child({ module: 'ChannelService' }) @@ -20,10 +12,7 @@ const logger = parentLogger.child({ module: 'ChannelService' }) * @param {IChannel} channel - The channel object to be created. * @returns {Promise} - A promise that resolves to the created channel object. */ -async function createChannel( - connection: Connection, - channel: IChannel -): Promise { +async function createChannel(connection: Connection, channel: IChannel): Promise { try { return await connection.models.Channel.create(channel) } catch (error) { @@ -37,10 +26,7 @@ async function createChannel( * @param {IChannel[]} channels - An array of channel objects to be created. * @returns {Promise} - A promise that resolves to an array of the created channel objects. */ -async function createChannels( - connection: Connection, - channels: IChannel[] -): Promise { +async function createChannels(connection: Connection, channels: IChannel[]): Promise { try { return await connection.models.Channel.insertMany(channels, { ordered: false, @@ -56,10 +42,7 @@ async function createChannels( * @param {object} filter - An object specifying the filter criteria to match the desired channel entry. * @returns {Promise} - A promise that resolves to the matching channel object or null if not found. */ -async function getChannel( - connection: Connection, - filter: object -): Promise<(IChannel & IChannelMethods) | null> { +async function getChannel(connection: Connection, filter: object): Promise<(IChannel & IChannelMethods) | null> { return await connection.models.Channel.findOne(filter) } @@ -69,10 +52,7 @@ async function getChannel( * @param {object} filter - An object specifying the filter criteria to match the desired channel entries. * @returns {Promise} - A promise that resolves to an array of the matching channel objects. */ -async function getChannels( - connection: Connection, - filter: object -): Promise { +async function getChannels(connection: Connection, filter: object): Promise { return await connection.models.Channel.find(filter) } @@ -97,10 +77,7 @@ async function updateChannel( await channel.save() return channel } catch (error) { - logger.error( - { database: connection.name, filter, updateBody, error }, - 'Failed to update channel' - ) + logger.error({ database: connection.name, filter, updateBody, error }, 'Failed to update channel') return null } } @@ -112,23 +89,13 @@ async function updateChannel( * @param {IChannelUpdateBody} updateBody - An object containing the updated channel data. * @returns {Promise} - A promise that resolves to the number of updated channel entries. */ -async function updateChannels( - connection: Connection, - filter: object, - updateBody: IChannelUpdateBody -): Promise { +async function updateChannels(connection: Connection, filter: object, updateBody: IChannelUpdateBody): Promise { try { - const updateResult = await connection.models.Channel.updateMany( - filter, - updateBody - ) + const updateResult = await connection.models.Channel.updateMany(filter, updateBody) // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions return updateResult.modifiedCount || 0 } catch (error) { - logger.error( - { database: connection.name, filter, updateBody, error }, - 'Failed to update channels' - ) + logger.error({ database: connection.name, filter, updateBody, error }, 'Failed to update channels') return 0 } } @@ -146,19 +113,12 @@ async function handelChannelChanges( ): Promise { const commonFields = getNeededDateFromChannel(channel) try { - const channelDoc = await updateChannel( - connection, - { channelId: channel.id }, - commonFields - ) + const channelDoc = await updateChannel(connection, { channelId: channel.id }, commonFields) if (!channelDoc) { await createChannel(connection, commonFields) } } catch (error) { - logger.error( - { guild_id: connection.name, channel_id: channel.id, error }, - 'Failed to handle channel changes' - ) + logger.error({ guild_id: connection.name, channel_id: channel.id, error }, 'Failed to handle channel changes') } } @@ -167,16 +127,12 @@ async function handelChannelChanges( * @param {TextChannel | VoiceChannel | CategoryChannel} channel - The Discord.js Channel object containing the full channel details. * @returns {IChannel} - The extracted data in the form of an IChannel object. */ -function getNeededDateFromChannel( - channel: TextChannel | VoiceChannel | CategoryChannel -): IChannel { +function getNeededDateFromChannel(channel: TextChannel | VoiceChannel | CategoryChannel): IChannel { return { channelId: channel.id, name: channel.name, // cast to TextChannel for 'name' parentId: channel.parentId, - permissionOverwrites: Array.from( - channel.permissionOverwrites.cache.values() - ).map((overwrite) => ({ + permissionOverwrites: Array.from(channel.permissionOverwrites.cache.values()).map((overwrite) => ({ id: overwrite.id, type: overwrite.type, allow: overwrite.allow.bitfield.toString(), diff --git a/bot/src/database/services/guildMember.service.ts b/bot/src/database/services/guildMember.service.ts index e8075783..5c438955 100644 --- a/bot/src/database/services/guildMember.service.ts +++ b/bot/src/database/services/guildMember.service.ts @@ -1,9 +1,5 @@ import { type Connection } from 'mongoose' -import { - type IGuildMember, - type IGuildMemberMethods, - type IGuildMemberUpdateBody, -} from '@togethercrew.dev/db' +import { type IGuildMember, type IGuildMemberMethods, type IGuildMemberUpdateBody } from '@togethercrew.dev/db' import { type GuildMember } from 'discord.js' import parentLogger from '../../config/logger' @@ -14,10 +10,7 @@ const logger = parentLogger.child({ module: 'GuildMemberService' }) * @param {IGuildMember} guildMember - The guild member object to be created. * @returns {Promise} - A promise that resolves to the created guild member object. */ -async function createGuildMember( - connection: Connection, - guildMember: IGuildMember -): Promise { +async function createGuildMember(connection: Connection, guildMember: IGuildMember): Promise { try { return await connection.models.GuildMember.create(guildMember) } catch (error) { @@ -31,10 +24,7 @@ async function createGuildMember( * @param {IGuildMember[]} guildMembers - An array of guild member objects to be created. * @returns {Promise} - A promise that resolves to an array of the created guild member objects. */ -async function createGuildMembers( - connection: Connection, - guildMembers: IGuildMember[] -): Promise { +async function createGuildMembers(connection: Connection, guildMembers: IGuildMember[]): Promise { try { return await connection.models.GuildMember.insertMany(guildMembers, { ordered: false, @@ -64,10 +54,7 @@ async function getGuildMember( * @param {object} filter - An object specifying the filter criteria to match the desired guild member entries. * @returns {Promise} - A promise that resolves to an array of the matching guild member objects. */ -async function getGuildMembers( - connection: Connection, - filter: object -): Promise { +async function getGuildMembers(connection: Connection, filter: object): Promise { return await connection.models.GuildMember.find(filter) } @@ -92,10 +79,7 @@ async function updateGuildMember( await guildMember.save() return guildMember } catch (error) { - logger.error( - { database: connection.name, filter, updateBody, error }, - 'Failed to update guild member' - ) + logger.error({ database: connection.name, filter, updateBody, error }, 'Failed to update guild member') return null } } @@ -113,17 +97,11 @@ async function updateGuildMembers( updateBody: IGuildMemberUpdateBody ): Promise { try { - const updateResult = await connection.models.GuildMember.updateMany( - filter, - updateBody - ) + const updateResult = await connection.models.GuildMember.updateMany(filter, updateBody) // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions return updateResult.modifiedCount || 0 } catch (error) { - logger.error( - { database: connection.name, filter, updateBody, error }, - 'Failed to update guild members' - ) + logger.error({ database: connection.name, filter, updateBody, error }, 'Failed to update guild members') return 0 } } @@ -134,19 +112,12 @@ async function updateGuildMembers( * @param {object} filter - An object specifying the filter criteria to match the desired guild member entry for deletion. * @returns {Promise} - A promise that resolves to true if the guild member was successfully deleted, or false otherwise. */ -async function deleteGuildMember( - connection: Connection, - filter: object -): Promise { +async function deleteGuildMember(connection: Connection, filter: object): Promise { try { - const deleteResult = - await connection.models.GuildMember.deleteOne(filter) + const deleteResult = await connection.models.GuildMember.deleteOne(filter) return deleteResult.deletedCount === 1 } catch (error) { - logger.error( - { database: connection.name, filter, error }, - 'Failed to delete guild member' - ) + logger.error({ database: connection.name, filter, error }, 'Failed to delete guild member') return false } } @@ -157,19 +128,12 @@ async function deleteGuildMember( * @param {object} filter - An object specifying the filter criteria to match multiple guild member entries for deletion. * @returns {Promise} - A promise that resolves to the number of deleted guild member entries. */ -async function deleteGuildMembers( - connection: Connection, - filter: object -): Promise { +async function deleteGuildMembers(connection: Connection, filter: object): Promise { try { - const deleteResult = - await connection.models.GuildMember.deleteMany(filter) + const deleteResult = await connection.models.GuildMember.deleteMany(filter) return deleteResult.deletedCount } catch (error) { - logger.error( - { database: connection.name, filter, error }, - 'Failed to delete guild members' - ) + logger.error({ database: connection.name, filter, error }, 'Failed to delete guild members') return 0 } } @@ -181,17 +145,10 @@ async function deleteGuildMembers( * @returns {Promise} - A promise that resolves when the create or update operation is complete. * */ -async function handelGuildMemberChanges( - connection: Connection, - guildMember: GuildMember -): Promise { +async function handelGuildMemberChanges(connection: Connection, guildMember: GuildMember): Promise { const commonFields = getNeededDateFromGuildMember(guildMember) try { - const guildMemberDoc = await updateGuildMember( - connection, - { discordId: guildMember.user.id }, - commonFields - ) + const guildMemberDoc = await updateGuildMember(connection, { discordId: guildMember.user.id }, commonFields) if (guildMemberDoc === null) { await createGuildMember(connection, { ...commonFields, @@ -236,10 +193,7 @@ function getNeededDateFromGuildMember(guildMember: GuildMember): IGuildMember { * @param {object} filter - An object specifying the filter criteria to match the desired rawInfo entry. * @returns {Promise} - A promise that resolves to the oldest rawInfo object for the channel, or null if not found. */ -async function getLatestGuildMember( - connection: Connection, - filter: object -): Promise { +async function getLatestGuildMember(connection: Connection, filter: object): Promise { return await connection.models.GuildMember.findOne(filter).sort({ _id: -1, }) diff --git a/bot/src/database/services/index.ts b/bot/src/database/services/index.ts index 3105c173..2e6c8759 100644 --- a/bot/src/database/services/index.ts +++ b/bot/src/database/services/index.ts @@ -3,10 +3,4 @@ import rawInfoService from './rawInfo.service' import platformService from './platform.service' import roleService from './role.service' import channelService from './channel.service' -export { - guildMemberService, - platformService, - rawInfoService, - roleService, - channelService, -} +export { guildMemberService, platformService, rawInfoService, roleService, channelService } diff --git a/bot/src/database/services/platform.service.ts b/bot/src/database/services/platform.service.ts index d7c7c29b..aff65937 100644 --- a/bot/src/database/services/platform.service.ts +++ b/bot/src/database/services/platform.service.ts @@ -1,9 +1,5 @@ import { type HydratedDocument } from 'mongoose' -import { - Platform, - type IPlatform, - type IPlatformUpdateBody, -} from '@togethercrew.dev/db' +import { Platform, type IPlatform, type IPlatformUpdateBody } from '@togethercrew.dev/db' import { type Snowflake } from 'discord.js' import { coreService } from '../../services' import parentLogger from '../../config/logger' @@ -15,9 +11,7 @@ const logger = parentLogger.child({ module: 'PlatformService' }) * @param {Object} filter * @returns {Promise} */ -async function getPlatform( - filter: object -): Promise | null> { +async function getPlatform(filter: object): Promise | null> { return await Platform.findOne(filter) } @@ -26,9 +20,7 @@ async function getPlatform( * @param {object} filter - Filter criteria to match the desired platform entries. * @returns {Promise} - A promise that resolves to an array of matching platform entries. */ -async function getPlatforms( - filter: object -): Promise>> { +async function getPlatforms(filter: object): Promise>> { return await Platform.find(filter) } @@ -60,10 +52,7 @@ async function updatePlatform( await platform.save() return platform } catch (error) { - logger.error( - { database: 'Core', filter, updateBody, error }, - 'Failed to update platform' - ) + logger.error({ database: 'Core', filter, updateBody, error }, 'Failed to update platform') return null } } @@ -74,19 +63,13 @@ async function updatePlatform( * @param {IPlatformUpdateBody} updateBody - Updated information for the platform entry. * @returns {Promise} - A promise that resolves to the number of platform entries updated. */ -async function updateManyPlatforms( - filter: object, - updateBody: IPlatformUpdateBody -): Promise { +async function updateManyPlatforms(filter: object, updateBody: IPlatformUpdateBody): Promise { try { const updateResult = await Platform.updateMany(filter, updateBody) const modifiedCount = updateResult.modifiedCount return modifiedCount } catch (error) { - logger.error( - { database: 'Core', filter, updateBody, error }, - 'Failed to update platforms' - ) + logger.error({ database: 'Core', filter, updateBody, error }, 'Failed to update platforms') return 0 } } diff --git a/bot/src/database/services/rawInfo.service.ts b/bot/src/database/services/rawInfo.service.ts index d35ae7b1..bc249e79 100644 --- a/bot/src/database/services/rawInfo.service.ts +++ b/bot/src/database/services/rawInfo.service.ts @@ -10,10 +10,7 @@ const logger = parentLogger.child({ module: 'rawInfoService' }) * @param {IRawInfo} rawInfo - The rawInfo object to be created. * @returns {Promise} - A promise that resolves to the created rawInfo object. */ -async function createRawInfo( - connection: Connection, - rawInfo: IRawInfo -): Promise { +async function createRawInfo(connection: Connection, rawInfo: IRawInfo): Promise { try { return await connection.models.RawInfo.create(rawInfo) } catch (error) { @@ -27,19 +24,13 @@ async function createRawInfo( * @param {IRawInfo[]} rawInfos - An array of rawInfo objects to be created. * @returns {Promise} - A promise that resolves to an array of the created rawInfo objects. */ -async function createRawInfos( - connection: Connection, - rawInfos: IRawInfo[] -): Promise { +async function createRawInfos(connection: Connection, rawInfos: IRawInfo[]): Promise { try { return await connection.models.RawInfo.insertMany(rawInfos, { ordered: false, }) } catch (error) { - logger.error( - { database: connection.name, error }, - 'Failed to create rawInfos' - ) + logger.error({ database: connection.name, error }, 'Failed to create rawInfos') return [] } } @@ -50,10 +41,7 @@ async function createRawInfos( * @param {object} filter - An object specifying the filter criteria to match the desired rawInfo entry. * @returns {Promise} - A promise that resolves to the matching rawInfo object or null if not found. */ -async function getRawInfo( - connection: Connection, - filter: object -): Promise { +async function getRawInfo(connection: Connection, filter: object): Promise { return await connection.models.RawInfo.findOne(filter) } @@ -63,10 +51,7 @@ async function getRawInfo( * @param {object} filter - An object specifying the filter criteria to match the desired rawInfo entries. * @returns {Promise} - A promise that resolves to an array of the matching rawInfo objects. */ -async function getRawInfos( - connection: Connection, - filter: object -): Promise { +async function getRawInfos(connection: Connection, filter: object): Promise { return await connection.models.RawInfo.find(filter) } @@ -91,10 +76,7 @@ async function updateRawInfo( await rawInfo.save() return rawInfo } catch (error) { - logger.error( - { database: connection.name, filter, updateBody, error }, - 'Failed to update rawInfo' - ) + logger.error({ database: connection.name, filter, updateBody, error }, 'Failed to update rawInfo') return null } } @@ -112,16 +94,10 @@ async function updateManyRawInfo( updateBody: IRawInfoUpdateBody ): Promise { try { - const updateResult = await connection.models.RawInfo.updateMany( - filter, - updateBody - ) + const updateResult = await connection.models.RawInfo.updateMany(filter, updateBody) return updateResult.modifiedCount || 0 } catch (error) { - logger.error( - { database: connection.name, filter, updateBody, error }, - 'Failed to update rawInfos' - ) + logger.error({ database: connection.name, filter, updateBody, error }, 'Failed to update rawInfos') return 0 } } @@ -132,18 +108,12 @@ async function updateManyRawInfo( * @param {object} filter - An object specifying the filter criteria to match the desired rawInfo entry for deletion. * @returns {Promise} - A promise that resolves to true if the rawInfo entry was successfully deleted, or false otherwise. */ -async function deleteRawInfo( - connection: Connection, - filter: object -): Promise { +async function deleteRawInfo(connection: Connection, filter: object): Promise { try { const deleteResult = await connection.models.RawInfo.deleteOne(filter) return deleteResult.deletedCount === 1 } catch (error) { - logger.error( - { database: connection.name, filter, error }, - 'Failed to delete rawInfo' - ) + logger.error({ database: connection.name, filter, error }, 'Failed to delete rawInfo') return false } } @@ -155,18 +125,12 @@ async function deleteRawInfo( * @returns {Promise} - A promise that resolves to the number of deleted rawInfo entries. * @throws {Error} - If there is an error while deleting the rawInfo entries. */ -async function deleteManyRawInfo( - connection: Connection, - filter: object -): Promise { +async function deleteManyRawInfo(connection: Connection, filter: object): Promise { try { const deleteResult = await connection.models.RawInfo.deleteMany(filter) return deleteResult.deletedCount } catch (error) { - logger.error( - { database: connection.name, filter, error }, - 'Failed to delete rawInfos' - ) + logger.error({ database: connection.name, filter, error }, 'Failed to delete rawInfos') return 0 } } @@ -177,10 +141,7 @@ async function deleteManyRawInfo( * @param {object} filter - An object specifying the filter criteria to match the desired rawInfo entry. * @returns {Promise} - A promise that resolves to the oldest rawInfo object for the channel, or null if not found. */ -async function getNewestRawInfo( - connection: Connection, - filter: object -): Promise { +async function getNewestRawInfo(connection: Connection, filter: object): Promise { return await connection.models.RawInfo.findOne(filter).sort({ createdDate: -1, }) @@ -192,10 +153,7 @@ async function getNewestRawInfo( * @param {object} filter - An object specifying the filter criteria to match the desired rawInfo entry. * @returns {Promise} - A promise that resolves to the oldest rawInfo object for the channel, or null if not found. */ -async function getOldestRawInfo( - connection: Connection, - filter: object -): Promise { +async function getOldestRawInfo(connection: Connection, filter: object): Promise { return await connection.models.RawInfo.findOne(filter).sort({ createdDate: 1, }) diff --git a/bot/src/database/services/role.service.ts b/bot/src/database/services/role.service.ts index 1b3943b0..f6b5fd6a 100644 --- a/bot/src/database/services/role.service.ts +++ b/bot/src/database/services/role.service.ts @@ -1,10 +1,6 @@ /* eslint-disable @typescript-eslint/strict-boolean-expressions */ import { type Connection } from 'mongoose' -import { - type IRole, - type IRoleMethods, - type IRoleUpdateBody, -} from '@togethercrew.dev/db' +import { type IRole, type IRoleMethods, type IRoleUpdateBody } from '@togethercrew.dev/db' import { type Role } from 'discord.js' import parentLogger from '../../config/logger' @@ -15,10 +11,7 @@ const logger = parentLogger.child({ module: 'roleService' }) * @param {IRole} role - The role object to be created. * @returns {Promise} - A promise that resolves to the created role object. */ -async function createRole( - connection: Connection, - role: IRole -): Promise { +async function createRole(connection: Connection, role: IRole): Promise { try { return await connection.models.Role.create(role) } catch (error) { @@ -32,10 +25,7 @@ async function createRole( * @param {IRole[]} roles - An array of role objects to be created. * @returns {Promise} - A promise that resolves to an array of the created role objects. */ -async function createRoles( - connection: Connection, - roles: IRole[] -): Promise { +async function createRoles(connection: Connection, roles: IRole[]): Promise { try { return await connection.models.Role.insertMany(roles, { ordered: false, @@ -51,10 +41,7 @@ async function createRoles( * @param {object} filter - An object specifying the filter criteria to match the desired role entry. * @returns {Promise} - A promise that resolves to the matching role object or null if not found. */ -async function getRole( - connection: Connection, - filter: object -): Promise<(IRole & IRoleMethods) | null> { +async function getRole(connection: Connection, filter: object): Promise<(IRole & IRoleMethods) | null> { return await connection.models.Role.findOne(filter) } @@ -64,10 +51,7 @@ async function getRole( * @param {object} filter - An object specifying the filter criteria to match the desired role entries. * @returns {Promise} - A promise that resolves to an array of the matching role objects. */ -async function getRoles( - connection: Connection, - filter: object -): Promise { +async function getRoles(connection: Connection, filter: object): Promise { return await connection.models.Role.find(filter) } @@ -78,11 +62,7 @@ async function getRoles( * @param {IRoleUpdateBody} updateBody - An object containing the updated role data. * @returns {Promise} - A promise that resolves to the updated role object or null if not found. */ -async function updateRole( - connection: Connection, - filter: object, - updateBody: IRoleUpdateBody -): Promise { +async function updateRole(connection: Connection, filter: object, updateBody: IRoleUpdateBody): Promise { try { const role = await connection.models.Role.findOne(filter) if (role === null) { @@ -92,10 +72,7 @@ async function updateRole( await role.save() return role } catch (error) { - logger.error( - { database: connection.name, filter, updateBody, error }, - 'Failed to update role' - ) + logger.error({ database: connection.name, filter, updateBody, error }, 'Failed to update role') return null } } @@ -107,22 +84,12 @@ async function updateRole( * @param {IRoleUpdateBody} updateBody - An object containing the updated role data. * @returns {Promise} - A promise that resolves to the number of updated role entries. */ -async function updateRoles( - connection: Connection, - filter: object, - updateBody: IRoleUpdateBody -): Promise { +async function updateRoles(connection: Connection, filter: object, updateBody: IRoleUpdateBody): Promise { try { - const updateResult = await connection.models.Role.updateMany( - filter, - updateBody - ) + const updateResult = await connection.models.Role.updateMany(filter, updateBody) return updateResult.modifiedCount || 0 } catch (error) { - logger.error( - { database: connection.name, filter, updateBody, error }, - 'Failed to update roles' - ) + logger.error({ database: connection.name, filter, updateBody, error }, 'Failed to update roles') return 0 } } @@ -134,25 +101,15 @@ async function updateRoles( * @returns {Promise} - A promise that resolves when the create or update operation is complete. * */ -async function handelRoleChanges( - connection: Connection, - role: Role -): Promise { +async function handelRoleChanges(connection: Connection, role: Role): Promise { const commonFields = getNeededDateFromRole(role) try { - const roleDoc = await updateRole( - connection, - { roleId: role.id }, - commonFields - ) + const roleDoc = await updateRole(connection, { roleId: role.id }, commonFields) if (roleDoc === null) { await createRole(connection, commonFields) } } catch (error) { - logger.error( - { guild_id: connection.name, role_id: role.id, error }, - 'Failed to handle role changes' - ) + logger.error({ guild_id: connection.name, role_id: role.id, error }, 'Failed to handle role changes') } } diff --git a/bot/src/events/channel/channelCreate.ts b/bot/src/events/channel/channelCreate.ts index 83c180ae..375c22d0 100644 --- a/bot/src/events/channel/channelCreate.ts +++ b/bot/src/events/channel/channelCreate.ts @@ -1,10 +1,4 @@ -import { - Events, - type Channel, - TextChannel, - VoiceChannel, - CategoryChannel, -} from 'discord.js' +import { Events, type Channel, TextChannel, VoiceChannel, CategoryChannel } from 'discord.js' import { addGuildEventQueue } from '../../queue/queues/guildEvent' import { channelService } from '../../database/services' @@ -12,11 +6,7 @@ export default { name: Events.ChannelCreate, once: false, execute(channel: Channel) { - if ( - channel instanceof TextChannel || - channel instanceof VoiceChannel || - channel instanceof CategoryChannel - ) { + if (channel instanceof TextChannel || channel instanceof VoiceChannel || channel instanceof CategoryChannel) { const dataToStore = channelService.getNeededDateFromChannel(channel) addGuildEventQueue({ type: Events.ChannelCreate, diff --git a/bot/src/events/channel/channelDelete.ts b/bot/src/events/channel/channelDelete.ts index 002a5ebc..789d2721 100644 --- a/bot/src/events/channel/channelDelete.ts +++ b/bot/src/events/channel/channelDelete.ts @@ -1,21 +1,11 @@ -import { - Events, - type Channel, - TextChannel, - VoiceChannel, - CategoryChannel, -} from 'discord.js' +import { Events, type Channel, TextChannel, VoiceChannel, CategoryChannel } from 'discord.js' import { addGuildEventQueue } from '../../queue/queues/guildEvent' export default { name: Events.ChannelDelete, once: false, execute(channel: Channel) { - if ( - channel instanceof TextChannel || - channel instanceof VoiceChannel || - channel instanceof CategoryChannel - ) { + if (channel instanceof TextChannel || channel instanceof VoiceChannel || channel instanceof CategoryChannel) { addGuildEventQueue({ type: Events.ChannelDelete, guildId: channel.guildId, diff --git a/bot/src/events/channel/channelUpdate.ts b/bot/src/events/channel/channelUpdate.ts index 051c24b5..8fe4fcb0 100644 --- a/bot/src/events/channel/channelUpdate.ts +++ b/bot/src/events/channel/channelUpdate.ts @@ -1,10 +1,4 @@ -import { - Events, - type Channel, - TextChannel, - VoiceChannel, - CategoryChannel, -} from 'discord.js' +import { Events, type Channel, TextChannel, VoiceChannel, CategoryChannel } from 'discord.js' import { addGuildEventQueue } from '../../queue/queues/guildEvent' import { channelService } from '../../database/services' @@ -17,8 +11,7 @@ export default { newChannel instanceof VoiceChannel || newChannel instanceof CategoryChannel ) { - const dataToStore = - channelService.getNeededDateFromChannel(newChannel) + const dataToStore = channelService.getNeededDateFromChannel(newChannel) addGuildEventQueue({ type: Events.ChannelUpdate, guildId: newChannel.guildId, diff --git a/bot/src/events/guild/guildCreate.ts b/bot/src/events/guild/guildCreate.ts index d9ef5e1d..6e5a4f49 100644 --- a/bot/src/events/guild/guildCreate.ts +++ b/bot/src/events/guild/guildCreate.ts @@ -7,8 +7,7 @@ export default { once: false, async execute(guild: Guild) { const botMember = await guild.members.fetch(config.discord.clientId) - const dataToStore = - guildMemberService.getNeededDateFromGuildMember(botMember) + const dataToStore = guildMemberService.getNeededDateFromGuildMember(botMember) addGuildEventQueue({ type: Events.GuildMemberUpdate, guildId: botMember.guild.id, diff --git a/bot/src/events/member/guildMemberAdd.ts b/bot/src/events/member/guildMemberAdd.ts index 2efc0454..4a95213e 100644 --- a/bot/src/events/member/guildMemberAdd.ts +++ b/bot/src/events/member/guildMemberAdd.ts @@ -6,8 +6,7 @@ export default { name: Events.GuildMemberAdd, once: false, execute(member: GuildMember) { - const dataToStore = - guildMemberService.getNeededDateFromGuildMember(member) + const dataToStore = guildMemberService.getNeededDateFromGuildMember(member) addGuildEventQueue({ type: Events.GuildMemberAdd, guildId: member.guild.id, diff --git a/bot/src/events/member/guildMemberUpdate.ts b/bot/src/events/member/guildMemberUpdate.ts index 347ddc55..2c5f3100 100644 --- a/bot/src/events/member/guildMemberUpdate.ts +++ b/bot/src/events/member/guildMemberUpdate.ts @@ -6,8 +6,7 @@ export default { name: Events.GuildMemberUpdate, once: false, execute(oldMember: GuildMember, newMember: GuildMember) { - const dataToStore = - guildMemberService.getNeededDateFromGuildMember(newMember) + const dataToStore = guildMemberService.getNeededDateFromGuildMember(newMember) addGuildEventQueue({ type: Events.GuildMemberUpdate, guildId: newMember.guild.id, diff --git a/bot/src/functions/cronJon.ts b/bot/src/functions/cronJon.ts index 7ff427d2..b904486a 100644 --- a/bot/src/functions/cronJon.ts +++ b/bot/src/functions/cronJon.ts @@ -16,20 +16,11 @@ export default async function cronJob(): Promise { }) for (let i = 0; i < platforms.length; i++) { try { - logger.info( - { platform_Id: platforms[i].metadata?.id }, - 'is running cronJob for platform' - ) + logger.info({ platform_Id: platforms[i].metadata?.id }, 'is running cronJob for platform') addGuildExtraction(platforms[i], false) - logger.info( - { platform_Id: platforms[i].metadata?.id }, - 'cronJob is done for platform' - ) + logger.info({ platform_Id: platforms[i].metadata?.id }, 'cronJob is done for platform') } catch (err) { - logger.error( - { platform_Id: platforms[i].metadata?.id, err }, - 'CronJob Failed for platform' - ) + logger.error({ platform_Id: platforms[i].metadata?.id, err }, 'CronJob Failed for platform') } } logger.info('event is done') diff --git a/bot/src/functions/fetchChannels.ts b/bot/src/functions/fetchChannels.ts index 5000ac3c..bc5bc8b8 100644 --- a/bot/src/functions/fetchChannels.ts +++ b/bot/src/functions/fetchChannels.ts @@ -13,15 +13,10 @@ const logger = parentLogger.child({ module: 'FetchChannels' }) * @param {Snowflake} guildId - The identifier of the guild to extract text and voice channels from. */ // eslint-disable-next-line @typescript-eslint/explicit-function-return-type -export default async function fetchGuildChannels( - connection: Connection, - platform: HydratedDocument -) { +export default async function fetchGuildChannels(connection: Connection, platform: HydratedDocument) { try { const client = await coreService.DiscordBotManager.getClient() - const hasBotAccessToGuild = await platformService.checkBotAccessToGuild( - platform.metadata?.id - ) + const hasBotAccessToGuild = await platformService.checkBotAccessToGuild(platform.metadata?.id) if (!hasBotAccessToGuild) { return } @@ -30,23 +25,12 @@ export default async function fetchGuildChannels( logger.info({ guild_id: platform.metadata?.id }, 'Fetching channels') const fetchedChannels = await guild.channels.fetch() const filterNeededChannels = [...fetchedChannels.values()].filter( - (channel) => - channel?.type === 0 || - channel?.type === 2 || - channel?.type === 4 + (channel) => channel?.type === 0 || channel?.type === 2 || channel?.type === 4 ) as Array - channelsToStore = filterNeededChannels.map( - channelService.getNeededDateFromChannel - ) + channelsToStore = filterNeededChannels.map(channelService.getNeededDateFromChannel) await channelService.createChannels(connection, channelsToStore) - logger.info( - { guild_id: platform.metadata?.id }, - 'Channels stored successfully' - ) + logger.info({ guild_id: platform.metadata?.id }, 'Channels stored successfully') } catch (error) { - logger.error( - { guild_id: platform.metadata?.id, error }, - 'Failed to fetch channels' - ) + logger.error({ guild_id: platform.metadata?.id, error }, 'Failed to fetch channels') } } diff --git a/bot/src/functions/fetchMembers.ts b/bot/src/functions/fetchMembers.ts index cc3994ba..7b50370d 100644 --- a/bot/src/functions/fetchMembers.ts +++ b/bot/src/functions/fetchMembers.ts @@ -16,10 +16,7 @@ const CHUNK_SIZE = 1000 * @param {Connection} connection - Mongoose connection object for the database. * @returns {Promise} - A promise that resolves when all members are fetched and stored. */ -async function fetchMembersInChunks( - guild: Guild, - connection: Connection -): Promise { +async function fetchMembersInChunks(guild: Guild, connection: Connection): Promise { let lastMemberId: Snowflake | undefined // TODO: fetch after latest stored guild member @@ -37,9 +34,7 @@ async function fetchMembersInChunks( break } - const membersToStore: IGuildMember[] = fetchedMembers.map( - guildMemberService.getNeededDateFromGuildMember - ) + const membersToStore: IGuildMember[] = fetchedMembers.map(guildMemberService.getNeededDateFromGuildMember) await guildMemberService.createGuildMembers(connection, membersToStore) @@ -62,27 +57,16 @@ export default async function fetchGuildMembers( ): Promise { try { const client = await coreService.DiscordBotManager.getClient() - const hasBotAccessToGuild = await platformService.checkBotAccessToGuild( - platform.metadata?.id - ) + const hasBotAccessToGuild = await platformService.checkBotAccessToGuild(platform.metadata?.id) if (!hasBotAccessToGuild) { - logger.info( - { guild_id: platform.metadata?.id }, - 'Bot access missing' - ) + logger.info({ guild_id: platform.metadata?.id }, 'Bot access missing') return } const guild = await client.guilds.fetch(platform.metadata?.id) logger.info({ guild_id: platform.metadata?.id }, 'Fetching members') await fetchMembersInChunks(guild, connection) - logger.info( - { guild_id: platform.metadata?.id }, - 'Members stored successfully' - ) + logger.info({ guild_id: platform.metadata?.id }, 'Members stored successfully') } catch (error) { - logger.error( - { guild_id: platform.metadata?.id, error }, - 'Failed to fetch guild members' - ) + logger.error({ guild_id: platform.metadata?.id, error }, 'Failed to fetch guild members') } } diff --git a/bot/src/functions/fetchMessages.ts b/bot/src/functions/fetchMessages.ts index 9be25210..2689e2d5 100644 --- a/bot/src/functions/fetchMessages.ts +++ b/bot/src/functions/fetchMessages.ts @@ -2,19 +2,8 @@ /* eslint-disable no-unneeded-ternary */ /* eslint-disable @typescript-eslint/strict-boolean-expressions */ import fetch from 'node-fetch' -import { - type Message, - TextChannel, - type User, - type Role, - ThreadChannel, - type Snowflake, -} from 'discord.js' -import { - type IRawInfo, - type IPlatform, - type IDiscordUser, -} from '@togethercrew.dev/db' +import { type Message, TextChannel, type User, type Role, ThreadChannel, type Snowflake } from 'discord.js' +import { type IRawInfo, type IPlatform, type IDiscordUser } from '@togethercrew.dev/db' import { rawInfoService, platformService } from '../database/services' import { type Connection, type HydratedDocument } from 'mongoose' import { guildService, channelService } from '../services' @@ -72,11 +61,7 @@ async function getReactions(message: Message): Promise { continue } - const users = await fetchAllUsersForReaction( - channelId, - messageId, - encodedEmoji - ) + const users = await fetchAllUsersForReaction(channelId, messageId, encodedEmoji) const usersString = users.map((user) => `${user.id}`).join(',') // eslint-disable-next-line @typescript-eslint/restrict-template-expressions reactionsArr.push(`${usersString},${emoji.name}`) @@ -140,10 +125,7 @@ async function fetchAllUsersForReaction( continue } else { const errorText = await response.text() - logger.error( - { channelId, messageId, errorText }, - 'Error fetching users for reaction' - ) + logger.error({ channelId, messageId, errorText }, 'Error fetching users for reaction') hasMore = false } } @@ -156,10 +138,7 @@ async function fetchAllUsersForReaction( * @param {threadInfo} threadInfo - An optional thread info object containing details about the thread the message is part of. * @returns {Promise} - A promise that resolves to an object of type IRawInfo containing the extracted data. */ -async function getNeedDataFromMessage( - message: Message, - threadInfo?: threadInfo -): Promise { +async function getNeedDataFromMessage(message: Message, threadInfo?: threadInfo): Promise { if (threadInfo) { return { type: message.type, @@ -168,8 +147,7 @@ async function getNeedDataFromMessage( createdDate: message.createdAt, role_mentions: message.mentions.roles.map((role: Role) => role.id), user_mentions: message.mentions.users.map((user: User) => user.id), - replied_user: - message.type === 19 ? message.mentions.repliedUser?.id : null, + replied_user: message.type === 19 ? message.mentions.repliedUser?.id : null, reactions: await getReactions(message), messageId: message.id, channelId: threadInfo?.channelId ? threadInfo?.channelId : '', @@ -186,15 +164,11 @@ async function getNeedDataFromMessage( createdDate: message.createdAt, role_mentions: message.mentions.roles.map((role: Role) => role.id), user_mentions: message.mentions.users.map((user: User) => user.id), - replied_user: - message.type === 19 ? message.mentions.repliedUser?.id : null, + replied_user: message.type === 19 ? message.mentions.repliedUser?.id : null, reactions: await getReactions(message), messageId: message.id, channelId: message.channelId, - channelName: - message.channel instanceof TextChannel - ? message.channel.name - : null, + channelName: message.channel instanceof TextChannel ? message.channel.name : null, threadId: null, threadName: null, isGeneratedByWebhook: message.webhookId ? true : false, @@ -259,51 +233,29 @@ async function fetchMessages( let fetchedMessages = await channel.messages.fetch(options) while (fetchedMessages.size > 0) { - const boundaryMessage = - fetchDirection === 'before' - ? fetchedMessages.last() - : fetchedMessages.first() - if ( - !boundaryMessage || - (period && boundaryMessage.createdAt < period) - ) { + const boundaryMessage = fetchDirection === 'before' ? fetchedMessages.last() : fetchedMessages.first() + if (!boundaryMessage || (period && boundaryMessage.createdAt < period)) { if (period) { - fetchedMessages = fetchedMessages.filter( - (msg) => msg.createdAt > period - ) + fetchedMessages = fetchedMessages.filter((msg) => msg.createdAt > period) } channel instanceof ThreadChannel - ? await pushMessagesToArray( - connection, - messagesToStore, - [...fetchedMessages.values()], - { - threadId: channel.id, - threadName: channel.name, - channelId: channel.parent?.id, - channelName: channel.parent?.name, - } - ) - : await pushMessagesToArray(connection, messagesToStore, [ - ...fetchedMessages.values(), - ]) - break - } - channel instanceof ThreadChannel - ? await pushMessagesToArray( - connection, - messagesToStore, - [...fetchedMessages.values()], - { + ? await pushMessagesToArray(connection, messagesToStore, [...fetchedMessages.values()], { threadId: channel.id, threadName: channel.name, channelId: channel.parent?.id, channelName: channel.parent?.name, - } - ) - : await pushMessagesToArray(connection, messagesToStore, [ - ...fetchedMessages.values(), - ]) + }) + : await pushMessagesToArray(connection, messagesToStore, [...fetchedMessages.values()]) + break + } + channel instanceof ThreadChannel + ? await pushMessagesToArray(connection, messagesToStore, [...fetchedMessages.values()], { + threadId: channel.id, + threadName: channel.name, + channelId: channel.parent?.id, + channelName: channel.parent?.name, + }) + : await pushMessagesToArray(connection, messagesToStore, [...fetchedMessages.values()]) await rawInfoService.createRawInfos(connection, messagesToStore) options[fetchDirection] = boundaryMessage.id fetchedMessages = await channel.messages.fetch(options) @@ -332,158 +284,77 @@ async function fetchMessages( * @param {Date} period - A date object specifying the oldest date for the messages to be fetched. * @throws Will throw an error if an issue is encountered during processing. */ -async function handleFetchChannelMessages( - connection: Connection, - channel: TextChannel, - period: Date -) { +async function handleFetchChannelMessages(connection: Connection, channel: TextChannel, period: Date) { // logger.info({ guild_id: connection.name, channel_id: channel.id }, 'Handle channel messages for channel is running'); try { - const oldestChannelRawInfo = await rawInfoService.getOldestRawInfo( - connection, - { - channelId: channel?.id, - threadId: null, - } - ) - const newestChannelRawInfo = await rawInfoService.getNewestRawInfo( - connection, - { - channelId: channel?.id, - threadId: null, - } - ) + const oldestChannelRawInfo = await rawInfoService.getOldestRawInfo(connection, { + channelId: channel?.id, + threadId: null, + }) + const newestChannelRawInfo = await rawInfoService.getNewestRawInfo(connection, { + channelId: channel?.id, + threadId: null, + }) if (oldestChannelRawInfo && oldestChannelRawInfo.createdDate > period) { - await fetchMessages( - connection, - channel, - oldestChannelRawInfo, - period, - 'before' - ) + await fetchMessages(connection, channel, oldestChannelRawInfo, period, 'before') } if (newestChannelRawInfo) { - await fetchMessages( - connection, - channel, - newestChannelRawInfo, - period, - 'after' - ) + await fetchMessages(connection, channel, newestChannelRawInfo, period, 'after') } if (!newestChannelRawInfo && !oldestChannelRawInfo) { - await fetchMessages( - connection, - channel, - undefined, - period, - 'before' - ) + await fetchMessages(connection, channel, undefined, period, 'before') } const threads = channel.threads.cache.values() for (const thread of threads) { - const oldestThreadRawInfo = await rawInfoService.getOldestRawInfo( - connection, - { - channelId: channel?.id, - threadId: thread.id, - } - ) - const newestThreadRawInfo = await rawInfoService.getNewestRawInfo( - connection, - { - channelId: channel?.id, - threadId: thread.id, - } - ) + const oldestThreadRawInfo = await rawInfoService.getOldestRawInfo(connection, { + channelId: channel?.id, + threadId: thread.id, + }) + const newestThreadRawInfo = await rawInfoService.getNewestRawInfo(connection, { + channelId: channel?.id, + threadId: thread.id, + }) - if ( - oldestThreadRawInfo && - oldestThreadRawInfo.createdDate > period - ) { - await fetchMessages( - connection, - thread, - oldestThreadRawInfo, - period, - 'before' - ) + if (oldestThreadRawInfo && oldestThreadRawInfo.createdDate > period) { + await fetchMessages(connection, thread, oldestThreadRawInfo, period, 'before') } if (newestThreadRawInfo) { - await fetchMessages( - connection, - thread, - newestThreadRawInfo, - period, - 'after' - ) + await fetchMessages(connection, thread, newestThreadRawInfo, period, 'after') } if (!newestThreadRawInfo && !oldestThreadRawInfo) { - await fetchMessages( - connection, - thread, - undefined, - period, - 'before' - ) + await fetchMessages(connection, thread, undefined, period, 'before') } } } catch (err) { - logger.error( - { guild_id: connection.name, channel_id: channel.id, err }, - 'Handle fetch channel messages failed' - ) + logger.error({ guild_id: connection.name, channel_id: channel.id, err }, 'Handle fetch channel messages failed') } // logger.info({ guild_id: connection.name, channel_id: channel.id }, 'Handle fetch channel messages is done'); } -export default async function handleFetchMessages( - connection: Connection, - platform: HydratedDocument -) { +export default async function handleFetchMessages(connection: Connection, platform: HydratedDocument) { try { - const guild = await guildService.getGuildFromDiscordAPI( - platform.metadata?.id - ) + const guild = await guildService.getGuildFromDiscordAPI(platform.metadata?.id) if (guild) { - if ( - platform.metadata?.selectedChannels && - platform.metadata?.period - ) { - await platformService.updatePlatform( - { _id: platform.id }, - { metadata: { isInProgress: true } } - ) - for ( - let i = 0; - i < platform.metadata?.selectedChannels.length; - i++ - ) { - const channel = - await channelService.getChannelFromDiscordAPI( - guild, - platform.metadata?.selectedChannels[i] - ) + if (platform.metadata?.selectedChannels && platform.metadata?.period) { + await platformService.updatePlatform({ _id: platform.id }, { metadata: { isInProgress: true } }) + for (let i = 0; i < platform.metadata?.selectedChannels.length; i++) { + const channel = await channelService.getChannelFromDiscordAPI( + guild, + platform.metadata?.selectedChannels[i] + ) if (channel) { if (channel.type !== 0) continue - await handleFetchChannelMessages( - connection, - channel, - platform.metadata?.period - ) + await handleFetchChannelMessages(connection, channel, platform.metadata?.period) } } } } } catch (error) { - logger.error( - { guild_id: platform.metadata?.id, error }, - 'Failed to fetch messages' - ) + logger.error({ guild_id: platform.metadata?.id, error }, 'Failed to fetch messages') } } diff --git a/bot/src/functions/fetchRoles.ts b/bot/src/functions/fetchRoles.ts index 8b0b2aa6..9b4222cd 100644 --- a/bot/src/functions/fetchRoles.ts +++ b/bot/src/functions/fetchRoles.ts @@ -12,21 +12,13 @@ const logger = parentLogger.child({ module: 'FetchRoles' }) * @param {Snowflake} guildId - The identifier of the guild to extract roles from. */ // eslint-disable-next-line @typescript-eslint/explicit-function-return-type -export default async function fetchGuildRoles( - connection: Connection, - platform: HydratedDocument -) { +export default async function fetchGuildRoles(connection: Connection, platform: HydratedDocument) { try { const client = await coreService.DiscordBotManager.getClient() - const hasBotAccessToGuild = await platformService.checkBotAccessToGuild( - platform.metadata?.id - ) + const hasBotAccessToGuild = await platformService.checkBotAccessToGuild(platform.metadata?.id) let rolesToStore: IRole[] = [] if (!hasBotAccessToGuild) { - logger.info( - { guild_id: platform.metadata?.id }, - 'Bot access missing' - ) + logger.info({ guild_id: platform.metadata?.id }, 'Bot access missing') return } const guild = await client.guilds.fetch(platform.metadata?.id) @@ -34,14 +26,8 @@ export default async function fetchGuildRoles( const fetchedRoles = await guild.roles.fetch() rolesToStore = fetchedRoles.map(roleService.getNeededDateFromRole) await roleService.createRoles(connection, rolesToStore) - logger.info( - { guild_id: platform.metadata?.id }, - 'Roles stored successfully' - ) + logger.info({ guild_id: platform.metadata?.id }, 'Roles stored successfully') } catch (error) { - logger.error( - { guild_id: platform.metadata?.id, error }, - 'Failed to fetch roles' - ) + logger.error({ guild_id: platform.metadata?.id, error }, 'Failed to fetch roles') } } diff --git a/bot/src/functions/guildExtraction.ts b/bot/src/functions/guildExtraction.ts index 93f17721..b1c16417 100644 --- a/bot/src/functions/guildExtraction.ts +++ b/bot/src/functions/guildExtraction.ts @@ -10,32 +10,17 @@ const logger = parentLogger.child({ module: 'GuildExtraction' }) * @param {Snowflake} guildId - The identifier of the guild to extract information from. */ // eslint-disable-next-line @typescript-eslint/explicit-function-return-type -export default async function guildExtraction( - platform: HydratedDocument -) { - const connection = await DatabaseManager.getInstance().getGuildDb( - platform.metadata?.id - ) - logger.info( - { guild_id: platform.metadata?.id }, - 'Guild extraction for guild is running' - ) +export default async function guildExtraction(platform: HydratedDocument) { + const connection = await DatabaseManager.getInstance().getGuildDb(platform.metadata?.id) + logger.info({ guild_id: platform.metadata?.id }, 'Guild extraction for guild is running') try { - const hasBotAccessToGuild = await platformService.checkBotAccessToGuild( - platform.metadata?.id - ) + const hasBotAccessToGuild = await platformService.checkBotAccessToGuild(platform.metadata?.id) if (!hasBotAccessToGuild) { return } await fetchMessages(connection, platform) } catch (err) { - logger.error( - { guild_id: platform.metadata?.id, err }, - 'Guild extraction CronJob failed for guild' - ) + logger.error({ guild_id: platform.metadata?.id, err }, 'Guild extraction CronJob failed for guild') } - logger.info( - { guild_id: platform.metadata?.id }, - 'Guild extraction for guild is done' - ) + logger.info({ guild_id: platform.metadata?.id }, 'Guild extraction for guild is done') } diff --git a/bot/src/functions/sendDirectMessage.ts b/bot/src/functions/sendDirectMessage.ts index a821cfdd..53982d18 100644 --- a/bot/src/functions/sendDirectMessage.ts +++ b/bot/src/functions/sendDirectMessage.ts @@ -7,10 +7,7 @@ import { coreService } from '../services' * @returns throw error if User has DMs closed or has no mutual servers with the bot */ // eslint-disable-next-line @typescript-eslint/explicit-function-return-type -export default async function sendDirectMessage(info: { - discordId: Snowflake - message: string -}) { +export default async function sendDirectMessage(info: { discordId: Snowflake; message: string }) { const client = await coreService.DiscordBotManager.getClient() const { discordId, message } = info diff --git a/bot/src/migrations/utils/addChannelTypeLogic.ts b/bot/src/migrations/utils/addChannelTypeLogic.ts index 9ae61066..58d2e809 100644 --- a/bot/src/migrations/utils/addChannelTypeLogic.ts +++ b/bot/src/migrations/utils/addChannelTypeLogic.ts @@ -20,8 +20,7 @@ async function channelMigration(connection: Connection, guildId: Snowflake) { const updates: Array<{ channelId: string; type: number }> = [] const guild = await client.guilds.fetch(guildId) const channels = [...guild.channels.cache.values()].filter( - (channel) => - channel.type === 0 || channel.type === 2 || channel.type === 4 + (channel) => channel.type === 0 || channel.type === 2 || channel.type === 4 ) as Array for (const channel of channels) { diff --git a/bot/src/migrations/utils/isBotLogic.ts b/bot/src/migrations/utils/isBotLogic.ts index 1769af61..82ce7497 100644 --- a/bot/src/migrations/utils/isBotLogic.ts +++ b/bot/src/migrations/utils/isBotLogic.ts @@ -12,10 +12,7 @@ const logger = parentLogger.child({ module: 'Migration-isBot' }) * @param {GuildMember[]} guildMembersArray - An array of guild members from which data is to be extracted. * @returns {Promise} - A promise that resolves to the updated array containing the extracted data. */ -function pushMembersToArray( - arr: IGuildMember[], - guildMembersArray: GuildMember[] -): IGuildMember[] { +function pushMembersToArray(arr: IGuildMember[], guildMembersArray: GuildMember[]): IGuildMember[] { for (const guildMember of guildMembersArray) { arr.push(guildMemberService.getNeededDateFromGuildMember(guildMember)) } @@ -27,11 +24,7 @@ function pushMembersToArray( * @param {Connection} connection - Mongoose connection object for the database. * @param {Snowflake} guildId - The identifier of the guild to extract information from. */ -export default async function isBotLogic( - connection: Connection, - client: Client, - guildId: Snowflake -) { +export default async function isBotLogic(connection: Connection, client: Client, guildId: Snowflake) { // logger.info({ guild_id: guildId }, 'add-isBot-to-guilbMember-schema migration is running'); try { const botGuildMembers = [] @@ -40,9 +33,7 @@ export default async function isBotLogic( const guild = await client.guilds.fetch(guildId) const membersToStore: IGuildMember[] = [] const fetchedMembers = await guild.members.fetch() - const guildMembers = pushMembersToArray(membersToStore, [ - ...fetchedMembers.values(), - ]) + const guildMembers = pushMembersToArray(membersToStore, [...fetchedMembers.values()]) if (guildMembers) { for (const guildMember of guildMembers) { @@ -79,10 +70,7 @@ export default async function isBotLogic( ) } } catch (err) { - logger.error( - { guild_id: guildId, err }, - 'add-isBot-to-guilbMember-schema migration is failed' - ) + logger.error({ guild_id: guildId, err }, 'add-isBot-to-guilbMember-schema migration is failed') } // logger.info({ guild_id: guildId }, 'add-isBot-to-guilbMember-schema migration is done'); } diff --git a/bot/src/migrations/utils/webhookLogic.ts b/bot/src/migrations/utils/webhookLogic.ts index 94b059f3..1630d175 100644 --- a/bot/src/migrations/utils/webhookLogic.ts +++ b/bot/src/migrations/utils/webhookLogic.ts @@ -1,11 +1,6 @@ /* eslint-disable @typescript-eslint/strict-boolean-expressions */ /* eslint-disable @typescript-eslint/explicit-function-return-type */ -import { - type TextChannel, - type Message, - type ThreadChannel, - type Snowflake, -} from 'discord.js' +import { type TextChannel, type Message, type ThreadChannel, type Snowflake } from 'discord.js' import { type IRawInfo } from '@togethercrew.dev/db' import { type Connection } from 'mongoose' import parentLogger from '../../config/logger' @@ -28,17 +23,12 @@ async function fetchMessagesBetweenOldestAndNewest( ) { try { let allMessages: Message[] = [] - logger.info( - { guild_id: connection.name, channel_id: channel.id }, - 'Fetching channel messages is running' - ) + logger.info({ guild_id: connection.name, channel_id: channel.id }, 'Fetching channel messages is running') const options: FetchOptions = { limit: 100 } options.after = oldestRawInfo.messageId let fetchedMessages = await channel.messages.fetch(options) while (fetchedMessages.size > 0) { - allMessages = allMessages.concat( - Array.from(fetchedMessages.values()) - ) + allMessages = allMessages.concat(Array.from(fetchedMessages.values())) if (fetchedMessages.has(newestRawInfo.messageId)) { break } @@ -47,21 +37,12 @@ async function fetchMessagesBetweenOldestAndNewest( } return allMessages } catch (err) { - logger.error( - { guild_id: connection.name, channel_id: channel.id, err }, - 'Fetching channel messages failed' - ) + logger.error({ guild_id: connection.name, channel_id: channel.id, err }, 'Fetching channel messages failed') } - logger.info( - { guild_id: connection.name, channel_id: channel.id }, - 'Fetching channel messages is done' - ) + logger.info({ guild_id: connection.name, channel_id: channel.id }, 'Fetching channel messages is done') } -async function migrateIsGeneratedByWebhook( - connection: Connection, - channel: TextChannel -) { +async function migrateIsGeneratedByWebhook(connection: Connection, channel: TextChannel) { try { logger.info( { guild_id: connection.name, channel_id: channel.id }, @@ -69,22 +50,16 @@ async function migrateIsGeneratedByWebhook( ) // Fetch oldest rawInfo from DB - const oldestChannelRawInfo = await rawInfoService.getOldestRawInfo( - connection, - { - channelId: channel?.id, - threadId: null, - } - ) + const oldestChannelRawInfo = await rawInfoService.getOldestRawInfo(connection, { + channelId: channel?.id, + threadId: null, + }) // Fetch newest rawInfo from DB - const newestChannelRawInfo = await rawInfoService.getNewestRawInfo( - connection, - { - channelId: channel?.id, - threadId: null, - } - ) + const newestChannelRawInfo = await rawInfoService.getNewestRawInfo(connection, { + channelId: channel?.id, + threadId: null, + }) if (!oldestChannelRawInfo || !newestChannelRawInfo) { logger.info( @@ -103,12 +78,8 @@ async function migrateIsGeneratedByWebhook( const messagesToUpdateTrue = [] const messagesToUpdateFalse = [] - const oldestMessage = await channel.messages.fetch( - oldestChannelRawInfo.messageId - ) - const newestMessage = await channel.messages.fetch( - newestChannelRawInfo.messageId - ) + const oldestMessage = await channel.messages.fetch(oldestChannelRawInfo.messageId) + const newestMessage = await channel.messages.fetch(newestChannelRawInfo.messageId) if (oldestMessage.webhookId) messagesToUpdateTrue.push(oldestMessage.id) else messagesToUpdateFalse.push(oldestMessage.id) @@ -146,50 +117,37 @@ async function migrateIsGeneratedByWebhook( // Handle threads of the channel for (const thread of threads) { - const oldestThreadRawInfo = await rawInfoService.getOldestRawInfo( - connection, - { - channelId: channel?.id, - threadId: thread.id, - } - ) + const oldestThreadRawInfo = await rawInfoService.getOldestRawInfo(connection, { + channelId: channel?.id, + threadId: thread.id, + }) - const newestThreadRawInfo = await rawInfoService.getNewestRawInfo( - connection, - { - channelId: channel?.id, - threadId: thread.id, - } - ) + const newestThreadRawInfo = await rawInfoService.getNewestRawInfo(connection, { + channelId: channel?.id, + threadId: thread.id, + }) if (!oldestThreadRawInfo || !newestThreadRawInfo) { continue // No data to migrate for this thread } - const fetchedThreadMessages = - await fetchMessagesBetweenOldestAndNewest( - connection, - thread, - oldestThreadRawInfo, - newestThreadRawInfo - ) + const fetchedThreadMessages = await fetchMessagesBetweenOldestAndNewest( + connection, + thread, + oldestThreadRawInfo, + newestThreadRawInfo + ) const threadMessagesToUpdateTrue = [] const threadMessagesToUpdateFalse = [] - const oldestThreadMessage = await thread.messages.fetch( - oldestThreadRawInfo.messageId - ) - const newestThreadMessage = await thread.messages.fetch( - newestThreadRawInfo.messageId - ) + const oldestThreadMessage = await thread.messages.fetch(oldestThreadRawInfo.messageId) + const newestThreadMessage = await thread.messages.fetch(newestThreadRawInfo.messageId) - if (oldestThreadMessage.webhookId) - threadMessagesToUpdateTrue.push(oldestThreadMessage.id) + if (oldestThreadMessage.webhookId) threadMessagesToUpdateTrue.push(oldestThreadMessage.id) else threadMessagesToUpdateFalse.push(oldestThreadMessage.id) - if (newestThreadMessage.webhookId) - threadMessagesToUpdateTrue.push(newestThreadMessage.id) + if (newestThreadMessage.webhookId) threadMessagesToUpdateTrue.push(newestThreadMessage.id) else threadMessagesToUpdateFalse.push(newestThreadMessage.id) if (fetchedThreadMessages) { @@ -219,10 +177,7 @@ async function migrateIsGeneratedByWebhook( } } - logger.info( - { guild_id: connection.name, channel_id: channel.id }, - 'Migration for isGeneratedByWebhook is done' - ) + logger.info({ guild_id: connection.name, channel_id: channel.id }, 'Migration for isGeneratedByWebhook is done') } catch (err) { logger.error( { guild_id: connection.name, channel_id: channel.id, err }, diff --git a/bot/src/queue/handlers/channelCreateHandler.ts b/bot/src/queue/handlers/channelCreateHandler.ts index 3bf113d6..66930b98 100644 --- a/bot/src/queue/handlers/channelCreateHandler.ts +++ b/bot/src/queue/handlers/channelCreateHandler.ts @@ -5,10 +5,7 @@ import parentLogger from '../../config/logger' const logger = parentLogger.child({ event: 'ChannelCreateHandler' }) -export default async function ( - guildId: Snowflake, - dataToStore: IChannel -): Promise { +export default async function (guildId: Snowflake, dataToStore: IChannel): Promise { const logFields = { guild_id: guildId, channel_id: dataToStore.channelId } // logger.info(logFields, 'event is running'); const connection = await DatabaseManager.getInstance().getGuildDb(guildId) diff --git a/bot/src/queue/handlers/channelDeleteHandler.ts b/bot/src/queue/handlers/channelDeleteHandler.ts index e6d94324..5e524532 100644 --- a/bot/src/queue/handlers/channelDeleteHandler.ts +++ b/bot/src/queue/handlers/channelDeleteHandler.ts @@ -5,10 +5,7 @@ import parentLogger from '../../config/logger' const logger = parentLogger.child({ event: 'ChannelDeleteHandler' }) -export default async function ( - guildId: Snowflake, - channelId: Snowflake -): Promise { +export default async function (guildId: Snowflake, channelId: Snowflake): Promise { const logFields = { guild_id: guildId, channel_id: channelId } // logger.info(logFields, 'event is running'); const connection = await DatabaseManager.getInstance().getGuildDb(guildId) @@ -20,12 +17,10 @@ export default async function ( const platformDoc = await platformService.getPlatform({ 'metadata.id': guildId, }) - const updatedSelecetdChannels = - platformDoc?.metadata?.selectedChannels?.filter( - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (selectedChannel: any) => - selectedChannel.channelId !== channelId - ) + const updatedSelecetdChannels = platformDoc?.metadata?.selectedChannels?.filter( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (selectedChannel: any) => selectedChannel.channelId !== channelId + ) await platformService.updatePlatform( { 'metadata.id': guildId }, { metadata: { selectedChannels: updatedSelecetdChannels } } diff --git a/bot/src/queue/handlers/channelUpdateHandler.ts b/bot/src/queue/handlers/channelUpdateHandler.ts index 1014c435..37c76ebe 100644 --- a/bot/src/queue/handlers/channelUpdateHandler.ts +++ b/bot/src/queue/handlers/channelUpdateHandler.ts @@ -5,10 +5,7 @@ import parentLogger from '../../config/logger' const logger = parentLogger.child({ event: 'ChannelUpdateHandler' }) -export default async function ( - guildId: Snowflake, - dataToStore: IChannel -): Promise { +export default async function (guildId: Snowflake, dataToStore: IChannel): Promise { const logFields = { guild_id: guildId, channel_id: dataToStore.channelId } // logger.info(logFields, 'event is running'); const connection = await DatabaseManager.getInstance().getGuildDb(guildId) diff --git a/bot/src/queue/handlers/guildMemberAddHandler.ts b/bot/src/queue/handlers/guildMemberAddHandler.ts index ea89ee32..01e2ffdf 100644 --- a/bot/src/queue/handlers/guildMemberAddHandler.ts +++ b/bot/src/queue/handlers/guildMemberAddHandler.ts @@ -5,10 +5,7 @@ import parentLogger from '../../config/logger' const logger = parentLogger.child({ event: 'GuildMemberAddHandler' }) -export default async function ( - guildId: Snowflake, - dataToStore: IGuildMember -): Promise { +export default async function (guildId: Snowflake, dataToStore: IGuildMember): Promise { const logFields = { guild_id: guildId, guild_member_id: dataToStore.discordId, @@ -26,9 +23,6 @@ export default async function ( } // logger.info(logFields, 'event is done'); } catch (err) { - logger.error( - { ...logFields, err }, - 'Failed to handle guild member changes' - ) + logger.error({ ...logFields, err }, 'Failed to handle guild member changes') } } diff --git a/bot/src/queue/handlers/guildMemberRemoveHandler.ts b/bot/src/queue/handlers/guildMemberRemoveHandler.ts index ccecb34a..03d8dabc 100644 --- a/bot/src/queue/handlers/guildMemberRemoveHandler.ts +++ b/bot/src/queue/handlers/guildMemberRemoveHandler.ts @@ -5,24 +5,15 @@ import parentLogger from '../../config/logger' const logger = parentLogger.child({ event: 'GuildMemberRemoveHandler' }) -export default async function ( - guildId: Snowflake, - guildMemberId: Snowflake -): Promise { +export default async function (guildId: Snowflake, guildMemberId: Snowflake): Promise { const logFields = { guild_id: guildId, guild_member_id: guildMemberId } // logger.info(logFields, 'event is running'); const connection = await DatabaseManager.getInstance().getGuildDb(guildId) try { - const guildMemberDoc = await guildMemberService.getGuildMember( - connection, - { discordId: guildMemberId } - ) + const guildMemberDoc = await guildMemberService.getGuildMember(connection, { discordId: guildMemberId }) guildMemberDoc?.softDelete() // logger.info(logFields, 'event is done'); } catch (err) { - logger.error( - { ...logFields, err }, - 'Failed to soft delete the guild member' - ) + logger.error({ ...logFields, err }, 'Failed to soft delete the guild member') } } diff --git a/bot/src/queue/handlers/guildMemberUpdateHandler.ts b/bot/src/queue/handlers/guildMemberUpdateHandler.ts index 67508171..053a6d7e 100644 --- a/bot/src/queue/handlers/guildMemberUpdateHandler.ts +++ b/bot/src/queue/handlers/guildMemberUpdateHandler.ts @@ -5,10 +5,7 @@ import parentLogger from '../../config/logger' const logger = parentLogger.child({ event: 'GuildMemberUpdateHandler' }) -export default async function ( - guildId: Snowflake, - dataToStore: IGuildMember -): Promise { +export default async function (guildId: Snowflake, dataToStore: IGuildMember): Promise { const logFields = { guild_id: guildId, guild_member_id: dataToStore.discordId, @@ -26,9 +23,6 @@ export default async function ( } // logger.info(logFields, 'event is done'); } catch (err) { - logger.error( - { ...logFields, err }, - 'Failed to handle guild member changes' - ) + logger.error({ ...logFields, err }, 'Failed to handle guild member changes') } } diff --git a/bot/src/queue/handlers/roleCreateHandler.ts b/bot/src/queue/handlers/roleCreateHandler.ts index 62d07c8b..07379c7a 100644 --- a/bot/src/queue/handlers/roleCreateHandler.ts +++ b/bot/src/queue/handlers/roleCreateHandler.ts @@ -5,19 +5,12 @@ import parentLogger from '../../config/logger' const logger = parentLogger.child({ event: 'GuildRoleCreateHandler' }) -export default async function ( - guildId: Snowflake, - dataToStore: IRole -): Promise { +export default async function (guildId: Snowflake, dataToStore: IRole): Promise { const logFields = { guild_id: guildId, role_id: dataToStore.roleId } // logger.info(logFields, 'event is running'); const connection = await DatabaseManager.getInstance().getGuildDb(guildId) try { - const roleDoc = await roleService.updateRole( - connection, - { roleId: dataToStore.roleId }, - dataToStore - ) + const roleDoc = await roleService.updateRole(connection, { roleId: dataToStore.roleId }, dataToStore) if (roleDoc === null) { await roleService.createRole(connection, dataToStore) } diff --git a/bot/src/queue/handlers/roleDeleteHandler.ts b/bot/src/queue/handlers/roleDeleteHandler.ts index a9e3dcba..92e7882c 100644 --- a/bot/src/queue/handlers/roleDeleteHandler.ts +++ b/bot/src/queue/handlers/roleDeleteHandler.ts @@ -5,10 +5,7 @@ import parentLogger from '../../config/logger' const logger = parentLogger.child({ event: 'GuildRoleDeleteHandler' }) -export default async function ( - guildId: Snowflake, - roleId: Snowflake -): Promise { +export default async function (guildId: Snowflake, roleId: Snowflake): Promise { const logFields = { guild_id: guildId, role_id: roleId } // logger.info(logFields, 'event is running'); const connection = await DatabaseManager.getInstance().getGuildDb(guildId) diff --git a/bot/src/queue/handlers/roleUpdateHandler.ts b/bot/src/queue/handlers/roleUpdateHandler.ts index 7affcb8b..b468a716 100644 --- a/bot/src/queue/handlers/roleUpdateHandler.ts +++ b/bot/src/queue/handlers/roleUpdateHandler.ts @@ -5,10 +5,7 @@ import parentLogger from '../../config/logger' const logger = parentLogger.child({ event: 'GuildRoleUpdateHandler' }) -export default async function ( - guildId: Snowflake, - dataToStore: IRole -): Promise { +export default async function (guildId: Snowflake, dataToStore: IRole): Promise { const logFields = { guild_id: guildId, role_id: dataToStore.roleId } // logger.info(logFields, 'event is running'); const connection = await DatabaseManager.getInstance().getGuildDb(guildId) diff --git a/bot/src/queue/handlers/userUpdateHandler.ts b/bot/src/queue/handlers/userUpdateHandler.ts index 364d8e74..e3323e7f 100644 --- a/bot/src/queue/handlers/userUpdateHandler.ts +++ b/bot/src/queue/handlers/userUpdateHandler.ts @@ -16,9 +16,7 @@ export default async function (dataToStore: IdataToStore): Promise { disconnectedAt: null, }) for (let i = 0; i < platforms.length; i++) { - const connection = await DatabaseManager.getInstance().getGuildDb( - platforms[i].metadata?.id - ) + const connection = await DatabaseManager.getInstance().getGuildDb(platforms[i].metadata?.id) await guildMemberService.updateGuildMember( connection, diff --git a/bot/src/queue/queues/channelMessage.ts b/bot/src/queue/queues/channelMessage.ts index 854a9b9d..338fcadd 100644 --- a/bot/src/queue/queues/channelMessage.ts +++ b/bot/src/queue/queues/channelMessage.ts @@ -2,15 +2,9 @@ import { type Snowflake } from 'discord.js' import { QueueFactory } from './index' import { type ObjectId } from 'mongodb' -export const channelMessageQueue = QueueFactory.createQueue( - 'channelMessageQueue' -) +export const channelMessageQueue = QueueFactory.createQueue('channelMessageQueue') -export const addChannelMessage = ( - discordId: Snowflake, - message: string, - sagaId: ObjectId -): void => { +export const addChannelMessage = (discordId: Snowflake, message: string, sagaId: ObjectId): void => { void channelMessageQueue.add( 'channelMessageQueue', { discordId, message, sagaId }, diff --git a/bot/src/queue/queues/guildExtraction.ts b/bot/src/queue/queues/guildExtraction.ts index 040bca8c..0568bb71 100644 --- a/bot/src/queue/queues/guildExtraction.ts +++ b/bot/src/queue/queues/guildExtraction.ts @@ -2,14 +2,9 @@ import { QueueFactory } from './index' import { type HydratedDocument } from 'mongoose' import { type IPlatform } from '@togethercrew.dev/db' -export const guildExtractionQueue = QueueFactory.createQueue( - 'guildExtractionQueue' -) +export const guildExtractionQueue = QueueFactory.createQueue('guildExtractionQueue') -export const addGuildExtraction = ( - platform: HydratedDocument, - recompute: boolean -): void => { +export const addGuildExtraction = (platform: HydratedDocument, recompute: boolean): void => { void guildExtractionQueue.add( 'guildExtractionQueue', { platform, recompute }, diff --git a/bot/src/queue/workers/channelMessageWorker.ts b/bot/src/queue/workers/channelMessageWorker.ts index e6c28dca..82bc4898 100644 --- a/bot/src/queue/workers/channelMessageWorker.ts +++ b/bot/src/queue/workers/channelMessageWorker.ts @@ -12,10 +12,7 @@ export const channelMessageWorker = new Worker( sagaId: job.data.sagaId, }) - const message = await channelService.sendChannelMessage( - job.data.discordId, - job.data.message - ) + const message = await channelService.sendChannelMessage(job.data.discordId, job.data.message) if (saga.data.isSafetyMessage === true) { saga.data = { ...saga.data, diff --git a/bot/src/queue/workers/directMessageWorker.ts b/bot/src/queue/workers/directMessageWorker.ts index 74134b21..a921608d 100644 --- a/bot/src/queue/workers/directMessageWorker.ts +++ b/bot/src/queue/workers/directMessageWorker.ts @@ -7,10 +7,7 @@ export const directMessageWorker = new Worker( 'directMessageQueue', async (job: Job | undefined) => { if (job !== null && job !== undefined) { - await userService.sendDirectMessage( - job.data.discordId, - job.data.info - ) + await userService.sendDirectMessage(job.data.discordId, job.data.info) } }, { diff --git a/bot/src/queue/workers/guildEventWorker.ts b/bot/src/queue/workers/guildEventWorker.ts index 8ca16405..33b52c14 100644 --- a/bot/src/queue/workers/guildEventWorker.ts +++ b/bot/src/queue/workers/guildEventWorker.ts @@ -21,59 +21,35 @@ export const discordEventWorker = new Worker( if (job !== null && job !== undefined) { switch (job.data.type) { case Events.ChannelCreate: { - await channelCreateHandler( - job.data.guildId, - job.data.dataToStore - ) + await channelCreateHandler(job.data.guildId, job.data.dataToStore) break } case Events.ChannelUpdate: { - await channelUpdateHandler( - job.data.guildId, - job.data.dataToStore - ) + await channelUpdateHandler(job.data.guildId, job.data.dataToStore) break } case Events.ChannelDelete: { - await channelDeleteHandler( - job.data.guildId, - job.data.channelId - ) + await channelDeleteHandler(job.data.guildId, job.data.channelId) break } case Events.GuildMemberAdd: { - await guildMemberAddHandler( - job.data.guildId, - job.data.dataToStore - ) + await guildMemberAddHandler(job.data.guildId, job.data.dataToStore) break } case Events.GuildMemberUpdate: { - await guildMemberUpdateHandler( - job.data.guildId, - job.data.dataToStore - ) + await guildMemberUpdateHandler(job.data.guildId, job.data.dataToStore) break } case Events.GuildMemberRemove: { - await guildMemberRemoveHandler( - job.data.guildId, - job.data.guildMemberId - ) + await guildMemberRemoveHandler(job.data.guildId, job.data.guildMemberId) break } case Events.GuildRoleCreate: { - await roleCreateHandler( - job.data.guildId, - job.data.dataToStore - ) + await roleCreateHandler(job.data.guildId, job.data.dataToStore) break } case Events.GuildRoleUpdate: { - await roleUpdateHandler( - job.data.guildId, - job.data.dataToStore - ) + await roleUpdateHandler(job.data.guildId, job.data.dataToStore) break } case Events.GuildRoleDelete: { diff --git a/bot/src/queue/workers/index.ts b/bot/src/queue/workers/index.ts index c1d8f3b9..08732d95 100644 --- a/bot/src/queue/workers/index.ts +++ b/bot/src/queue/workers/index.ts @@ -15,8 +15,7 @@ export class WorkerFactory { worker.on('completed', async (job: any) => { if (worker.name === 'guildExtractionQueue') { try { - const platform = job.data - .platform as HydratedDocument + const platform = job.data.platform as HydratedDocument const recompute = job.data.recompute const res = await airflowService.triggerDag({ platform_id: platform.id, @@ -24,10 +23,7 @@ export class WorkerFactory { period: platform.metadata?.period, recompute, }) - logger.info( - { jobId: job.id, res, recompute, platform }, - 'Guild extraction job completed' - ) + logger.info({ jobId: job.id, res, recompute, platform }, 'Guild extraction job completed') } catch (err) { console.log(error) logger.error({ job, err }, 'triggerDag failed') diff --git a/bot/src/rabbitmq/RabbitMQConnection.ts b/bot/src/rabbitmq/RabbitMQConnection.ts index 1057117b..0279198d 100644 --- a/bot/src/rabbitmq/RabbitMQConnection.ts +++ b/bot/src/rabbitmq/RabbitMQConnection.ts @@ -8,9 +8,6 @@ export const connectToRabbitMQ = async (): Promise => { await RabbitMQ.connect(config.rabbitMQ.url, Queue.DISCORD_BOT) logger.info({ queue: Queue.DISCORD_BOT }, 'Connected to RabbitMQ!') } catch (error) { - logger.fatal( - { queue: Queue.DISCORD_BOT, error }, - 'Failed to connect to RabbitMQ!' - ) + logger.fatal({ queue: Queue.DISCORD_BOT, error }, 'Failed to connect to RabbitMQ!') } } diff --git a/bot/src/rabbitmq/RabbitMQHandler.ts b/bot/src/rabbitmq/RabbitMQHandler.ts index b76bb987..fe082327 100644 --- a/bot/src/rabbitmq/RabbitMQHandler.ts +++ b/bot/src/rabbitmq/RabbitMQHandler.ts @@ -12,25 +12,10 @@ import { handleSendMessageToChannel } from './events/sendMessageToChannel' export function setupRabbitMQHandlers(): void { RabbitMQ.onEvent(Event.DISCORD_BOT.FETCH, handleFetchEvent) RabbitMQ.onEvent(Event.DISCORD_BOT.SEND_MESSAGE, handleSendMessageEvent) - RabbitMQ.onEvent( - Event.DISCORD_BOT.SEND_MESSAGE_TO_CHANNEL, - handleSendMessageToChannel - ) + RabbitMQ.onEvent(Event.DISCORD_BOT.SEND_MESSAGE_TO_CHANNEL, handleSendMessageToChannel) RabbitMQ.onEvent(Event.DISCORD_BOT.FETCH_MEMBERS, handleFetchMembersEvent) - RabbitMQ.onEvent( - Event.DISCORD_BOT.INTERACTION_RESPONSE.CREATE, - handleInteractionResponseCreate - ) - RabbitMQ.onEvent( - Event.DISCORD_BOT.INTERACTION_RESPONSE.EDIT, - handleInteractionResponseEdit - ) - RabbitMQ.onEvent( - Event.DISCORD_BOT.INTERACTION_RESPONSE.DELETE, - handleInteractionResponseDelete - ) - RabbitMQ.onEvent( - Event.DISCORD_BOT.FOLLOWUP_MESSAGE.CREATE, - handleFollowUpMessageCreate - ) + RabbitMQ.onEvent(Event.DISCORD_BOT.INTERACTION_RESPONSE.CREATE, handleInteractionResponseCreate) + RabbitMQ.onEvent(Event.DISCORD_BOT.INTERACTION_RESPONSE.EDIT, handleInteractionResponseEdit) + RabbitMQ.onEvent(Event.DISCORD_BOT.INTERACTION_RESPONSE.DELETE, handleInteractionResponseDelete) + RabbitMQ.onEvent(Event.DISCORD_BOT.FOLLOWUP_MESSAGE.CREATE, handleFollowUpMessageCreate) } diff --git a/bot/src/rabbitmq/events/FollowUpMessageCreate.ts b/bot/src/rabbitmq/events/FollowUpMessageCreate.ts index 6bab031f..e08c6df1 100644 --- a/bot/src/rabbitmq/events/FollowUpMessageCreate.ts +++ b/bot/src/rabbitmq/events/FollowUpMessageCreate.ts @@ -8,10 +8,7 @@ const logger = parentLogger.child({ // eslint-disable-next-line @typescript-eslint/no-explicit-any export async function handleFollowUpMessageCreate(msg: any): Promise { try { - logger.info( - { msg, event: Event.DISCORD_BOT.FOLLOWUP_MESSAGE.CREATE }, - 'is running' - ) + logger.info({ msg, event: Event.DISCORD_BOT.FOLLOWUP_MESSAGE.CREATE }, 'is running') // const interaction: ChatInputCommandInteraction_broker = JSON.parse(msg?.content.interaction); // const data: FollowUpMessageData = JSON.parse(msg?.content.data); @@ -19,14 +16,8 @@ export async function handleFollowUpMessageCreate(msg: any): Promise { const data = msg?.content.data await interactionService.createFollowUpMessage(interaction, data) - logger.info( - { msg, event: Event.DISCORD_BOT.FOLLOWUP_MESSAGE.CREATE }, - 'is done' - ) + logger.info({ msg, event: Event.DISCORD_BOT.FOLLOWUP_MESSAGE.CREATE }, 'is done') } catch (error) { - logger.error( - { msg, event: Event.DISCORD_BOT.FOLLOWUP_MESSAGE.CREATE, error }, - 'is failed' - ) + logger.error({ msg, event: Event.DISCORD_BOT.FOLLOWUP_MESSAGE.CREATE, error }, 'is failed') } } diff --git a/bot/src/rabbitmq/events/fetchEvent.ts b/bot/src/rabbitmq/events/fetchEvent.ts index 80c5684f..16561c81 100644 --- a/bot/src/rabbitmq/events/fetchEvent.ts +++ b/bot/src/rabbitmq/events/fetchEvent.ts @@ -21,23 +21,15 @@ const fetchMethod = async (msg: any): Promise => { if (platform !== null) { const isPlatformCreated = saga.data.created - const connection = await DatabaseManager.getInstance().getGuildDb( - platform.metadata?.id - ) + const connection = await DatabaseManager.getInstance().getGuildDb(platform.metadata?.id) if (isPlatformCreated === true) { - await platformService.updatePlatform( - { _id: platform.id }, - { metadata: { isFetchingInitialData: true } } - ) + await platformService.updatePlatform({ _id: platform.id }, { metadata: { isFetchingInitialData: true } }) await Promise.all([ fetchMembers(connection, platform), fetchChannels(connection, platform), fetchRoles(connection, platform), ]) - await platformService.updatePlatform( - { _id: platform.id }, - { metadata: { isFetchingInitialData: false } } - ) + await platformService.updatePlatform({ _id: platform.id }, { metadata: { isFetchingInitialData: false } }) } else { addGuildExtraction(platform, true) } @@ -47,10 +39,7 @@ const fetchMethod = async (msg: any): Promise => { export async function handleFetchEvent(msg: any): Promise { try { - logger.info( - { msg, event: Event.DISCORD_BOT.FETCH, sagaId: msg.content.uuid }, - 'is running' - ) + logger.info({ msg, event: Event.DISCORD_BOT.FETCH, sagaId: msg.content.uuid }, 'is running') if (msg === undefined || msg === null) return const { content } = msg const saga = await MBConnection.models.Saga.findOne({ @@ -58,10 +47,7 @@ export async function handleFetchEvent(msg: any): Promise { }) // eslint-disable-next-line @typescript-eslint/return-await await saga.next(async () => fetchMethod(msg)) - logger.info( - { msg, event: Event.DISCORD_BOT.FETCH, sagaId: msg.content.uuid }, - 'is done' - ) + logger.info({ msg, event: Event.DISCORD_BOT.FETCH, sagaId: msg.content.uuid }, 'is done') } catch (error) { logger.error( { diff --git a/bot/src/rabbitmq/events/fetchMembersEvent.ts b/bot/src/rabbitmq/events/fetchMembersEvent.ts index e5de2222..effb0a30 100644 --- a/bot/src/rabbitmq/events/fetchMembersEvent.ts +++ b/bot/src/rabbitmq/events/fetchMembersEvent.ts @@ -11,26 +11,16 @@ const logger = parentLogger.child({ module: `${Event.DISCORD_BOT.FETCH_MEMBERS}`, }) -const fetchInitialData = async ( - platform: HydratedDocument -): Promise => { +const fetchInitialData = async (platform: HydratedDocument): Promise => { try { - const connection = await DatabaseManager.getInstance().getGuildDb( - platform.metadata?.id - ) - await platformService.updatePlatform( - { _id: platform.id }, - { metadata: { isFetchingInitialData: true } } - ) + const connection = await DatabaseManager.getInstance().getGuildDb(platform.metadata?.id) + await platformService.updatePlatform({ _id: platform.id }, { metadata: { isFetchingInitialData: true } }) await Promise.all([ fetchMembers(connection, platform), fetchChannels(connection, platform), fetchRoles(connection, platform), ]) - await platformService.updatePlatform( - { _id: platform.id }, - { metadata: { isFetchingInitialData: false } } - ) + await platformService.updatePlatform({ _id: platform.id }, { metadata: { isFetchingInitialData: false } }) } catch (error) { logger.error({ error }, 'fetchInitialData is failed') } diff --git a/bot/src/rabbitmq/events/interactionResponseCreate.ts b/bot/src/rabbitmq/events/interactionResponseCreate.ts index c86cd089..4dafdef4 100644 --- a/bot/src/rabbitmq/events/interactionResponseCreate.ts +++ b/bot/src/rabbitmq/events/interactionResponseCreate.ts @@ -8,17 +8,11 @@ const logger = parentLogger.child({ // eslint-disable-next-line @typescript-eslint/no-explicit-any export async function handleInteractionResponseCreate(msg: any): Promise { try { - logger.info( - { msg, event: Event.DISCORD_BOT.INTERACTION_RESPONSE.CREATE }, - 'is running' - ) + logger.info({ msg, event: Event.DISCORD_BOT.INTERACTION_RESPONSE.CREATE }, 'is running') const interaction = msg?.content.interaction const data = msg?.content.data await interactionService.createInteractionResponse(interaction, data) - logger.info( - { msg, event: Event.DISCORD_BOT.INTERACTION_RESPONSE.CREATE }, - 'is done' - ) + logger.info({ msg, event: Event.DISCORD_BOT.INTERACTION_RESPONSE.CREATE }, 'is done') } catch (error) { logger.error( { diff --git a/bot/src/rabbitmq/events/interactionResponseEdit.ts b/bot/src/rabbitmq/events/interactionResponseEdit.ts index f93ce6ad..e63644e3 100644 --- a/bot/src/rabbitmq/events/interactionResponseEdit.ts +++ b/bot/src/rabbitmq/events/interactionResponseEdit.ts @@ -11,15 +11,9 @@ export async function handleInteractionResponseEdit(msg: any): Promise { // logger.info({ msg, event: Event.DISCORD_BOT.INTERACTION_RESPONSE.EDIT }, 'is running'); const interaction = msg?.content.interaction const data = msg?.content.data - await interactionService.editOriginalInteractionResponse( - interaction, - data - ) + await interactionService.editOriginalInteractionResponse(interaction, data) // logger.info({ msg, event: Event.DISCORD_BOT.INTERACTION_RESPONSE.EDIT }, 'is done'); } catch (error) { - logger.error( - { msg, event: Event.DISCORD_BOT.INTERACTION_RESPONSE.EDIT, error }, - 'is failed' - ) + logger.error({ msg, event: Event.DISCORD_BOT.INTERACTION_RESPONSE.EDIT, error }, 'is failed') } } diff --git a/bot/src/rabbitmq/events/sendMessageEvent.ts b/bot/src/rabbitmq/events/sendMessageEvent.ts index 0cf3f0f3..f98266a9 100644 --- a/bot/src/rabbitmq/events/sendMessageEvent.ts +++ b/bot/src/rabbitmq/events/sendMessageEvent.ts @@ -39,8 +39,7 @@ export async function handleSendMessageEvent(msg: any): Promise { guildId: platform.metadata?.id, message: element.message, useFallback: element.useFallback, - channelId: - saga.data.safetyMessageReference.channelId, + channelId: saga.data.safetyMessageReference.channelId, announcement: true, }) } diff --git a/bot/src/scripts/cleanupCompletedJobs.ts b/bot/src/scripts/cleanupCompletedJobs.ts index d8928f47..289bdbb5 100644 --- a/bot/src/scripts/cleanupCompletedJobs.ts +++ b/bot/src/scripts/cleanupCompletedJobs.ts @@ -13,54 +13,18 @@ const logger = parentLogger.child({ module: `cleanupCompletedJobs` }) */ async function cleanAllCompletedJobs(): Promise { try { - const deletedUserEventJobIds = await userEventQueue.clean( - 0, - 500000, - 'completed' - ) - const deletedGuildExtractionJobIds = await guildExtractionQueue.clean( - 0, - 500000, - 'completed' - ) - const deletedDirectMessageJobIds = await directMessageQueue.clean( - 0, - 500000, - 'completed' - ) - const deletedChannelMessageJobIds = await channelMessageQueue.clean( - 0, - 500000, - 'completed' - ) - const deletedCronJobJobIds = await cronJobQueue.clean( - 0, - 500000, - 'completed' - ) - const deletedGuildEventJobIds = await guildEventQueue.clean( - 0, - 500000, - 'completed' - ) - logger.info( - `All GuildEvent completed jobs cleaned: ${deletedGuildEventJobIds.length} jobs removed.` - ) - logger.info( - `All CronJob completed jobs cleaned: ${deletedCronJobJobIds.length} jobs removed.` - ) - logger.info( - `All ChannelMessage completed jobs cleaned: ${deletedChannelMessageJobIds.length} jobs removed.` - ) - logger.info( - `All DirectMessage completed jobs cleaned: ${deletedDirectMessageJobIds.length} jobs removed.` - ) - logger.info( - `All GuildExtraction completed jobs cleaned: ${deletedGuildExtractionJobIds.length} jobs removed.` - ) - logger.info( - `All UserEvent completed jobs cleaned: ${deletedUserEventJobIds.length} jobs removed.` - ) + const deletedUserEventJobIds = await userEventQueue.clean(0, 500000, 'completed') + const deletedGuildExtractionJobIds = await guildExtractionQueue.clean(0, 500000, 'completed') + const deletedDirectMessageJobIds = await directMessageQueue.clean(0, 500000, 'completed') + const deletedChannelMessageJobIds = await channelMessageQueue.clean(0, 500000, 'completed') + const deletedCronJobJobIds = await cronJobQueue.clean(0, 500000, 'completed') + const deletedGuildEventJobIds = await guildEventQueue.clean(0, 500000, 'completed') + logger.info(`All GuildEvent completed jobs cleaned: ${deletedGuildEventJobIds.length} jobs removed.`) + logger.info(`All CronJob completed jobs cleaned: ${deletedCronJobJobIds.length} jobs removed.`) + logger.info(`All ChannelMessage completed jobs cleaned: ${deletedChannelMessageJobIds.length} jobs removed.`) + logger.info(`All DirectMessage completed jobs cleaned: ${deletedDirectMessageJobIds.length} jobs removed.`) + logger.info(`All GuildExtraction completed jobs cleaned: ${deletedGuildExtractionJobIds.length} jobs removed.`) + logger.info(`All UserEvent completed jobs cleaned: ${deletedUserEventJobIds.length} jobs removed.`) } catch (error) { logger.error('Failed to clean all completed jobs', error) } diff --git a/bot/src/scripts/deleteRnDAOGuildCommands.ts b/bot/src/scripts/deleteRnDAOGuildCommands.ts index 2f226b58..930ed18f 100644 --- a/bot/src/scripts/deleteRnDAOGuildCommands.ts +++ b/bot/src/scripts/deleteRnDAOGuildCommands.ts @@ -12,19 +12,10 @@ async function deleteRnDAOGuildCommands(): Promise { const rest = new REST().setToken(config.discord.botToken) const guildCommands: any = await rest.get( // RnDAO:915914985140531240 - Routes.applicationGuildCommands( - config.discord.clientId, - '915914985140531240' - ) + Routes.applicationGuildCommands(config.discord.clientId, '915914985140531240') ) guildCommands.forEach(async (command: any) => { - await rest.delete( - Routes.applicationGuildCommand( - config.discord.clientId, - '915914985140531240', - command.id - ) - ) + await rest.delete(Routes.applicationGuildCommand(config.discord.clientId, '915914985140531240', command.id)) }) } catch (error) { logger.error('Failed to delete RnDAO guild commands', error) diff --git a/bot/src/services/airflow.service.ts b/bot/src/services/airflow.service.ts index 065b4901..45734bad 100644 --- a/bot/src/services/airflow.service.ts +++ b/bot/src/services/airflow.service.ts @@ -35,29 +35,22 @@ async function triggerDag(params: DagConfig): Promise { try { // eslint-disable-next-line @typescript-eslint/restrict-template-expressions - const auth = Buffer.from( - `${config.airflow.username}:${config.airflow.password}` - ).toString('base64') + const auth = Buffer.from(`${config.airflow.username}:${config.airflow.password}`).toString('base64') // eslint-disable-next-line @typescript-eslint/restrict-template-expressions - const response = await fetch( - `${config.airflow.baseURL}/api/v1/dags/discord_guild_analyzer_etl/dagRuns`, - { - method: 'POST', - body: JSON.stringify(body), - headers: { - 'Content-Type': 'application/json', - Authorization: `Basic ${auth}`, - }, - } - ) + const response = await fetch(`${config.airflow.baseURL}/api/v1/dags/discord_guild_analyzer_etl/dagRuns`, { + method: 'POST', + body: JSON.stringify(body), + headers: { + 'Content-Type': 'application/json', + Authorization: `Basic ${auth}`, + }, + }) if (!response.ok) { const error = await response.json() logger.error({ error, body }, 'Failed to trigger DAG run') // eslint-disable-next-line @typescript-eslint/restrict-template-expressions - throw new Error( - `Airflow API call failed with status ${response.status}: ${error.message}` - ) + throw new Error(`Airflow API call failed with status ${response.status}: ${error.message}`) } else { const data = await response.json() logger.info({ data }, 'Successfully triggered DAG run') diff --git a/bot/src/services/channel.service.ts b/bot/src/services/channel.service.ts index 50888498..7d912c58 100644 --- a/bot/src/services/channel.service.ts +++ b/bot/src/services/channel.service.ts @@ -1,9 +1,4 @@ -import { - type Snowflake, - type Message, - type Channel, - type Guild, -} from 'discord.js' +import { type Snowflake, type Message, type Channel, type Guild } from 'discord.js' import coreService from './core.service' import parentLogger from '../config/logger' @@ -15,10 +10,7 @@ const logger = parentLogger.child({ module: 'ChannelService' }) * @param {string} message - message string. * @returns {Promise} - The sent message or undefined if unable to send. */ -async function sendChannelMessage( - discordId: Snowflake, - message: string -): Promise { +async function sendChannelMessage(discordId: Snowflake, message: string): Promise { const client = await coreService.DiscordBotManager.getClient() const channel = await client.channels.fetch(discordId) // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions, @typescript-eslint/prefer-optional-chain @@ -27,18 +19,12 @@ async function sendChannelMessage( } } -async function getChannelFromDiscordAPI( - guild: Guild, - channelId: Snowflake -): Promise { +async function getChannelFromDiscordAPI(guild: Guild, channelId: Snowflake): Promise { try { const channel = await guild.channels.fetch(channelId) return channel } catch (err) { - logger.error( - { guild_id: guild.id, channel_id: channelId, err }, - 'Failed to fetch channel from discord API' - ) + logger.error({ guild_id: guild.id, channel_id: channelId, err }, 'Failed to fetch channel from discord API') return null } } diff --git a/bot/src/services/command.service.ts b/bot/src/services/command.service.ts index 298c23fa..66d5d9bd 100644 --- a/bot/src/services/command.service.ts +++ b/bot/src/services/command.service.ts @@ -35,9 +35,7 @@ async function registerCommand(): Promise { try { const client = await coreService.DiscordBotManager.getClient() const rest = new REST().setToken(config.discord.botToken) - const commandData = [...client.commands.values()].map((command) => - command.data.toJSON() - ) + const commandData = [...client.commands.values()].map((command) => command.data.toJSON()) await rest.put(Routes.applicationCommands(config.discord.clientId), { body: commandData, }) diff --git a/bot/src/services/event.service.ts b/bot/src/services/event.service.ts index cf9caffb..443149a9 100644 --- a/bot/src/services/event.service.ts +++ b/bot/src/services/event.service.ts @@ -16,14 +16,10 @@ async function loadEvents(): Promise { const event = (await import(filePath)).default if (event.once === true) { // eslint-disable-next-line @typescript-eslint/no-explicit-any - client.once(event.name, (...args: any[]) => - event.execute(...args) - ) + client.once(event.name, (...args: any[]) => event.execute(...args)) } else { // eslint-disable-next-line @typescript-eslint/no-explicit-any - client.on(event.name, (...args: any[]) => - event.execute(...args) - ) + client.on(event.name, (...args: any[]) => event.execute(...args)) } } } diff --git a/bot/src/services/guild.service.ts b/bot/src/services/guild.service.ts index 83f605d6..ce5f7a81 100644 --- a/bot/src/services/guild.service.ts +++ b/bot/src/services/guild.service.ts @@ -4,18 +4,13 @@ import parentLogger from '../config/logger' const logger = parentLogger.child({ module: 'GuildService' }) -async function getGuildFromDiscordAPI( - guildId: Snowflake -): Promise { +async function getGuildFromDiscordAPI(guildId: Snowflake): Promise { try { const client = await coreService.DiscordBotManager.getClient() const guild = await client.guilds.fetch(guildId) return guild } catch (err) { - logger.error( - { guild_id: guildId, err }, - 'Failed to fetch guild from discord API' - ) + logger.error({ guild_id: guildId, err }, 'Failed to fetch guild from discord API') return null } } diff --git a/bot/src/services/interaction.service.ts b/bot/src/services/interaction.service.ts index 6e37bfe7..5300ba13 100644 --- a/bot/src/services/interaction.service.ts +++ b/bot/src/services/interaction.service.ts @@ -45,10 +45,7 @@ async function createInteractionResponse( } } catch (error) { logger.error(error, 'Failed to send interaction response') - logger.error( - { interaction_id: interaction.id, user: interaction.user }, - 'Failed to send interaction response' - ) + logger.error({ interaction_id: interaction.id, user: interaction.user }, 'Failed to send interaction response') } } @@ -58,9 +55,7 @@ async function createInteractionResponse( @param {string} redirect_uri * @returns {Promise} */ -async function getOriginalInteractionResponse( - interaction: ChatInputCommandInteraction_broker -): Promise { +async function getOriginalInteractionResponse(interaction: ChatInputCommandInteraction_broker): Promise { try { if ( interaction.token === null || @@ -68,9 +63,7 @@ async function getOriginalInteractionResponse( interaction.applicationId === null || interaction.applicationId === undefined ) { - throw new Error( - 'InteractionToken or InteractionApplicationId is null or undefined' - ) + throw new Error('InteractionToken or InteractionApplicationId is null or undefined') } const response = await fetch( @@ -112,9 +105,7 @@ async function editOriginalInteractionResponse( interaction.applicationId === null || interaction.applicationId === undefined ) { - throw new Error( - 'InteractionToken or InteractionApplicationId is null or undefined' - ) + throw new Error('InteractionToken or InteractionApplicationId is null or undefined') } const response = await fetch( @@ -146,9 +137,7 @@ async function editOriginalInteractionResponse( @param {string} redirect_uri * @returns {Promise} */ -async function deleteOriginalInteractionResponse( - interaction: ChatInputCommandInteraction_broker -): Promise { +async function deleteOriginalInteractionResponse(interaction: ChatInputCommandInteraction_broker): Promise { try { if ( interaction.token === null || @@ -156,9 +145,7 @@ async function deleteOriginalInteractionResponse( interaction.applicationId === null || interaction.applicationId === undefined ) { - throw new Error( - 'InteractionToken or InteractionApplicationId is null or undefined' - ) + throw new Error('InteractionToken or InteractionApplicationId is null or undefined') } const response = await fetch( @@ -187,10 +174,7 @@ async function deleteOriginalInteractionResponse( @param {string} redirect_uri * @returns {Promise} */ -async function createFollowUpMessage( - interaction: ChatInputCommandInteraction_broker, - data: object -): Promise { +async function createFollowUpMessage(interaction: ChatInputCommandInteraction_broker, data: object): Promise { try { if ( interaction.token === null || @@ -198,9 +182,7 @@ async function createFollowUpMessage( interaction.applicationId === null || interaction.applicationId === undefined ) { - throw new Error( - 'InteractionToken or InteractionApplicationId is null or undefined' - ) + throw new Error('InteractionToken or InteractionApplicationId is null or undefined') } const response = await fetch( @@ -219,10 +201,7 @@ async function createFollowUpMessage( } } catch (error) { logger.error(error, 'Failed to create follow up message') - logger.error( - { interaction_id: interaction.id, user: interaction.user }, - 'Failed to create follow up message' - ) + logger.error({ interaction_id: interaction.id, user: interaction.user }, 'Failed to create follow up message') } } diff --git a/bot/src/services/module.service.ts b/bot/src/services/module.service.ts index 46cea48c..355542f2 100644 --- a/bot/src/services/module.service.ts +++ b/bot/src/services/module.service.ts @@ -6,9 +6,7 @@ import { Module, type IModule } from '@togethercrew.dev/db' * @param {Object} filter - Mongo filter * @returns {Promise | null>} */ -const getModuleByFilter = async ( - filter: object -): Promise | null> => { +const getModuleByFilter = async (filter: object): Promise | null> => { return Module.findOne(filter) } diff --git a/bot/src/services/platform.service.ts b/bot/src/services/platform.service.ts index 17ac574b..a30d002d 100644 --- a/bot/src/services/platform.service.ts +++ b/bot/src/services/platform.service.ts @@ -6,9 +6,7 @@ import { Platform, type IPlatform } from '@togethercrew.dev/db' * @param {Object} filter - Mongo filter * @returns {Promise | null>} */ -const getPlatformByFilter = async ( - filter: object -): Promise | null> => { +const getPlatformByFilter = async (filter: object): Promise | null> => { return await Platform.findOne(filter) } diff --git a/bot/src/services/user.service.ts b/bot/src/services/user.service.ts index 83204af9..71d7d79a 100644 --- a/bot/src/services/user.service.ts +++ b/bot/src/services/user.service.ts @@ -1,9 +1,4 @@ -import { - type Channel, - ChannelType, - type Snowflake, - type TextChannel, -} from 'discord.js' +import { type Channel, ChannelType, type Snowflake, type TextChannel } from 'discord.js' import {} from 'discord.js' import { createPrivateThreadAndSendMessage } from '../functions/thread' import coreService from './core.service' @@ -21,10 +16,7 @@ interface IInfo { * @param {object} info - message string. * @returns {Promise} A promise that resolves with the sent message or undefined. */ -async function sendDirectMessage( - discordId: string, - info: IInfo -): Promise { +async function sendDirectMessage(discordId: string, info: IInfo): Promise { const client = await coreService.DiscordBotManager.getClient() const { guildId, message, useFallback, channelId } = info try { @@ -45,9 +37,7 @@ async function sendDirectMessage( const textChannels = arrayChannels.filter( (channel) => channel.type === ChannelType.GuildText ) as TextChannel[] - const rawPositionBasedSortedTextChannels = textChannels.sort( - (a, b) => a.rawPosition - b.rawPosition - ) + const rawPositionBasedSortedTextChannels = textChannels.sort((a, b) => a.rawPosition - b.rawPosition) channel = rawPositionBasedSortedTextChannels[0] threadName = 'TogetherCrew Status' await createPrivateThreadAndSendMessage(channel, { @@ -56,10 +46,7 @@ async function sendDirectMessage( }) } else if (info.announcement === true && channelId !== undefined) { const guild = await client.guilds.fetch(guildId) - channel = await channelService.getChannelFromDiscordAPI( - guild, - channelId - ) + channel = await channelService.getChannelFromDiscordAPI(guild, channelId) const user = await guild.members.fetch(discordId) threadName = `Private Message for ${user.user.username}` if (channel !== null && channel.type === 0) { diff --git a/hivemind-adapter/.prettierrc b/hivemind-adapter/.prettierrc index c3abc387..f0db82f1 100644 --- a/hivemind-adapter/.prettierrc +++ b/hivemind-adapter/.prettierrc @@ -3,5 +3,5 @@ "tabWidth": 4, "semi": false, "singleQuote": true, - "printWidth": 80 + "printWidth": 120 } diff --git a/hivemind-adapter/src/bot-adapter/bot.adapter.service.ts b/hivemind-adapter/src/bot-adapter/bot.adapter.service.ts index d735d7e5..ac7ae066 100644 --- a/hivemind-adapter/src/bot-adapter/bot.adapter.service.ts +++ b/hivemind-adapter/src/bot-adapter/bot.adapter.service.ts @@ -34,11 +34,7 @@ export class BotAdapterService { 'metadata.id': interaction.guildId, }) const data = this.adaptDataToHivemind(interaction, platform.community) - this.rabbitMQService.publish( - Queue.HIVEMIND, - Event.HIVEMIND.QUESTION_RECEIVED, - { ...data } - ) + this.rabbitMQService.publish(Queue.HIVEMIND, Event.HIVEMIND.QUESTION_RECEIVED, { ...data }) this.logger.info(msg, `QUESTION_COMMAND_RECEIVED event is processed`) } @@ -52,8 +48,7 @@ export class BotAdapterService { source: PlatformNames.Discord, destination: { queue: Queue.DISCORD_HIVEMIND_ADAPTER, - event: Event.DISCORD_HIVEMIND_ADAPTER - .QUESTION_COMMAND_RECEIVED, + event: Event.DISCORD_HIVEMIND_ADAPTER.QUESTION_COMMAND_RECEIVED, }, }, question: { diff --git a/hivemind-adapter/src/config/app.config.ts b/hivemind-adapter/src/config/app.config.ts index f48640c3..9afc563c 100644 --- a/hivemind-adapter/src/config/app.config.ts +++ b/hivemind-adapter/src/config/app.config.ts @@ -6,8 +6,5 @@ export default registerAs('app', () => ({ })) export const appConfigSchema = { - NODE_ENV: Joi.string() - .valid('production', 'development', 'test') - .required() - .description('Application environment'), + NODE_ENV: Joi.string().valid('production', 'development', 'test').required().description('Application environment'), } diff --git a/hivemind-adapter/src/config/index.ts b/hivemind-adapter/src/config/index.ts index 32f38654..6f8dab01 100644 --- a/hivemind-adapter/src/config/index.ts +++ b/hivemind-adapter/src/config/index.ts @@ -1,17 +1,10 @@ import * as Joi from 'joi' -import rabbitmqConfig, { - rabbitmqConfigSchema, -} from '../rabbitmq/config/rabbitmq.config' +import rabbitmqConfig, { rabbitmqConfigSchema } from '../rabbitmq/config/rabbitmq.config' import appConfig, { appConfigSchema } from './app.config' import loggerConfig, { loggerConfigSchema } from './logger.config' import mongoDBConfig, { mongoDBConfigSchema } from './mongoDB.config' -export const configModules = [ - appConfig, - rabbitmqConfig, - loggerConfig, - mongoDBConfig, -] +export const configModules = [appConfig, rabbitmqConfig, loggerConfig, mongoDBConfig] export const configValidationSchema = Joi.object({ ...appConfigSchema, diff --git a/hivemind-adapter/src/config/logger.config.ts b/hivemind-adapter/src/config/logger.config.ts index f27563fd..47a145cd 100644 --- a/hivemind-adapter/src/config/logger.config.ts +++ b/hivemind-adapter/src/config/logger.config.ts @@ -6,7 +6,5 @@ export default registerAs('logger', () => ({ })) export const loggerConfigSchema = { - LOG_LEVEL: Joi.string() - .valid('fatal', 'error', 'warn', 'info', 'debug', 'trace') - .default('info'), + LOG_LEVEL: Joi.string().valid('fatal', 'error', 'warn', 'info', 'debug', 'trace').default('info'), } diff --git a/hivemind-adapter/src/config/mongoDB.config.ts b/hivemind-adapter/src/config/mongoDB.config.ts index 5f6d301c..9c01608d 100644 --- a/hivemind-adapter/src/config/mongoDB.config.ts +++ b/hivemind-adapter/src/config/mongoDB.config.ts @@ -14,7 +14,5 @@ export const mongoDBConfigSchema = { MONGODB_PORT: Joi.string().required().description('MongoDB port'), MONGODB_USER: Joi.string().required().description('MongoDB user'), MONGODB_PASSWORD: Joi.string().required().description('MongoDB password'), - MONGODB_DB_NAME: Joi.string() - .required() - .description('MongoDB db name password'), + MONGODB_DB_NAME: Joi.string().required().description('MongoDB db name password'), } diff --git a/hivemind-adapter/src/config/pino.config.ts b/hivemind-adapter/src/config/pino.config.ts index d06316be..51a65eb2 100644 --- a/hivemind-adapter/src/config/pino.config.ts +++ b/hivemind-adapter/src/config/pino.config.ts @@ -19,8 +19,7 @@ export const pinoConfig = (configService: ConfigService) => { return { level: label.toUpperCase() } }, }, - timestamp: () => - `,"timestamp":"${new Date(Date.now()).toISOString()}"`, + timestamp: () => `,"timestamp":"${new Date(Date.now()).toISOString()}"`, }, } } diff --git a/hivemind-adapter/src/hivemind-adapter/hivemind.adapter.service.ts b/hivemind-adapter/src/hivemind-adapter/hivemind.adapter.service.ts index 5de32f39..487c4d72 100644 --- a/hivemind-adapter/src/hivemind-adapter/hivemind.adapter.service.ts +++ b/hivemind-adapter/src/hivemind-adapter/hivemind.adapter.service.ts @@ -4,10 +4,7 @@ import { PinoLogger, InjectPinoLogger } from 'nestjs-pino' import { RabbitMQService } from '../rabbitmq/rabbitmq.service' import { Question } from '../common/interfaces/hivemind.interface' import { Event, Queue } from '@togethercrew.dev/tc-messagebroker' -import { - ChatInputCommandInteraction_broker, - InteractionEditResponse, -} from '../common/interfaces/bot.interface' +import { ChatInputCommandInteraction_broker, InteractionEditResponse } from '../common/interfaces/bot.interface' @Injectable() export class HivemindAdapterService { @@ -31,11 +28,7 @@ export class HivemindAdapterService { this.logger.info(msg, `processing QUESTION_RESPONSE_RECEIVED event`) const question = msg?.content.question const data = this.adaptDataToBot(question) - this.rabbitMQService.publish( - Queue.DISCORD_BOT, - Event.DISCORD_BOT.INTERACTION_RESPONSE.EDIT, - { ...data } - ) + this.rabbitMQService.publish(Queue.DISCORD_BOT, Event.DISCORD_BOT.INTERACTION_RESPONSE.EDIT, { ...data }) this.logger.info(msg, `QUESTION_RESPONSE_RECEIVED event is processed`) } diff --git a/hivemind-adapter/src/platform/platform.module.ts b/hivemind-adapter/src/platform/platform.module.ts index ba1a3b96..76760185 100644 --- a/hivemind-adapter/src/platform/platform.module.ts +++ b/hivemind-adapter/src/platform/platform.module.ts @@ -5,11 +5,7 @@ import { platformSchema } from '@togethercrew.dev/db' import { PlatformService } from './platform.service' @Module({ - imports: [ - MongooseModule.forFeature([ - { name: 'Platform', schema: platformSchema }, - ]), - ], + imports: [MongooseModule.forFeature([{ name: 'Platform', schema: platformSchema }])], providers: [PlatformService], exports: [PlatformService], }) diff --git a/hivemind-adapter/src/platform/platform.service.ts b/hivemind-adapter/src/platform/platform.service.ts index ca9d1c18..641aa080 100644 --- a/hivemind-adapter/src/platform/platform.service.ts +++ b/hivemind-adapter/src/platform/platform.service.ts @@ -7,13 +7,9 @@ import { IPlatform } from '@togethercrew.dev/db' @Injectable() export class PlatformService { - constructor( - @InjectModel('Platform') private platformModel: Model - ) {} + constructor(@InjectModel('Platform') private platformModel: Model) {} - async getPlatform( - filter: FilterQuery - ): Promise | null> { + async getPlatform(filter: FilterQuery): Promise | null> { return this.platformModel.findOne(filter) } }