Skip to content

Commit

Permalink
feat: Add mongodb as a default database for application
Browse files Browse the repository at this point in the history
Signed-off-by: Michal Drla <michal.drla@outlook.com>
  • Loading branch information
mimotej committed Sep 9, 2023
1 parent acec59b commit d5f5d5e
Show file tree
Hide file tree
Showing 11 changed files with 258 additions and 126 deletions.
1 change: 1 addition & 0 deletions jest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
setupFilesAfterEnv: ['<rootDir>/tests/utils/singletonPrisma.ts'],
};
78 changes: 78 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
"homepage": "https://github.com/OqixDevs/OqixTS#readme",
"dependencies": {
"@discordjs/rest": "2.0.0",
"@prisma/client": "^5.2.0",
"discord-api-types": "0.37.52",
"discord.js": "14.12.1",
"dotenv": "16.3.1",
Expand All @@ -47,11 +48,15 @@
"eslint": "8.47.0",
"jest": "29.6.2",
"prettier": "3.0.1",
"prisma": "^5.2.0",
"ts-jest": "29.1.1",
"ts-node": "10.9.1",
"typescript": "5.1.6"
},
"optionalDependencies": {
"nodemon": "3.0.1"
},
"prisma": {
"schema": "src/model/schema.prisma"
}
}
2 changes: 2 additions & 0 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@ import { SubjectChannels } from './utils';
export default () => {
dotenv.config();
const token = process.env.DISCORD_TOKEN; // add your token here

console.log('Bot is starting...');

const client = new Client({
intents: [
GatewayIntentBits.Guilds,
Expand Down
78 changes: 45 additions & 33 deletions src/commands/verify.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { ChatInputCommandInteraction, SlashCommandBuilder } from 'discord.js';
import { sanitizeUrl } from '@braintree/sanitize-url';
import { assignRole, scrapeConfirmationStudies, scrapeThesis } from '../utils';
import * as fs from 'fs';
import { prisma } from '../model';

/**
* Takes URL to confirmation of studies and thesis and if the data scraped from websites are correct verifies user with role.
Expand All @@ -28,14 +28,6 @@ export const data = new SlashCommandBuilder()
);

export async function execute(interaction: ChatInputCommandInteraction) {
let userLog = undefined;
try {
userLog = fs.readFileSync('./userLog.json', 'utf8');
} catch (e) {
fs.writeFileSync('./userLog.json', '[]');
userLog = fs.readFileSync('./userLog.json', 'utf8');
}
const userLogJSON = JSON.parse(userLog);
const idConfirmationMuni = interaction.options.getString(
'linktoconfirmationmuni'
);
Expand All @@ -50,39 +42,61 @@ export async function execute(interaction: ChatInputCommandInteraction) {
const idConfirmationMuniParsedUrl = new URL(
sanitizeUrl(idConfirmationMuni)
);
for (const key in userLogJSON) {
if (interaction.user.id === userLogJSON[key].id) {
return interaction.reply({
content:
'User already verified! Contact admin if you need to verify again.',
ephemeral: true,
});
} else if (
userLogJSON[key].idThesis ===
bachelorThesisParsedUrl.pathname.split('/')[3]
) {
return interaction.reply({
content: 'This thesis is already used! Please contact admin.',
ephemeral: true,
});
}

await interaction.reply({
content: 'Verifying, wait please...',
ephemeral: true,
});
let user;
try {
user = await prisma.users.findMany({
where: {
discordId: interaction.user.id,
},
});
} catch (err) {
console.log(`Database error: ${err}`);
return interaction.editReply({
content: 'Verification failed! Contact admin.',
});
}
if (user.length != 0) {
return interaction.editReply({
content:
'User already verified! Contact admin if you need to verify again.',
});
}
try {
user = await prisma.users.findMany({
where: {
idThesis: bachelorThesisParsedUrl.pathname.split('/')[3],
},
});
} catch (err) {
console.log(`Database error: ${err}`);
return interaction.editReply({
content: 'Verification failed! Contact admin.',
});
}
if (user.length != 0) {
return interaction.editReply({
content: 'This thesis is already used! Please contact admin.',
});
}
const authorName = await scrapeThesis(bachelorThesisParsedUrl.pathname);
if (!authorName) {
return interaction.reply({
return interaction.editReply({
content:
'Could not get the author name. Maybe thesis URL is wrong or the website did not respond.',
ephemeral: true,
});
}
const scrapedConfirmationStudy = await scrapeConfirmationStudies(
idConfirmationMuniParsedUrl.pathname
);
if (!scrapedConfirmationStudy) {
return interaction.reply({
return interaction.editReply({
content:
'Could not get infromation from the confirmation of studies. Maybe confirmation of studies URL is wrong or the website did not respond.',
ephemeral: true,
});
}

Expand All @@ -93,17 +107,15 @@ export async function execute(interaction: ChatInputCommandInteraction) {
bachelorThesisParsedUrl
);
if (roleProgramm) {
return interaction.reply({
return interaction.editReply({
content:
'You have been successfully verified with role ' +
roleProgramm.name +
'.',
ephemeral: true,
});
}
return interaction.reply({
return interaction.editReply({
content:
'Verification failed check if you entered the correct information or contact admin.',
ephemeral: true,
});
}
1 change: 1 addition & 0 deletions src/model/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './prisma';
3 changes: 3 additions & 0 deletions src/model/prisma.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { PrismaClient } from '@prisma/client';

export const prisma = new PrismaClient();
15 changes: 15 additions & 0 deletions src/model/schema.prisma
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
generator client {
provider = "prisma-client-js"
}

datasource database {
provider = "mongodb"
url = env("DATABASE_CONNECTION_STRING")
}

model Users {
id String @id @default(auto()) @map("_id") @database.ObjectId
discordId String @map("id")
idThesis String?
status String
}
29 changes: 14 additions & 15 deletions src/utils/assignRole.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { CommandInteraction, GuildMember } from 'discord.js';
import * as fs from 'fs';
import { prisma } from '../model';

interface Dictionary<T> {
[Key: string]: T;
Expand All @@ -25,14 +25,6 @@ export async function assignRole(
authorName: string,
bachelorThesisParsedUrl: URL
) {
let userLog = undefined;
try {
userLog = fs.readFileSync('./userLog.json', 'utf8');
} catch (e) {
fs.writeFileSync('./userLog.json', '[]');
userLog = fs.readFileSync('./userLog.json', 'utf8');
}
const userLogJSON = JSON.parse(userLog);
const today = new Date();
if (
scrapedConfirmationStudy[
Expand All @@ -59,12 +51,19 @@ export async function assignRole(
programme_roles[scrapedConfirmationStudy['Programme']]
);
const member = interaction.member as GuildMember;
userLogJSON.push({
id: interaction.user.id,
idThesis: bachelorThesisParsedUrl.pathname.split('/')[3],
status: 'verified',
});
fs.writeFileSync('./userLog.json', JSON.stringify(userLogJSON));
try {
await prisma.users.create({
data: {
discordId: interaction.user.id,
idThesis:
bachelorThesisParsedUrl.pathname.split('/')[3],
status: 'verified',
},
});
} catch (err) {
console.log(`Database error: ${err}`);
return undefined;
}
if (roleVerified && roleProgramm) {
member.roles.add(roleVerified);
member.roles.add(roleProgramm);
Expand Down
15 changes: 15 additions & 0 deletions tests/utils/singletonPrisma.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { PrismaClient } from '@prisma/client';
import { mockDeep, mockReset, DeepMockProxy } from 'jest-mock-extended';

import { prisma } from '../../src/model';

jest.mock('../../src/model', () => ({
__esModule: true,
prisma: mockDeep<PrismaClient>(),
}));

beforeEach(() => {
mockReset(prismaMock);
});

export const prismaMock = prisma as unknown as DeepMockProxy<PrismaClient>;
Loading

0 comments on commit d5f5d5e

Please sign in to comment.