diff --git a/__tests__/fixtures/guid.fixture.ts b/__tests__/fixtures/guid.fixture.ts deleted file mode 100644 index dede6ee0..00000000 --- a/__tests__/fixtures/guid.fixture.ts +++ /dev/null @@ -1,62 +0,0 @@ -import { Types } from 'mongoose'; -import { Guild } from '@togethercrew.dev/db'; - -export const guild1 = { - guildId: '123456789', - user: '987654321', - name: 'Guild 1', - _id: new Types.ObjectId(), - selectedChannels: [ - { - channelId: '111111111', - channelName: 'Channel 1', - }, - ], - period: new Date(), - connectedAt: new Date(), - isDisconnected: false, - isInProgress: true, - icon: 'guild1.png', - window: [1, 2], // Update to have 2 numbers - action: [4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 1, 1], // Update to have 13 numbers -}; - -export const guild2 = { - guildId: '987654321', - user: '987654321', - name: 'Guild 2', - _id: new Types.ObjectId(), - selectedChannels: [ - { - channelId: '333333333', - channelName: 'Channel 3', - }, - ], - connectedAt: new Date(), - isDisconnected: true, - isInProgress: false, - icon: null, - window: [7, 8], // Update to have 2 numbers - action: [4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 1, 1], // Update to have 13 numbers -}; - -export const guild3 = { - guildId: '567890123', - user: '098765432', - name: 'Guild 3', - _id: new Types.ObjectId(), - selectedChannels: [ - { - channelId: '555555555', - channelName: 'Channel 5', - }, - ], - connectedAt: new Date(), - isDisconnected: false, - isInProgress: true, - icon: 'guild3.png', -}; - -export const insertManyGuilds = async function (guilds: Array) { - await Guild.insertMany(guilds.map((guild) => guild)); -}; diff --git a/__tests__/unit/database/services/guild.test.ts b/__tests__/unit/database/services/guild.test.ts deleted file mode 100644 index 44e32d9b..00000000 --- a/__tests__/unit/database/services/guild.test.ts +++ /dev/null @@ -1,110 +0,0 @@ -import { Guild, IGuildUpdateBody } from '@togethercrew.dev/db'; -import { guildService } from '../../../../src/database/services'; -import { - insertManyGuilds, - guild1, - guild2, -} from '../../../fixtures/guid.fixture'; -import setupTestDB from '../../../utils/setupTestDB'; - -setupTestDB(); - -describe('guildService', () => { - describe('getGuild', () => { - test('should retrieve an existing guild that matches the filter criteria', async () => { - await insertManyGuilds([guild1]); - const result = await guildService.getGuild({ guildId: guild1.guildId }); - - expect(result).toMatchObject(guild1); - }); - - test('should return null when no guild matches the filter criteria', async () => { - const result = await guildService.getGuild({}); - expect(result).toBeNull(); - }); - }); - - describe('getGuilds', () => { - test('should retrieve an existing guilds that matches the filter criteria', async () => { - await insertManyGuilds([guild1, guild2]); - const result = await guildService.getGuilds({ user: guild1.user }); - - expect(result).toMatchObject([guild1, guild2]); - }); - - test('should return null when no guilds matches the filter criteria', async () => { - const result = await guildService.getGuild({}); - expect(result).toBeNull(); - }); - }); - - describe('updateGuild', () => { - const updateBody: IGuildUpdateBody = { - selectedChannels: [ - { - channelId: '1233123213', - channelName: 'test1', - }, - ], - isDisconnected: false, - }; - test('should update an existing guild that matches the filter criteria', async () => { - await insertManyGuilds([guild1]); - const result = await guildService.updateGuild( - { guildId: guild1.guildId }, - updateBody - ); - - expect(result).toMatchObject({ - id: guild1?._id.toHexString(), - guildId: guild1.guildId, - isDisconnected: updateBody.isDisconnected, - name: guild1.name, - selectedChannels: updateBody.selectedChannels, - }); - - const dbGuild = await Guild.findById(guild1?._id); - expect(dbGuild).toBeDefined(); - expect(dbGuild).toMatchObject({ - isDisconnected: updateBody.isDisconnected, - selectedChannels: updateBody.selectedChannels, - }); - }); - test('should return null when no guild matches the filter criteria', async () => { - const result = await guildService.updateGuild( - { guildId: 'notExistId' }, - updateBody - ); - expect(result).toBeNull(); - }); - }); - - describe('updateGuilds', () => { - const updateBody: IGuildUpdateBody = { - selectedChannels: [ - { - channelId: '14151322', - channelName: 'test2', - }, - ], - isDisconnected: false, - }; - test('should update an existing guilds that matches the filter criteria', async () => { - await insertManyGuilds([guild1, guild2]); - const result = await guildService.updateManyGuilds( - { user: guild1.user }, - updateBody - ); - - expect(result).toBe(2); - }); - test('should return null when no guild matches the filter criteria', async () => { - const result = await guildService.updateManyGuilds( - { guildId: 'notExistId' }, - updateBody - ); - - expect(result).toBe(0); - }); - }); -}); diff --git a/package-lock.json b/package-lock.json index 1d79a4b1..b3cbcb27 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10,7 +10,7 @@ "license": "ISC", "dependencies": { "@sentry/node": "^7.51.2", - "@togethercrew.dev/db": "^2.5.1", + "@togethercrew.dev/db": "^3.0.18", "@togethercrew.dev/tc-messagebroker": "^0.0.40", "babel-jest": "^29.5.0", "bullmq": "^3.14.0", @@ -41,7 +41,7 @@ "eslint-plugin-promise": "^6.1.1", "jest": "^29.5.0", "node-mocks-http": "^1.12.2", - "nodemon": "^2.0.22", + "nodemon": "^3.0.1", "prettier": "^2.8.8", "supertest": "^6.3.3", "ts-jest": "^29.1.0", @@ -715,11 +715,11 @@ } }, "node_modules/@babel/code-frame": { - "version": "7.22.13", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.22.13.tgz", - "integrity": "sha512-XktuhWlJ5g+3TJXc5upd9Ks1HutSArik6jf2eAjYFyIOf4ej3RN+184cZbzDvbPnuTJIUhPKKJE3cIsYTiAT3w==", + "version": "7.23.4", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.23.4.tgz", + "integrity": "sha512-r1IONyb6Ia+jYR2vvIDhdWdlTGhqbBoFqLTQidzZ4kepUFH15ejXvFHxCVbtl7BOXIudsIubf4E81xeA3h3IXA==", "dependencies": { - "@babel/highlight": "^7.22.13", + "@babel/highlight": "^7.23.4", "chalk": "^2.4.2" }, "engines": { @@ -764,11 +764,11 @@ } }, "node_modules/@babel/generator": { - "version": "7.22.15", - "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.22.15.tgz", - "integrity": "sha512-Zu9oWARBqeVOW0dZOjXc3JObrzuqothQ3y/n1kUtrjCoCPLkXUwMvOo/F/TCfoHMbWIFlWwpZtkZVb9ga4U2pA==", + "version": "7.23.4", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.23.4.tgz", + "integrity": "sha512-esuS49Cga3HcThFNebGhlgsrVLkvhqvYDTzgjfFFlHJcIfLe5jFmRRfCQ1KuBfc4Jrtn3ndLgKWAKjBE+IraYQ==", "dependencies": { - "@babel/types": "^7.22.15", + "@babel/types": "^7.23.4", "@jridgewell/gen-mapping": "^0.3.2", "@jridgewell/trace-mapping": "^0.3.17", "jsesc": "^2.5.1" @@ -801,12 +801,12 @@ } }, "node_modules/@babel/helper-function-name": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.22.5.tgz", - "integrity": "sha512-wtHSq6jMRE3uF2otvfuD3DIvVhOsSNshQl0Qrd7qC9oQJzHvOL4qQXlQn2916+CXGywIjpGuIkoyZRRxHPiNQQ==", + "version": "7.23.0", + "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.23.0.tgz", + "integrity": "sha512-OErEqsrxjZTJciZ4Oo+eoZqeW9UIiOcuYKRJA4ZAgV9myA+pOXhhmpfNCKjEH/auVfEYVFJ6y1Tc4r0eIApqiw==", "dependencies": { - "@babel/template": "^7.22.5", - "@babel/types": "^7.22.5" + "@babel/template": "^7.22.15", + "@babel/types": "^7.23.0" }, "engines": { "node": ">=6.9.0" @@ -883,9 +883,9 @@ } }, "node_modules/@babel/helper-string-parser": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.22.5.tgz", - "integrity": "sha512-mM4COjgZox8U+JcXQwPijIZLElkgEpO5rsERVDJTc2qfCDfERyob6k5WegS14SX18IIjv+XD+GrqNumY5JRCDw==", + "version": "7.23.4", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.23.4.tgz", + "integrity": "sha512-803gmbQdqwdf4olxrX4AJyFBV/RTr3rSmOj0rKwesmzlfhYNDEs+/iOcznzpNWlJlIlTJC2QfPFcHB6DlzdVLQ==", "engines": { "node": ">=6.9.0" } @@ -920,9 +920,9 @@ } }, "node_modules/@babel/highlight": { - "version": "7.22.20", - "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.22.20.tgz", - "integrity": "sha512-dkdMCN3py0+ksCgYmGG8jKeGA/8Tk+gJwSYYlFGxG5lmhfKNoAy004YpLxpS1W2J8m/EK2Ew+yOs9pVRwO89mg==", + "version": "7.23.4", + "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.23.4.tgz", + "integrity": "sha512-acGdbYSfp2WheJoJm/EBBBLh/ID8KDc64ISZ9DYtBmC8/Q204PZJLHyzeB5qMzJ5trcOkybd78M4x2KWsUq++A==", "dependencies": { "@babel/helper-validator-identifier": "^7.22.20", "chalk": "^2.4.2", @@ -933,9 +933,9 @@ } }, "node_modules/@babel/parser": { - "version": "7.22.16", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.22.16.tgz", - "integrity": "sha512-+gPfKv8UWeKKeJTUxe59+OobVcrYHETCsORl61EmSkmgymguYk/X5bp7GuUIXaFsc6y++v8ZxPsLSSuujqDphA==", + "version": "7.23.4", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.23.4.tgz", + "integrity": "sha512-vf3Xna6UEprW+7t6EtOmFpHNAuxw3xqPZghy+brsnusscJRW5BMUzzHZc5ICjULee81WeUV2jjakG09MDglJXQ==", "bin": { "parser": "bin/babel-parser.js" }, @@ -1122,18 +1122,18 @@ } }, "node_modules/@babel/traverse": { - "version": "7.22.20", - "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.22.20.tgz", - "integrity": "sha512-eU260mPZbU7mZ0N+X10pxXhQFMGTeLb9eFS0mxehS8HZp9o1uSnFeWQuG1UPrlxgA7QoUzFhOnilHDp0AXCyHw==", + "version": "7.23.4", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.23.4.tgz", + "integrity": "sha512-IYM8wSUwunWTB6tFC2dkKZhxbIjHoWemdK+3f8/wq8aKhbUscxD5MX72ubd90fxvFknaLPeGw5ycU84V1obHJg==", "dependencies": { - "@babel/code-frame": "^7.22.13", - "@babel/generator": "^7.22.15", + "@babel/code-frame": "^7.23.4", + "@babel/generator": "^7.23.4", "@babel/helper-environment-visitor": "^7.22.20", - "@babel/helper-function-name": "^7.22.5", + "@babel/helper-function-name": "^7.23.0", "@babel/helper-hoist-variables": "^7.22.5", "@babel/helper-split-export-declaration": "^7.22.6", - "@babel/parser": "^7.22.16", - "@babel/types": "^7.22.19", + "@babel/parser": "^7.23.4", + "@babel/types": "^7.23.4", "debug": "^4.1.0", "globals": "^11.1.0" }, @@ -1142,12 +1142,12 @@ } }, "node_modules/@babel/types": { - "version": "7.22.19", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.22.19.tgz", - "integrity": "sha512-P7LAw/LbojPzkgp5oznjE6tQEIWbp4PkkfrZDINTro9zgBRtI324/EYsiSI7lhPbpIQ+DCeR2NNmMWANGGfZsg==", + "version": "7.23.4", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.23.4.tgz", + "integrity": "sha512-7uIFwVYpoplT5jp/kVv6EF93VaJ8H+Yn5IczYiaAi98ajzjfoZfslet/e0sLh+wVBjb2qqIut1b0S26VSafsSQ==", "dependencies": { - "@babel/helper-string-parser": "^7.22.5", - "@babel/helper-validator-identifier": "^7.22.19", + "@babel/helper-string-parser": "^7.23.4", + "@babel/helper-validator-identifier": "^7.22.20", "to-fast-properties": "^2.0.0" }, "engines": { @@ -1183,17 +1183,17 @@ } }, "node_modules/@discordjs/builders": { - "version": "1.6.5", - "resolved": "https://registry.npmjs.org/@discordjs/builders/-/builders-1.6.5.tgz", - "integrity": "sha512-SdweyCs/+mHj+PNhGLLle7RrRFX9ZAhzynHahMCLqp5Zeq7np7XC6/mgzHc79QoVlQ1zZtOkTTiJpOZu5V8Ufg==", - "dependencies": { - "@discordjs/formatters": "^0.3.2", - "@discordjs/util": "^1.0.1", - "@sapphire/shapeshift": "^3.9.2", - "discord-api-types": "0.37.50", + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/@discordjs/builders/-/builders-1.7.0.tgz", + "integrity": "sha512-GDtbKMkg433cOZur8Dv6c25EHxduNIBsxeHrsRoIM8+AwmEZ8r0tEpckx/sHwTLwQPOF3e2JWloZh9ofCaMfAw==", + "dependencies": { + "@discordjs/formatters": "^0.3.3", + "@discordjs/util": "^1.0.2", + "@sapphire/shapeshift": "^3.9.3", + "discord-api-types": "0.37.61", "fast-deep-equal": "^3.1.3", "ts-mixer": "^6.0.3", - "tslib": "^2.6.1" + "tslib": "^2.6.2" }, "engines": { "node": ">=16.11.0" @@ -1208,62 +1208,78 @@ } }, "node_modules/@discordjs/formatters": { - "version": "0.3.2", - "resolved": "https://registry.npmjs.org/@discordjs/formatters/-/formatters-0.3.2.tgz", - "integrity": "sha512-lE++JZK8LSSDRM5nLjhuvWhGuKiXqu+JZ/DsOR89DVVia3z9fdCJVcHF2W/1Zxgq0re7kCzmAJlCMMX3tetKpA==", + "version": "0.3.3", + "resolved": "https://registry.npmjs.org/@discordjs/formatters/-/formatters-0.3.3.tgz", + "integrity": "sha512-wTcI1Q5cps1eSGhl6+6AzzZkBBlVrBdc9IUhJbijRgVjCNIIIZPgqnUj3ntFODsHrdbGU8BEG9XmDQmgEEYn3w==", "dependencies": { - "discord-api-types": "0.37.50" + "discord-api-types": "0.37.61" }, "engines": { "node": ">=16.11.0" } }, "node_modules/@discordjs/rest": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/@discordjs/rest/-/rest-2.0.1.tgz", - "integrity": "sha512-/eWAdDRvwX/rIE2tuQUmKaxmWeHmGealttIzGzlYfI4+a7y9b6ZoMp8BG/jaohs8D8iEnCNYaZiOFLVFLQb8Zg==", + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@discordjs/rest/-/rest-2.2.0.tgz", + "integrity": "sha512-nXm9wT8oqrYFRMEqTXQx9DUTeEtXUDMmnUKIhZn6O2EeDY9VCdwj23XCPq7fkqMPKdF7ldAfeVKyxxFdbZl59A==", "dependencies": { - "@discordjs/collection": "^1.5.3", - "@discordjs/util": "^1.0.1", + "@discordjs/collection": "^2.0.0", + "@discordjs/util": "^1.0.2", "@sapphire/async-queue": "^1.5.0", "@sapphire/snowflake": "^3.5.1", "@vladfrangu/async_event_emitter": "^2.2.2", - "discord-api-types": "0.37.50", - "magic-bytes.js": "^1.0.15", - "tslib": "^2.6.1", - "undici": "5.22.1" + "discord-api-types": "0.37.61", + "magic-bytes.js": "^1.5.0", + "tslib": "^2.6.2", + "undici": "5.27.2" }, "engines": { "node": ">=16.11.0" } }, + "node_modules/@discordjs/rest/node_modules/@discordjs/collection": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-2.0.0.tgz", + "integrity": "sha512-YTWIXLrf5FsrLMycpMM9Q6vnZoR/lN2AWX23/Cuo8uOOtS8eHB2dyQaaGnaF8aZPYnttf2bkLMcXn/j6JUOi3w==", + "engines": { + "node": ">=18" + } + }, "node_modules/@discordjs/util": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@discordjs/util/-/util-1.0.1.tgz", - "integrity": "sha512-d0N2yCxB8r4bn00/hvFZwM7goDcUhtViC5un4hPj73Ba4yrChLSJD8fy7Ps5jpTLg1fE9n4K0xBLc1y9WGwSsA==", + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@discordjs/util/-/util-1.0.2.tgz", + "integrity": "sha512-IRNbimrmfb75GMNEjyznqM1tkI7HrZOf14njX7tCAAUetyZM1Pr8hX/EK2lxBCOgWDRmigbp24fD1hdMfQK5lw==", "engines": { "node": ">=16.11.0" } }, "node_modules/@discordjs/ws": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@discordjs/ws/-/ws-1.0.1.tgz", - "integrity": "sha512-avvAolBqN3yrSvdBPcJ/0j2g42ABzrv3PEL76e3YTp2WYMGH7cuspkjfSyNWaqYl1J+669dlLp+YFMxSVQyS5g==", + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@discordjs/ws/-/ws-1.0.2.tgz", + "integrity": "sha512-+XI82Rm2hKnFwAySXEep4A7Kfoowt6weO6381jgW+wVdTpMS/56qCvoXyFRY0slcv7c/U8My2PwIB2/wEaAh7Q==", "dependencies": { - "@discordjs/collection": "^1.5.3", - "@discordjs/rest": "^2.0.1", - "@discordjs/util": "^1.0.1", + "@discordjs/collection": "^2.0.0", + "@discordjs/rest": "^2.1.0", + "@discordjs/util": "^1.0.2", "@sapphire/async-queue": "^1.5.0", - "@types/ws": "^8.5.5", + "@types/ws": "^8.5.9", "@vladfrangu/async_event_emitter": "^2.2.2", - "discord-api-types": "0.37.50", - "tslib": "^2.6.1", - "ws": "^8.13.0" + "discord-api-types": "0.37.61", + "tslib": "^2.6.2", + "ws": "^8.14.2" }, "engines": { "node": ">=16.11.0" } }, + "node_modules/@discordjs/ws/node_modules/@discordjs/collection": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-2.0.0.tgz", + "integrity": "sha512-YTWIXLrf5FsrLMycpMM9Q6vnZoR/lN2AWX23/Cuo8uOOtS8eHB2dyQaaGnaF8aZPYnttf2bkLMcXn/j6JUOi3w==", + "engines": { + "node": ">=18" + } + }, "node_modules/@eslint-community/eslint-utils": { "version": "4.4.0", "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.4.0.tgz", @@ -1365,6 +1381,14 @@ "node": "^12.22.0 || ^14.17.0 || >=16.0.0" } }, + "node_modules/@fastify/busboy": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/@fastify/busboy/-/busboy-2.1.0.tgz", + "integrity": "sha512-+KpH+QxZU7O4675t3mnkQKcZZg56u+K/Ct2K+N2AZYNVK8kyeo/bI18tI8aPm3tvNNRyTWfj6s5tnGNlcbQRsA==", + "engines": { + "node": ">=14" + } + }, "node_modules/@hapi/hoek": { "version": "9.3.0", "resolved": "https://registry.npmjs.org/@hapi/hoek/-/hoek-9.3.0.tgz", @@ -2353,9 +2377,9 @@ } }, "node_modules/@sapphire/shapeshift": { - "version": "3.9.2", - "resolved": "https://registry.npmjs.org/@sapphire/shapeshift/-/shapeshift-3.9.2.tgz", - "integrity": "sha512-YRbCXWy969oGIdqR/wha62eX8GNHsvyYi0Rfd4rNW6tSVVa8p0ELiMEuOH/k8rgtvRoM+EMV7Csqz77YdwiDpA==", + "version": "3.9.3", + "resolved": "https://registry.npmjs.org/@sapphire/shapeshift/-/shapeshift-3.9.3.tgz", + "integrity": "sha512-WzKJSwDYloSkHoBbE8rkRW8UNKJiSRJ/P8NqJ5iVq7U2Yr/kriIBx2hW+wj2Z5e5EnXL1hgYomgaFsdK6b+zqQ==", "dependencies": { "fast-deep-equal": "^3.1.3", "lodash": "^4.17.21" @@ -3014,9 +3038,9 @@ } }, "node_modules/@togethercrew.dev/db": { - "version": "2.5.1", - "resolved": "https://registry.npmjs.org/@togethercrew.dev/db/-/db-2.5.1.tgz", - "integrity": "sha512-I9rf6mMTrv3x0gt81UFzNY2ximsPo11nw1KLUC04IJm0nOuQO1hLlBqeM6izhsZhXVt4aVdbOEnY//YCbpZ8uQ==", + "version": "3.0.18", + "resolved": "https://registry.npmjs.org/@togethercrew.dev/db/-/db-3.0.18.tgz", + "integrity": "sha512-LIGkRnChhja1hnHnVk9qfaZXfCoruUsYVtMvt2v4IOzFLvUt6DeVqvrvSheK5yf63ikkwdiQMLyx62WNLbtUmw==", "dependencies": { "discord.js": "^14.7.1", "joi": "^17.7.0", @@ -3307,9 +3331,9 @@ } }, "node_modules/@types/ws": { - "version": "8.5.5", - "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.5.5.tgz", - "integrity": "sha512-lwhs8hktwxSjf9UaZ9tG5M03PGogvFaH8gUgLNbN9HKIg0dvv6q+gkSuJ8HN4/VbyxkuLzCjlN7GquQ0gUJfIg==", + "version": "8.5.9", + "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.5.9.tgz", + "integrity": "sha512-jbdrY0a8lxfdTp/+r7Z4CkycbOFN8WX+IOchLJr3juT/xzbJ8URyTVSJ/hvNdadTgM1mnedb47n+Y31GsFnQlg==", "dependencies": { "@types/node": "*" } @@ -4323,17 +4347,6 @@ "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==" }, - "node_modules/busboy": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/busboy/-/busboy-1.6.0.tgz", - "integrity": "sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA==", - "dependencies": { - "streamsearch": "^1.1.0" - }, - "engines": { - "node": ">=10.16.0" - } - }, "node_modules/call-bind": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.2.tgz", @@ -4885,29 +4898,29 @@ } }, "node_modules/discord-api-types": { - "version": "0.37.50", - "resolved": "https://registry.npmjs.org/discord-api-types/-/discord-api-types-0.37.50.tgz", - "integrity": "sha512-X4CDiMnDbA3s3RaUXWXmgAIbY1uxab3fqe3qwzg5XutR3wjqi7M3IkgQbsIBzpqBN2YWr/Qdv7JrFRqSgb4TFg==" + "version": "0.37.61", + "resolved": "https://registry.npmjs.org/discord-api-types/-/discord-api-types-0.37.61.tgz", + "integrity": "sha512-o/dXNFfhBpYHpQFdT6FWzeO7pKc838QeeZ9d91CfVAtpr5XLK4B/zYxQbYgPdoMiTDvJfzcsLW5naXgmHGDNXw==" }, "node_modules/discord.js": { - "version": "14.13.0", - "resolved": "https://registry.npmjs.org/discord.js/-/discord.js-14.13.0.tgz", - "integrity": "sha512-Kufdvg7fpyTEwANGy9x7i4od4yu5c6gVddGi5CKm4Y5a6sF0VBODObI3o0Bh7TGCj0LfNT8Qp8z04wnLFzgnbA==", - "dependencies": { - "@discordjs/builders": "^1.6.5", - "@discordjs/collection": "^1.5.3", - "@discordjs/formatters": "^0.3.2", - "@discordjs/rest": "^2.0.1", - "@discordjs/util": "^1.0.1", - "@discordjs/ws": "^1.0.1", - "@sapphire/snowflake": "^3.5.1", - "@types/ws": "^8.5.5", - "discord-api-types": "0.37.50", - "fast-deep-equal": "^3.1.3", - "lodash.snakecase": "^4.1.1", - "tslib": "^2.6.1", - "undici": "5.22.1", - "ws": "^8.13.0" + "version": "14.14.1", + "resolved": "https://registry.npmjs.org/discord.js/-/discord.js-14.14.1.tgz", + "integrity": "sha512-/hUVzkIerxKHyRKopJy5xejp4MYKDPTszAnpYxzVVv4qJYf+Tkt+jnT2N29PIPschicaEEpXwF2ARrTYHYwQ5w==", + "dependencies": { + "@discordjs/builders": "^1.7.0", + "@discordjs/collection": "1.5.3", + "@discordjs/formatters": "^0.3.3", + "@discordjs/rest": "^2.1.0", + "@discordjs/util": "^1.0.2", + "@discordjs/ws": "^1.0.2", + "@sapphire/snowflake": "3.5.1", + "@types/ws": "8.5.9", + "discord-api-types": "0.37.61", + "fast-deep-equal": "3.1.3", + "lodash.snakecase": "4.1.1", + "tslib": "2.6.2", + "undici": "5.27.2", + "ws": "8.14.2" }, "engines": { "node": ">=16.11.0" @@ -8726,9 +8739,9 @@ } }, "node_modules/magic-bytes.js": { - "version": "1.0.17", - "resolved": "https://registry.npmjs.org/magic-bytes.js/-/magic-bytes.js-1.0.17.tgz", - "integrity": "sha512-PEDpPzHpKe5AxkVmQrNPHFRvPN2ELkkj3eIg4IZO9JdhBiAY3aU53lgYXs9j8B7lpza+QiW0UA4QHCH7EskSeg==" + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/magic-bytes.js/-/magic-bytes.js-1.5.0.tgz", + "integrity": "sha512-wJkXvutRbNWcc37tt5j1HyOK1nosspdh3dj6LUYYAvF6JYNqs53IfRvK9oEpcwiDA1NdoIi64yAMfdivPeVAyw==" }, "node_modules/make-dir": { "version": "4.0.0", @@ -9320,9 +9333,9 @@ "integrity": "sha512-uYr7J37ae/ORWdZeQ1xxMJe3NtdmqMC/JZK+geofDrkLUApKRHPd18/TxtBOJ4A0/+uUIliorNrfYV6s1b02eQ==" }, "node_modules/nodemon": { - "version": "2.0.22", - "resolved": "https://registry.npmjs.org/nodemon/-/nodemon-2.0.22.tgz", - "integrity": "sha512-B8YqaKMmyuCO7BowF1Z1/mkPqLk6cs/l63Ojtd6otKjMx47Dq1utxfRxcavH1I7VSaL8n5BUaoutadnsX3AAVQ==", + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/nodemon/-/nodemon-3.0.1.tgz", + "integrity": "sha512-g9AZ7HmkhQkqXkRc20w+ZfQ73cHLbE8hnPbtaFbFtCumZsjyMhKk9LajQ07U5Ux28lvFjZ5X7HvWR1xzU8jHVw==", "dev": true, "dependencies": { "chokidar": "^3.5.2", @@ -9330,8 +9343,8 @@ "ignore-by-default": "^1.0.1", "minimatch": "^3.1.2", "pstree.remy": "^1.1.8", - "semver": "^5.7.1", - "simple-update-notifier": "^1.0.7", + "semver": "^7.5.3", + "simple-update-notifier": "^2.0.0", "supports-color": "^5.5.0", "touch": "^3.1.0", "undefsafe": "^2.0.5" @@ -9340,7 +9353,7 @@ "nodemon": "bin/nodemon.js" }, "engines": { - "node": ">=8.10.0" + "node": ">=10" }, "funding": { "type": "opencollective", @@ -9356,15 +9369,39 @@ "ms": "^2.1.1" } }, + "node_modules/nodemon/node_modules/lru-cache": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", + "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", + "dev": true, + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=10" + } + }, "node_modules/nodemon/node_modules/semver": { - "version": "5.7.2", - "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.2.tgz", - "integrity": "sha512-cBznnQ9KjJqU67B52RMC65CMarK2600WFnbkcaiwWq3xy/5haFJlshgnpjovMVJ+Hff49d8GEn0b87C5pDQ10g==", + "version": "7.5.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.4.tgz", + "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==", "dev": true, + "dependencies": { + "lru-cache": "^6.0.0" + }, "bin": { - "semver": "bin/semver" + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" } }, + "node_modules/nodemon/node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", + "dev": true + }, "node_modules/nopt": { "version": "1.0.10", "resolved": "https://registry.npmjs.org/nopt/-/nopt-1.0.10.tgz", @@ -10307,26 +10344,50 @@ "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==" }, "node_modules/simple-update-notifier": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/simple-update-notifier/-/simple-update-notifier-1.1.0.tgz", - "integrity": "sha512-VpsrsJSUcJEseSbMHkrsrAVSdvVS5I96Qo1QAQ4FxQ9wXFcB+pjj7FB7/us9+GcgfW4ziHtYMc1J0PLczb55mg==", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/simple-update-notifier/-/simple-update-notifier-2.0.0.tgz", + "integrity": "sha512-a2B9Y0KlNXl9u/vsW6sTIu9vGEpfKu2wRV6l1H3XEas/0gUIzGzBoP/IouTcUQbm9JWZLH3COxyn03TYlFax6w==", "dev": true, "dependencies": { - "semver": "~7.0.0" + "semver": "^7.5.3" }, "engines": { - "node": ">=8.10.0" + "node": ">=10" + } + }, + "node_modules/simple-update-notifier/node_modules/lru-cache": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", + "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", + "dev": true, + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=10" } }, "node_modules/simple-update-notifier/node_modules/semver": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.0.0.tgz", - "integrity": "sha512-+GB6zVA9LWh6zovYQLALHwv5rb2PHGlJi3lfiqIHxR0uuwCgefcOJc59v9fv1w8GbStwxuuqqAjI9NMAOOgq1A==", + "version": "7.5.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.4.tgz", + "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==", "dev": true, + "dependencies": { + "lru-cache": "^6.0.0" + }, "bin": { "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" } }, + "node_modules/simple-update-notifier/node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", + "dev": true + }, "node_modules/sisteransi": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/sisteransi/-/sisteransi-1.0.5.tgz", @@ -10446,14 +10507,6 @@ "resolved": "https://registry.npmjs.org/standard-as-callback/-/standard-as-callback-2.1.0.tgz", "integrity": "sha512-qoRRSyROncaz1z0mvYqIE4lCd9p2R90i6GxW3uZv5ucSu8tU7B5HXUP1gG8pVZsYNVaXjk8ClXHPttLyxAL48A==" }, - "node_modules/streamsearch": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-1.1.0.tgz", - "integrity": "sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg==", - "engines": { - "node": ">=10.0.0" - } - }, "node_modules/string_decoder": { "version": "0.10.31", "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz", @@ -11103,11 +11156,11 @@ "dev": true }, "node_modules/undici": { - "version": "5.22.1", - "resolved": "https://registry.npmjs.org/undici/-/undici-5.22.1.tgz", - "integrity": "sha512-Ji2IJhFXZY0x/0tVBXeQwgPlLWw13GVzpsWPQ3rV50IFMMof2I55PZZxtm4P6iNq+L5znYN9nSTAq0ZyE6lSJw==", + "version": "5.27.2", + "resolved": "https://registry.npmjs.org/undici/-/undici-5.27.2.tgz", + "integrity": "sha512-iS857PdOEy/y3wlM3yRp+6SNQQ6xU0mmZcwRSriqk+et/cwWAtwmIGf6WkoDN2EK/AMdCO/dfXzIwi+rFMrjjQ==", "dependencies": { - "busboy": "^1.6.0" + "@fastify/busboy": "^2.0.0" }, "engines": { "node": ">=14.0" diff --git a/package.json b/package.json index d40f9545..c58495ab 100644 --- a/package.json +++ b/package.json @@ -29,7 +29,7 @@ "homepage": "https://github.com/Behzad-rabiei/tc-discordBot#readme", "dependencies": { "@sentry/node": "^7.51.2", - "@togethercrew.dev/db": "^2.5.1", + "@togethercrew.dev/db": "^3.0.18", "@togethercrew.dev/tc-messagebroker": "^0.0.40", "babel-jest": "^29.5.0", "bullmq": "^3.14.0", @@ -60,11 +60,11 @@ "eslint-plugin-promise": "^6.1.1", "jest": "^29.5.0", "node-mocks-http": "^1.12.2", - "nodemon": "^2.0.22", + "nodemon": "^3.0.1", "prettier": "^2.8.8", "supertest": "^6.3.3", "ts-jest": "^29.1.0", "ts-node": "^10.9.1", "typescript": "^5.0.4" } -} \ No newline at end of file +} diff --git a/src/database/connection.ts b/src/database/connection.ts deleted file mode 100644 index a112bf63..00000000 --- a/src/database/connection.ts +++ /dev/null @@ -1,46 +0,0 @@ -import mongoose, { Connection } from 'mongoose'; -import { - heatMapSchema, - rawInfoSchema, - MemberActivitySchema, - guildMemberSchema, - channelSchema, - roleSchema, - type IHeatMap, - type IRawInfo, - type IMemberActivity, - type IGuildMember, - type IChannel, - type IRole, -} from '@togethercrew.dev/db'; -import { type Snowflake } from 'discord.js'; - -export default class DatabaseManager { - private static instance: DatabaseManager; - private modelCache: Record = {}; - public static getInstance(): DatabaseManager { - if (typeof DatabaseManager.instance === 'undefined') { - DatabaseManager.instance = new DatabaseManager(); - } - return DatabaseManager.instance; - } - - public getTenantDb(tenantId: Snowflake): Connection { - const dbName = tenantId; - const db = mongoose.connection.useDb(dbName, { useCache: true }); - this.setupModels(db); - return db; - } - - private setupModels(db: Connection): void { - if (!this.modelCache[db.name]) { - db.model('HeatMap', heatMapSchema); - db.model('RawInfo', rawInfoSchema); - db.model('MemberActivity', MemberActivitySchema); - db.model('GuildMember', guildMemberSchema); - db.model('Channel', channelSchema); - db.model('Role', roleSchema); - this.modelCache[db.name] = true; - } - } -} diff --git a/src/database/services/guild.service.ts b/src/database/services/guild.service.ts deleted file mode 100644 index 212628a8..00000000 --- a/src/database/services/guild.service.ts +++ /dev/null @@ -1,76 +0,0 @@ -import { Guild, IGuild, IGuildUpdateBody } from '@togethercrew.dev/db'; -import { Snowflake, Client } from 'discord.js'; -import parentLogger from '../../config/logger'; - -const logger = parentLogger.child({ module: 'GuildService' }); - -/** - * get guild by query - * @param {Object} filter - * @returns {Promise} - */ -async function getGuild(filter: object): Promise { - return Guild.findOne(filter); -} - -/** - * Retrieve and return multiple guild entries that match the provided filter. - * @param {object} filter - Filter criteria to match the desired guild entries. - * @returns {Promise} - A promise that resolves to an array of matching guild entries. - */ -async function getGuilds(filter: object): Promise { - return await Guild.find(filter); -} - -/** - * Update the guild entry that matches the provided filter with the provided data. - * @param {object} filter - Filter criteria to match the desired guild entry for update. - * @param {IGuildUpdateBody} updateBody - Updated information for the guild entry. - * @returns {Promise} - A promise that resolves to the updated guild entry, or null if not found. - */ -async function updateGuild(filter: object, updateBody: IGuildUpdateBody): Promise { - try { - const guild = await Guild.findOne(filter); - if (!guild) { - return null; - } - Object.assign(guild, updateBody); - return await guild.save(); - } catch (error) { - logger.error({ database: 'RnDAO', filter, updateBody, error }, 'Failed to update guild'); - return null; - } -} - -/** - * Update multiple guild entries that match the provided filter with the provided data. - * @param {object} filter - Filter criteria to match the desired guild entries for update. - * @param {IGuildUpdateBody} updateBody - Updated information for the guild entry. - * @returns {Promise} - A promise that resolves to the number of guild entries updated. - */ -async function updateManyGuilds(filter: object, updateBody: IGuildUpdateBody): Promise { - try { - const updateResult = await Guild.updateMany(filter, updateBody); - const modifiedCount = updateResult.modifiedCount; - return modifiedCount; - } catch (error) { - logger.error({ database: 'RnDAO', filter, updateBody, error }, 'Failed to update guilds'); - return 0; - } -} - -async function checkBotAccessToGuild(client: Client, guildId: Snowflake) { - if (!client.guilds.cache.has(guildId)) { - await updateGuild({ guildId }, { isDisconnected: false }); - return false; - } - return true; -} - -export default { - getGuild, - getGuilds, - updateGuild, - updateManyGuilds, - checkBotAccessToGuild, -}; diff --git a/src/database/services/index.ts b/src/database/services/index.ts index 5d7a9d19..f1cad469 100644 --- a/src/database/services/index.ts +++ b/src/database/services/index.ts @@ -1,6 +1,6 @@ import guildMemberService from './guildMember.service'; import rawInfoService from './rawInfo.service'; -import guildService from './guild.service'; +import platformService from './platform.service'; import roleService from './role.service'; import channelService from './channel.service'; -export { guildMemberService, guildService, rawInfoService, roleService, channelService }; +export { guildMemberService, platformService, rawInfoService, roleService, channelService }; diff --git a/src/database/services/platform.service.ts b/src/database/services/platform.service.ts new file mode 100644 index 00000000..2af4dbaa --- /dev/null +++ b/src/database/services/platform.service.ts @@ -0,0 +1,85 @@ +import { HydratedDocument, ObjectId } from 'mongoose'; +import { Platform, IPlatform, IPlatformUpdateBody } from '@togethercrew.dev/db'; +import { Snowflake, Client } from 'discord.js'; +import parentLogger from '../../config/logger'; + +const logger = parentLogger.child({ module: 'PlatformService' }); + +/** + * get platform by query + * @param {Object} filter + * @returns {Promise} + */ +async function getPlatform(filter: object): Promise | null> { + return Platform.findOne(filter); +} + +/** + * Retrieve and return multiple platform entries that match the provided filter. + * @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[]> { + return await Platform.find(filter); +} + +/** + * Update the platform entry that matches the provided filter with the provided data. + * @param {object} filter - Filter criteria to match the desired platform entry for update. + * @param {IPlatformUpdateBody} updateBody - Updated information for the platform entry. + * @returns {Promise} - A promise that resolves to the updated platform entry, or null if not found. + */ +async function updatePlatform(filter: object, updateBody: IPlatformUpdateBody): Promise | null> { + try { + const platform = await Platform.findOne(filter); + if (!platform) { + return null; + } + + if (updateBody.metadata) { + updateBody.metadata = { + ...platform.metadata, + ...updateBody.metadata + }; + } + + Object.assign(platform, updateBody); + return await platform.save(); + } catch (error) { + logger.error({ database: 'Core', filter, updateBody, error }, 'Failed to update platform'); + return null; + } +} + +/** + * Update multiple platform entries that match the provided filter with the provided data. + * @param {object} filter - Filter criteria to match the desired platform entries for update. + * @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 { + 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'); + return 0; + } +} + +async function checkBotAccessToGuild(client: Client, guildId: Snowflake) { + if (!client.guilds.cache.has(guildId)) { + await updatePlatform({ 'metadata.id': guildId }, { disconnectedAt: new Date() }); + return false; + } + return true; +} + +export default { + getPlatform, + getPlatforms, + updatePlatform, + updateManyPlatforms, + checkBotAccessToGuild, +}; diff --git a/src/events/channel/channelCreate.ts b/src/events/channel/channelCreate.ts index e86dcf2d..8282b097 100644 --- a/src/events/channel/channelCreate.ts +++ b/src/events/channel/channelCreate.ts @@ -1,6 +1,6 @@ import { Events, Channel, TextChannel, VoiceChannel, CategoryChannel } from 'discord.js'; import { channelService } from '../../database/services'; -import DatabaseManager from '../../database/connection'; +import { DatabaseManager } from '@togethercrew.dev/db'; import parentLogger from '../../config/logger'; const logger = parentLogger.child({ event: 'ChannelCreate' }); diff --git a/src/events/channel/channelDelete.ts b/src/events/channel/channelDelete.ts index ee0f99c9..31b5eb55 100644 --- a/src/events/channel/channelDelete.ts +++ b/src/events/channel/channelDelete.ts @@ -1,6 +1,6 @@ import { Events, Channel, TextChannel, VoiceChannel, CategoryChannel } from 'discord.js'; -import { channelService, guildService } from '../../database/services'; -import DatabaseManager from '../../database/connection'; +import { channelService, platformService } from '../../database/services'; +import { DatabaseManager } from '@togethercrew.dev/db'; import parentLogger from '../../config/logger'; const logger = parentLogger.child({ event: 'ChannelDelete' }); @@ -16,11 +16,12 @@ export default { try { const channelDoc = await channelService.getChannel(connection, { channelId: channel.id }); await channelDoc?.softDelete(); - const guildDoc = await guildService.getGuild({ guildId: channel.guild.id }); - const updatedSelecetdChannels = guildDoc?.selectedChannels?.filter( - selectedChannel => selectedChannel.channelId !== channel.id + const platformDoc = await platformService.getPlatform({ 'metadata.id': channel.guild.id }); + const updatedSelecetdChannels = platformDoc?.metadata?.selectedChannels?.filter( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (selectedChannel: any) => selectedChannel.channelId !== channel.id ); - await guildService.updateGuild({ guildId: channel.guild.id }, { selectedChannels: updatedSelecetdChannels }); + await platformService.updatePlatform({ 'metadata.id': channel.guild.id }, { metadata: { selectedChannels: updatedSelecetdChannels } }); logger.info(logFields, 'event is done'); } catch (err) { diff --git a/src/events/channel/channelUpdate.ts b/src/events/channel/channelUpdate.ts index 43a94d36..1848d501 100644 --- a/src/events/channel/channelUpdate.ts +++ b/src/events/channel/channelUpdate.ts @@ -1,6 +1,6 @@ import { Events, Channel, TextChannel, VoiceChannel, CategoryChannel } from 'discord.js'; import { channelService } from '../../database/services'; -import DatabaseManager from '../../database/connection'; +import { DatabaseManager } from '@togethercrew.dev/db'; import parentLogger from '../../config/logger'; const logger = parentLogger.child({ event: 'ChannelUpdate' }); diff --git a/src/events/client/ready.ts b/src/events/client/ready.ts index f45ead75..84a4f6c6 100644 --- a/src/events/client/ready.ts +++ b/src/events/client/ready.ts @@ -1,9 +1,9 @@ import { Events, Client } from 'discord.js'; -import { guildService } from '../../database/services'; +import { platformService } from '../../database/services'; import fetchMembers from '../../functions/fetchMembers'; import fetchChannels from '../../functions/fetchChannels'; import fetchRoles from '../../functions/fetchRoles'; -import DatabaseManager from '../../database/connection'; +import { DatabaseManager } from '@togethercrew.dev/db'; import parentLogger from '../../config/logger'; const logger = parentLogger.child({ event: 'ClientReady' }); @@ -13,17 +13,17 @@ export default { once: true, async execute(client: Client) { logger.info('event is running'); - const guilds = await guildService.getGuilds({ isDisconnected: false }); - for (let i = 0; i < guilds.length; i++) { - const connection = DatabaseManager.getInstance().getTenantDb(guilds[i].guildId); + const platforms = await platformService.getPlatforms({ disconnectedAt: null }); + for (let i = 0; i < platforms.length; i++) { + const connection = DatabaseManager.getInstance().getTenantDb(platforms[i].metadata?.id); try { - logger.info({ guild_id: guilds[i].guildId }, 'Fetching guild members, roles,and channels'); - await fetchMembers(connection, client, guilds[i].guildId); - await fetchRoles(connection, client, guilds[i].guildId); - await fetchChannels(connection, client, guilds[i].guildId); - logger.info({ guild_id: guilds[i].guildId }, 'Fetching guild members, roles, channels is done'); + logger.info({ platform_id: platforms[i].id }, 'Fetching guild members, roles,and channels'); + await fetchMembers(connection, client, platforms[i]); + await fetchRoles(connection, client, platforms[i]); + await fetchChannels(connection, client, platforms[i]); + logger.info({ platform_id: platforms[i].metadata?.id }, 'Fetching guild members, roles, channels is done'); } catch (err) { - logger.error({ guild_id: guilds[i].guildId, err }, 'Fetching guild members, roles,and channels failed'); + logger.error({ platform_id: platforms[i].metadata?.id, err }, 'Fetching guild members, roles,and channels failed'); logger.info('event is done'); } } diff --git a/src/events/member/guildMemberAdd.ts b/src/events/member/guildMemberAdd.ts index 4004c55f..1afc1d3f 100644 --- a/src/events/member/guildMemberAdd.ts +++ b/src/events/member/guildMemberAdd.ts @@ -1,6 +1,6 @@ import { Events, GuildMember } from 'discord.js'; import { guildMemberService } from '../../database/services'; -import DatabaseManager from '../../database/connection'; +import { DatabaseManager } from '@togethercrew.dev/db'; import parentLogger from '../../config/logger'; const logger = parentLogger.child({ event: 'GuildMemberAdd' }); diff --git a/src/events/member/guildMemberRemove.ts b/src/events/member/guildMemberRemove.ts index a84f5cd1..157e66e6 100644 --- a/src/events/member/guildMemberRemove.ts +++ b/src/events/member/guildMemberRemove.ts @@ -1,6 +1,6 @@ import { Events, GuildMember } from 'discord.js'; import { guildMemberService } from '../../database/services'; -import DatabaseManager from '../../database/connection'; +import { DatabaseManager } from '@togethercrew.dev/db'; import parentLogger from '../../config/logger'; const logger = parentLogger.child({ event: 'GuildMemberRemove' }); diff --git a/src/events/member/guildMemberUpdate.ts b/src/events/member/guildMemberUpdate.ts index e90f7213..d79260db 100644 --- a/src/events/member/guildMemberUpdate.ts +++ b/src/events/member/guildMemberUpdate.ts @@ -1,7 +1,6 @@ import { Events, GuildMember } from 'discord.js'; import { guildMemberService } from '../../database/services'; -import DatabaseManager from '../../database/connection'; - +import { DatabaseManager } from '@togethercrew.dev/db'; import parentLogger from '../../config/logger'; const logger = parentLogger.child({ event: 'GuildMemberUpdate' }); diff --git a/src/events/role/roleCreate.ts b/src/events/role/roleCreate.ts index 5c2ffc94..32677c2b 100644 --- a/src/events/role/roleCreate.ts +++ b/src/events/role/roleCreate.ts @@ -1,6 +1,6 @@ import { Events, Role } from 'discord.js'; import { roleService } from '../../database/services'; -import DatabaseManager from '../../database/connection'; +import { DatabaseManager } from '@togethercrew.dev/db'; import parentLogger from '../../config/logger'; const logger = parentLogger.child({ event: 'GuildRoleCreate' }); diff --git a/src/events/role/roleDelete.ts b/src/events/role/roleDelete.ts index 386b3986..bfc200d8 100644 --- a/src/events/role/roleDelete.ts +++ b/src/events/role/roleDelete.ts @@ -1,7 +1,6 @@ import { Events, Role } from 'discord.js'; import { roleService } from '../../database/services'; -import DatabaseManager from '../../database/connection'; - +import { DatabaseManager } from '@togethercrew.dev/db'; import parentLogger from '../../config/logger'; const logger = parentLogger.child({ event: 'GuildRoleDelete' }); diff --git a/src/events/role/roleUpdate.ts b/src/events/role/roleUpdate.ts index 40012a8e..8b015e8f 100644 --- a/src/events/role/roleUpdate.ts +++ b/src/events/role/roleUpdate.ts @@ -1,6 +1,6 @@ import { Events, Role } from 'discord.js'; import { roleService } from '../../database/services'; -import DatabaseManager from '../../database/connection'; +import { DatabaseManager } from '@togethercrew.dev/db'; import parentLogger from '../../config/logger'; const logger = parentLogger.child({ event: 'GuildRoleUpdate' }); diff --git a/src/events/user/userUpdate.ts b/src/events/user/userUpdate.ts index b59fa7f0..b92b003c 100644 --- a/src/events/user/userUpdate.ts +++ b/src/events/user/userUpdate.ts @@ -1,6 +1,6 @@ import { Events, User } from 'discord.js'; -import { guildMemberService, guildService } from '../../database/services'; -import DatabaseManager from '../../database/connection'; +import { guildMemberService, platformService } from '../../database/services'; +import { DatabaseManager } from '@togethercrew.dev/db'; import parentLogger from '../../config/logger'; const logger = parentLogger.child({ event: 'UserUpdate' }); @@ -11,9 +11,9 @@ export default { const logFields = { user_id: newUser.id }; logger.info(logFields, 'event is running'); try { - const guilds = await guildService.getGuilds({}); - for (let i = 0; i < guilds.length; i++) { - const connection = DatabaseManager.getInstance().getTenantDb(guilds[i].guildId); + const platforms = await platformService.getPlatforms({ disconnectedAt: null }); + for (let i = 0; i < platforms.length; i++) { + const connection = DatabaseManager.getInstance().getTenantDb(platforms[i].metadata?.id); await guildMemberService.updateGuildMember( connection, { discordId: newUser.id }, diff --git a/src/functions/cronJon.ts b/src/functions/cronJon.ts index 3e21bfea..e9cda21f 100644 --- a/src/functions/cronJon.ts +++ b/src/functions/cronJon.ts @@ -1,22 +1,23 @@ -import { Client, Snowflake } from 'discord.js'; -import { guildService } from '../database/services'; +import { Client } from 'discord.js'; +import { Types } from 'mongoose'; +import { platformService } from '../database/services'; import { ChoreographyDict, MBConnection, Status } from '@togethercrew.dev/tc-messagebroker'; import guildExtraction from './guildExtraction'; import parentLogger from '../config/logger'; -import DatabaseManager from '../database/connection'; +import { DatabaseManager } from '@togethercrew.dev/db'; const logger = parentLogger.child({ event: 'CronJob' }); -async function createAndStartCronJobSaga(guildId: Snowflake) { +async function createAndStartCronJobSaga(platformId: Types.ObjectId) { try { const saga = await MBConnection.models.Saga.create({ status: Status.NOT_STARTED, - data: { guildId }, + data: { platformId }, choreography: ChoreographyDict.DISCORD_SCHEDULED_JOB, }); await saga.start(); } catch (err) { - logger.error({ guild_Id: guildId, err }, 'Faield to create saga'); + logger.error({ platform_Id: platformId, err }, 'Failed to create saga'); } } @@ -26,16 +27,16 @@ async function createAndStartCronJobSaga(guildId: Snowflake) { */ export default async function cronJob(client: Client) { logger.info('event is running'); - const guilds = await guildService.getGuilds({ isDisconnected: false }); - for (let i = 0; i < guilds.length; i++) { - const connection = DatabaseManager.getInstance().getTenantDb(guilds[i].guildId); + const platforms = await platformService.getPlatforms({ disconnectedAt: null }); + for (let i = 0; i < platforms.length; i++) { + const connection = DatabaseManager.getInstance().getTenantDb(platforms[i].metadata?.id); try { - logger.info({ guild_id: guilds[i].guildId }, 'is running cronJob for guild'); - await guildExtraction(connection, client, guilds[i].guildId); - await createAndStartCronJobSaga(guilds[i].guildId); - logger.info({ guild_id: guilds[i].guildId }, 'cronJob is done for guild'); + logger.info({ platform_Id: platforms[i].metadata?.id }, 'is running cronJob for platform'); + await guildExtraction(connection, client, platforms[i]); + await createAndStartCronJobSaga(platforms[i].id); + logger.info({ platform_Id: platforms[i].metadata?.id }, 'cronJob is done for platform'); } catch (err) { - logger.error({ guild_id: guilds[i].guildId, err }, 'CronJob faield for guild'); + logger.error({ platform_Id: platforms[i].metadata?.id, err }, 'CronJob Failed for platform'); } } diff --git a/src/functions/fetchChannels.ts b/src/functions/fetchChannels.ts index 4db591af..33b27e4b 100644 --- a/src/functions/fetchChannels.ts +++ b/src/functions/fetchChannels.ts @@ -1,7 +1,7 @@ -import { Client, Snowflake, TextChannel, VoiceChannel, CategoryChannel } from 'discord.js'; -import { Connection } from 'mongoose'; -import { IChannel } from '@togethercrew.dev/db'; -import { channelService, guildService } from '../database/services'; +import { Client, TextChannel, VoiceChannel, CategoryChannel } from 'discord.js'; +import { Connection, HydratedDocument } from 'mongoose'; +import { IPlatform, IChannel } from '@togethercrew.dev/db'; +import { channelService, platformService } from '../database/services'; import parentLogger from '../config/logger'; const logger = parentLogger.child({ module: 'FetchChannels' }); @@ -28,20 +28,24 @@ function pushChannelsToArray( * @param {Client} client - The discord.js client object used to fetch the guild. * @param {Snowflake} guildId - The identifier of the guild to extract text and voice channels from. */ -export default async function fetchGuildChannels(connection: Connection, client: Client, guildId: Snowflake) { +export default async function fetchGuildChannels(connection: Connection, client: Client, platform: HydratedDocument) { try { - if (!client.guilds.cache.has(guildId)) { - await guildService.updateGuild({ guildId }, { isDisconnected: false }); + + const hasBotAccessToGuild = await platformService.checkBotAccessToGuild(client, platform.metadata?.id); + logger.info({ hasBotAccessToGuild, guildId: platform.metadata?.id, type: 'channel' }) + + if (!hasBotAccessToGuild) { return; } - const guild = await client.guilds.fetch(guildId); + const guild = await client.guilds.fetch(platform.metadata?.id); const channelsToStore: IChannel[] = []; const textAndVoiceChannels = [...guild.channels.cache.values()].filter( channel => channel.type === 0 || channel.type === 2 || channel.type === 4 ) as Array; pushChannelsToArray(channelsToStore, textAndVoiceChannels); + logger.info({ channels: channelsToStore }) await channelService.createChannels(connection, channelsToStore); // assuming a 'channelService' } catch (error) { - logger.error({ guildId, error }, 'Failed to fetch channels'); + logger.error({ guild_id: platform.metadata?.id, error }, 'Failed to fetch channels'); } } diff --git a/src/functions/fetchMembers.ts b/src/functions/fetchMembers.ts index 424d9ab2..0bd981e0 100644 --- a/src/functions/fetchMembers.ts +++ b/src/functions/fetchMembers.ts @@ -1,7 +1,9 @@ -import { GuildMember, Client, Snowflake } from 'discord.js'; -import { Connection } from 'mongoose'; -import { IGuildMember } from '@togethercrew.dev/db'; -import { guildMemberService, guildService } from '../database/services'; +import { GuildMember, Client } from 'discord.js'; +import { Connection, HydratedDocument } from 'mongoose'; +import { IPlatform } from '@togethercrew.dev/db'; +import { IGuildMember, } from '@togethercrew.dev/db'; +import { guildMemberService, platformService } from '../database/services'; + import parentLogger from '../config/logger'; const logger = parentLogger.child({ module: 'FetchMembers' }); @@ -26,18 +28,20 @@ function pushMembersToArray(arr: IGuildMember[], guildMembersArray: GuildMember[ * @param {Client} client - The discord.js client object used to fetch the guild. * @param {Snowflake} guildId - The identifier of the guild to extract information from. */ -export default async function fetchGuildMembers(connection: Connection, client: Client, guildId: Snowflake) { +export default async function fetchGuildMembers(connection: Connection, client: Client, platform: HydratedDocument) { try { - if (!client.guilds.cache.has(guildId)) { - await guildService.updateGuild({ guildId }, { isDisconnected: false }); + const hasBotAccessToGuild = await platformService.checkBotAccessToGuild(client, platform.metadata?.id); + logger.info({ hasBotAccessToGuild, guildId: platform.metadata?.id, type: 'guild member' }) + + if (!hasBotAccessToGuild) { return; } - const guild = await client.guilds.fetch(guildId); + const guild = await client.guilds.fetch(platform.metadata?.id); const membersToStore: IGuildMember[] = []; const fetchMembers = await guild.members.fetch(); pushMembersToArray(membersToStore, [...fetchMembers.values()]); await guildMemberService.createGuildMembers(connection, membersToStore); } catch (error) { - logger.error({ guildId, error }, 'Failed to fetch guild members'); + logger.error({ guild_id: platform.metadata?.id, error }, 'Failed to fetch guild members'); } } diff --git a/src/functions/fetchRoles.ts b/src/functions/fetchRoles.ts index 113050fc..6c1b46ba 100644 --- a/src/functions/fetchRoles.ts +++ b/src/functions/fetchRoles.ts @@ -1,9 +1,10 @@ -import { Client, Snowflake, Role } from 'discord.js'; -import { Connection } from 'mongoose'; -import { IRole } from '@togethercrew.dev/db'; -import { roleService, guildService } from '../database/services'; +import { Client, Role } from 'discord.js'; +import { Connection, HydratedDocument } from 'mongoose'; +import { IPlatform, IRole } from '@togethercrew.dev/db'; +import { roleService, platformService } from '../database/services'; import parentLogger from '../config/logger'; + const logger = parentLogger.child({ module: 'FetchRoles' }); /** @@ -25,17 +26,19 @@ function pushRolesToArray(arr: IRole[], roleArray: Role[]): IRole[] { * @param {Client} client - The discord.js client object used to fetch the guild. * @param {Snowflake} guildId - The identifier of the guild to extract roles from. */ -export default async function fetchGuildRoles(connection: Connection, client: Client, guildId: Snowflake) { +export default async function fetchGuildRoles(connection: Connection, client: Client, platform: HydratedDocument) { try { - if (!client.guilds.cache.has(guildId)) { - await guildService.updateGuild({ guildId }, { isDisconnected: false }); + const hasBotAccessToGuild = await platformService.checkBotAccessToGuild(client, platform.metadata?.id); + logger.info({ hasBotAccessToGuild, guildId: platform.metadata?.id, type: 'role' }) + + if (!hasBotAccessToGuild) { return; } - const guild = await client.guilds.fetch(guildId); + const guild = await client.guilds.fetch(platform.metadata?.id); const rolesToStore: IRole[] = []; pushRolesToArray(rolesToStore, [...guild.roles.cache.values()]); - await roleService.createRoles(connection, rolesToStore); // assuming a 'roleService' + await roleService.createRoles(connection, rolesToStore); } catch (error) { - logger.error({ guildId, error }, 'Failed to fetch roles'); + logger.error({ guild_id: platform.metadata?.id, error }, 'Failed to fetch roles'); } } diff --git a/src/functions/guildExtraction.ts b/src/functions/guildExtraction.ts index 79eb31ff..f24b5c55 100644 --- a/src/functions/guildExtraction.ts +++ b/src/functions/guildExtraction.ts @@ -1,9 +1,12 @@ -import { Client, Snowflake } from 'discord.js'; -import { guildService } from '../database/services'; +import { Client } from 'discord.js'; +import { Connection, HydratedDocument } from 'mongoose'; +import { IPlatform } from '@togethercrew.dev/db'; +import { platformService } from '../database/services'; import handleFetchChannelMessages from './fetchMessages'; -import { Connection } from 'mongoose'; import parentLogger from '../config/logger'; +console.log('FLAG - isInProgress Update?? || selectedChannels array of object to string') + const logger = parentLogger.child({ module: 'GuildExtraction' }); /** * Extracts information from a given guild. @@ -11,28 +14,27 @@ const logger = parentLogger.child({ module: 'GuildExtraction' }); * @param {Client} client - The discord.js client object used to fetch the guild. * @param {Snowflake} guildId - The identifier of the guild to extract information from. */ -export default async function guildExtraction(connection: Connection, client: Client, guildId: Snowflake) { - logger.info({ guild_id: guildId }, 'Guild extraction for guild is running'); +export default async function guildExtraction(connection: Connection, client: Client, platform: HydratedDocument) { + logger.info({ guild_id: platform.metadata?.id }, 'Guild extraction for guild is running'); try { - const hasBotAccessToGuild = await guildService.checkBotAccessToGuild(client, guildId); + const hasBotAccessToGuild = await platformService.checkBotAccessToGuild(client, platform.metadata?.id); if (!hasBotAccessToGuild) { return; } - const guild = await client.guilds.fetch(guildId); - const guildDoc = await guildService.getGuild({ guildId }); - if (guildDoc && guildDoc.selectedChannels && guildDoc.period) { - await guildService.updateGuild({ guildId }, { isInProgress: true }); - const selectedChannelsIds = guildDoc.selectedChannels.map(selectedChannel => selectedChannel.channelId); - for (const channelId of selectedChannelsIds) { - const channel = await guild.channels.fetch(channelId); + const guild = await client.guilds.fetch(platform.metadata?.id); + 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 guild.channels.fetch(platform.metadata?.selectedChannels[i]); if (channel) { if (channel.type !== 0) continue; - await handleFetchChannelMessages(connection, channel, guildDoc?.period); + await handleFetchChannelMessages(connection, channel, platform.metadata?.period); } } } } catch (err) { - logger.error({ guild_id: guildId, 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: guildId }, 'Guild extraction for guild is done'); + logger.info({ guild_id: platform.metadata?.id }, 'Guild extraction for guild is done'); } diff --git a/src/index.ts b/src/index.ts index 1dfae76a..cfe29625 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,4 +1,6 @@ import { Channel, ChannelType, Client, GatewayIntentBits, Snowflake, TextChannel } from 'discord.js'; +import { HydratedDocument } from 'mongoose'; +import { IPlatform } from '@togethercrew.dev/db' import config from './config'; import * as Sentry from '@sentry/node'; import loadEvents from './functions/loadEvents'; @@ -7,7 +9,7 @@ import { Queue, Worker, Job } from 'bullmq'; import RabbitMQ, { Event, MBConnection, Queue as RabbitMQQueue } from '@togethercrew.dev/tc-messagebroker'; // import './rabbitmqEvents' // we need this import statement here to initialize RabbitMQ events import { connectDB } from './database'; -import { databaseService } from '@togethercrew.dev/db'; +import { DatabaseManager } from '@togethercrew.dev/db'; import guildExtraction from './functions/guildExtraction'; import sendDirectMessage from './functions/sendDirectMessage'; import { createPrivateThreadAndSendMessage } from './functions/thread'; @@ -15,7 +17,7 @@ import fetchMembers from './functions/fetchMembers'; import fetchChannels from './functions/fetchChannels'; import fetchRoles from './functions/fetchRoles'; import parentLogger from './config/logger'; -import DatabaseManager from './database/connection'; +import { platformService } from './database/services'; const logger = parentLogger.child({ module: 'App' }); @@ -42,20 +44,25 @@ const partial = func(...args, ...rest); const fetchMethod = async (msg: any) => { + logger.info({ msg }, 'fetchMethod is running'); if (!msg) return; const { content } = msg; const saga = await MBConnection.models.Saga.findOne({ sagaId: content.uuid }); logger.info({ saga: saga.data }, 'the saga info'); - const guildId = saga.data['guildId']; - const isGuildCreated = saga.data['created']; - const connection = DatabaseManager.getInstance().getTenantDb(guildId); - if (isGuildCreated) { - await fetchMembers(connection, client, guildId); - await fetchRoles(connection, client, guildId); - await fetchChannels(connection, client, guildId); - } else { - await guildExtraction(connection, client, guildId); + const platformId = saga.data['platformId']; + const platform = await platformService.getPlatform({ _id: platformId }); + + if (platform) { + const isPlatformCreated = saga.data['created']; + const connection = DatabaseManager.getInstance().getTenantDb(platform.metadata?.id); + if (isPlatformCreated) { + await fetchChannels(connection, client, platform); + await fetchMembers(connection, client, platform); + await fetchRoles(connection, client, platform); + } else { + await guildExtraction(connection, client, platform); + } } logger.info({ msg }, 'fetchMethod is done'); }; @@ -90,11 +97,15 @@ const notifyUserAboutAnalysisFinish = async ( } }; -const fetchInitialData = async (guildId: Snowflake) => { - const connection = DatabaseManager.getInstance().getTenantDb(guildId); - await fetchRoles(connection, client, guildId); - await fetchChannels(connection, client, guildId); - await fetchMembers(connection, client, guildId); +const fetchInitialData = async (platform: HydratedDocument) => { + try { + const connection = DatabaseManager.getInstance().getTenantDb(platform.metadata?.id); + await fetchChannels(connection, client, platform); + await fetchRoles(connection, client, platform); + await fetchMembers(connection, client, platform); + } catch (error) { + logger.error({ error }, 'fetchInitialData is failed'); + } }; // APP @@ -120,15 +131,20 @@ async function app() { ); RabbitMQ.onEvent(Event.DISCORD_BOT.FETCH, async msg => { - logger.info({ msg, event: Event.DISCORD_BOT.FETCH }, 'is running'); - if (!msg) return; + try { + logger.info({ msg, event: Event.DISCORD_BOT.FETCH }, 'is running'); + if (!msg) return; - const { content } = msg; - const saga = await MBConnection.models.Saga.findOne({ sagaId: content.uuid }); + const { content } = msg; + const saga = await MBConnection.models.Saga.findOne({ sagaId: content.uuid }); - const fn = partial(fetchMethod, msg); - await saga.next(fn); - logger.info({ msg, event: Event.DISCORD_BOT.FETCH }, 'is done'); + const fn = partial(fetchMethod, msg); + await saga.next(fn); + logger.info({ msg, event: Event.DISCORD_BOT.FETCH }, 'is done'); + } catch (error) { + logger.error({ msg, event: Event.DISCORD_BOT.FETCH_MEMBERS, error }, 'is failed'); + + } }); RabbitMQ.onEvent(Event.DISCORD_BOT.SEND_MESSAGE, async msg => { @@ -138,28 +154,40 @@ async function app() { const { content } = msg; const saga = await MBConnection.models.Saga.findOne({ sagaId: content.uuid }); - const guildId = saga.data['guildId']; - const discordId = saga.data['discordId']; + const platformId = saga.data['platformId']; + const platform = await platformService.getPlatform({ _id: platformId }); const discordId = saga.data['discordId']; const message = saga.data['message']; const useFallback = saga.data['useFallback']; - const fn = notifyUserAboutAnalysisFinish.bind({}, discordId, { guildId, message, useFallback }); - await saga.next(fn); + if (platform) { + const fn = notifyUserAboutAnalysisFinish.bind({}, discordId, { guildId: platform.metadata?.id, message, useFallback }); + await saga.next(fn); + } + logger.info({ msg, event: Event.DISCORD_BOT.SEND_MESSAGE }, 'is done'); }); RabbitMQ.onEvent(Event.DISCORD_BOT.FETCH_MEMBERS, async msg => { - logger.info({ msg, event: Event.DISCORD_BOT.FETCH_MEMBERS }, 'is running'); - if (!msg) return; + try { + logger.info({ msg, event: Event.DISCORD_BOT.FETCH_MEMBERS }, 'is running'); + if (!msg) return; - const { content } = msg; - const saga = await MBConnection.models.Saga.findOne({ sagaId: content.uuid }); + const { content } = msg; + const saga = await MBConnection.models.Saga.findOne({ sagaId: content.uuid }); - const guildId = saga.data['guildId']; + const platformId = saga.data['platformId']; + + const platform = await platformService.getPlatform({ _id: platformId }); + + if (platform) { + const fn = fetchInitialData.bind({}, platform); + await saga.next(fn); + } + logger.info({ msg, event: Event.DISCORD_BOT.FETCH_MEMBERS }, 'is done'); + } catch (error) { + logger.error({ msg, event: Event.DISCORD_BOT.FETCH_MEMBERS, error }, 'is failed'); + } - const fn = fetchInitialData.bind({}, guildId); - await saga.next(fn); - logger.info({ msg, event: Event.DISCORD_BOT.FETCH_MEMBERS }, 'is done'); }); // *****************************BULLMQ diff --git a/src/migrations/db/1695210587863-add-isgeneratedbyweebhook-to-rawinfo-schema.ts b/src/migrations/db/1695210587863-add-isgeneratedbyweebhook-to-rawinfo-schema.ts index 2251b71d..4dc290b5 100644 --- a/src/migrations/db/1695210587863-add-isgeneratedbyweebhook-to-rawinfo-schema.ts +++ b/src/migrations/db/1695210587863-add-isgeneratedbyweebhook-to-rawinfo-schema.ts @@ -1,10 +1,10 @@ import 'dotenv/config'; -import { Client, GatewayIntentBits } from 'discord.js'; -import { guildService } from '../../database/services'; +import { Client, GatewayIntentBits, } from 'discord.js'; +import { platformService } from '../../database/services'; import { connectDB } from '../../database'; import config from '../../config'; import webhookLogic from '../utils/webhookLogic'; -import DatabaseManager from '../../database/connection'; +import { DatabaseManager } from '@togethercrew.dev/db'; const { Guilds, GuildMembers, GuildMessages, GuildPresences, DirectMessages } = GatewayIntentBits; @@ -15,10 +15,10 @@ export const up = async () => { await client.login(config.discord.botToken); await connectDB(); - const guilds = await guildService.getGuilds({}); - for (let i = 0; i < guilds.length; i++) { - const connection = DatabaseManager.getInstance().getTenantDb(guilds[i].guildId); - await webhookLogic(connection, client, guilds[i].guildId); + const platforms = await platformService.getPlatforms({}); + for (let i = 0; i < platforms.length; i++) { + const connection = DatabaseManager.getInstance().getTenantDb(platforms[i].metadata?.id); + await webhookLogic(connection, client, platforms[i].metadata?.id); } }; diff --git a/src/migrations/utils/template.ts b/src/migrations/utils/template.ts index 2361177c..7f34638e 100644 --- a/src/migrations/utils/template.ts +++ b/src/migrations/utils/template.ts @@ -1,6 +1,6 @@ import { connectDB } from '../../database'; import 'dotenv/config'; -import DatabaseManager from '../../database/connection'; +import { DatabaseManager } from '@togethercrew.dev/db'; export const up = async () => { await connectDB();