Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added MongoDB Support (Might requires a new branch) #162

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 1 addition & 5 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,7 @@ TEST_GUILD_ID="TEST_GUILD_ID"
BOT_OWNER_ID="YOUR_DISCORD_ID"

# database
# DATABASE_HOST="database" # if you use docker-compose, it should be the name of the service hosting the database
# DATABASE_PORT=5432
# DATABASE_NAME="tscord_bot"
# DATABASE_USER="tscord"
# DATABASE_PASSWORD="tscord123"
DATABASE_HOST="mongodb+srv://<user>:<password>@<host>/<databasename>?retryWrites=true&w=majority"

# api
# API_PORT=4000
Expand Down
18 changes: 18 additions & 0 deletions package-lock.json

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

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
"@mikro-orm/core": "~5.6.16",
"@mikro-orm/mariadb": "~5.6.16",
"@mikro-orm/migrations": "~5.6.16",
"@mikro-orm/migrations-mongodb": "~5.6.16",
"@mikro-orm/mongodb": "~5.6.16",
"@mikro-orm/mysql": "~5.6.16",
"@mikro-orm/postgresql": "~5.6.16",
Expand Down
78 changes: 40 additions & 38 deletions src/api/controllers/database.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { BodyParams, Controller, Get, Post, UseBefore } from '@tsed/common'

Check failure on line 1 in src/api/controllers/database.ts

View workflow job for this annotation

GitHub Actions / Build

'BodyParams' is defined but never used

Check failure on line 1 in src/api/controllers/database.ts

View workflow job for this annotation

GitHub Actions / Build

'Get' is defined but never used

Check failure on line 1 in src/api/controllers/database.ts

View workflow job for this annotation

GitHub Actions / Build

'Post' is defined but never used
import { InternalServerError } from '@tsed/exceptions'

Check failure on line 2 in src/api/controllers/database.ts

View workflow job for this annotation

GitHub Actions / Build

'InternalServerError' is defined but never used
import { Required } from '@tsed/schema'

Check failure on line 3 in src/api/controllers/database.ts

View workflow job for this annotation

GitHub Actions / Build

'Required' is defined but never used

import { DevAuthenticated } from '@/api/middlewares'
import { databaseConfig } from '@/configs'

Check failure on line 6 in src/api/controllers/database.ts

View workflow job for this annotation

GitHub Actions / Build

'databaseConfig' is defined but never used
import { Injectable } from '@/decorators'
import { Database } from '@/services'
import { BaseController } from '@/utils/classes'
import { formatDate, resolveDependencies } from '@/utils/functions'

Check failure on line 10 in src/api/controllers/database.ts

View workflow job for this annotation

GitHub Actions / Build

'formatDate' is defined but never used

@Controller('/database')
@UseBefore(
Expand All @@ -26,50 +26,52 @@
})
}

@Post('/backup')
async generateBackup() {
const snapshotName = `snapshot-${formatDate(new Date(), 'onlyDateFileName')}-manual-${Date.now()}`
const success = await this.db.backup(snapshotName)
// Commented due to Type Issues from MicroORM

if (success) {
return {
message: 'Backup generated',
data: {
snapshotName: `${snapshotName}.txt`,
},
}
} else {
throw new InternalServerError('Couldn\'t generate backup, see the logs for more information')
}
}
// @Post('/backup')
// async generateBackup() {
// const snapshotName = `snapshot-${formatDate(new Date(), 'onlyDateFileName')}-manual-${Date.now()}`
// const success = await this.db.backup(snapshotName)

@Post('/restore')
async restoreBackup(
@Required() @BodyParams('snapshotName') snapshotName: string
) {
const success = await this.db.restore(snapshotName)
// if (success) {
// return {
// message: 'Backup generated',
// data: {
// snapshotName: `${snapshotName}.txt`,
// },
// }
// } else {
// throw new InternalServerError('Couldn\'t generate backup, see the logs for more information')
// }
// }

if (success)
return { message: 'Backup restored' }
else throw new InternalServerError('Couldn\'t restore backup, see the logs for more information')
}
// @Post('/restore')
// async restoreBackup(
// @Required() @BodyParams('snapshotName') snapshotName: string

Check failure on line 50 in src/api/controllers/database.ts

View workflow job for this annotation

GitHub Actions / Build

Expected indentation of 1 tab but found 4 spaces
// ) {
// const success = await this.db.restore(snapshotName)

@Get('/backups')
async getBackups() {
const backupPath = databaseConfig.backup.path
if (!backupPath)
throw new InternalServerError('Backup path not set, couldn\'t find backups')
// if (success)
// return { message: 'Backup restored' }
// else throw new InternalServerError('Couldn\'t restore backup, see the logs for more information')
// }

const backupList = this.db.getBackupList()
// @Get('/backups')
// async getBackups() {
// const backupPath = databaseConfig.backup.path
// if (!backupPath)
// throw new InternalServerError('Backup path not set, couldn\'t find backups')

if (backupList)
return backupList
else throw new InternalServerError('Couldn\'t get backup list, see the logs for more information')
}
// const backupList = this.db.getBackupList()

@Get('/size')
async size() {
return await this.db.getSize()
}
// if (backupList)
// return backupList
// else throw new InternalServerError('Couldn\'t get backup list, see the logs for more information')
// }

// @Get('/size')
// async size() {
// return await this.db.getSize()
// }

}
2 changes: 1 addition & 1 deletion src/commands/Admin/prefix.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export default class PrefixCommand {
{ localize }: InteractionData
) {
const guild = resolveGuild(interaction)
const guildData = await this.db.get(Guild).findOne({ id: guild?.id || '' })
const guildData = await this.db.get(Guild).findOne({ guildId: guild?.id || '' })

if (guildData) {
guildData.prefix = prefix || null
Expand Down
8 changes: 4 additions & 4 deletions src/configs/database.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,14 +27,14 @@
/**
* SQLite
*/
type: 'better-sqlite', // or 'sqlite'
dbName: `${databaseConfig.path}db.sqlite`,
//type: 'better-sqlite', // or 'sqlite'

Check failure on line 30 in src/configs/database.ts

View workflow job for this annotation

GitHub Actions / Build

Expected exception block, space or tab after '//' in comment
//dbName: `${databaseConfig.path}db.sqlite`,

Check failure on line 31 in src/configs/database.ts

View workflow job for this annotation

GitHub Actions / Build

Expected exception block, space or tab after '//' in comment

/**
* MongoDB
*/
// type: 'mongo',
// clientUrl: env['DATABASE_HOST'],
type: 'mongo',
clientUrl: env['DATABASE_HOST'],

/**
* PostgreSQL
Expand Down
8 changes: 7 additions & 1 deletion src/entities/BaseEntity.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
import { Property } from '@mikro-orm/core'
import { PrimaryKey, Property, SerializedPrimaryKey } from "@mikro-orm/core"
import { ObjectId } from "@mikro-orm/mongodb";

export abstract class CustomBaseEntity {
@PrimaryKey()
_id: ObjectId;

@SerializedPrimaryKey()
id!: string; // won't be saved in the database

@Property()
createdAt: Date = new Date()
Expand Down
8 changes: 4 additions & 4 deletions src/entities/Guild.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Entity, EntityRepositoryType, PrimaryKey, Property } from '@mikro-orm/core'
import { Entity, EntityRepositoryType, Property } from '@mikro-orm/core'
import { EntityRepository } from '@mikro-orm/sqlite'

import { CustomBaseEntity } from './BaseEntity'
Expand All @@ -12,8 +12,8 @@ export class Guild extends CustomBaseEntity {

[EntityRepositoryType]?: GuildRepository

@PrimaryKey({ autoincrement: false })
id!: string
@Property()
guildId!: string

@Property({ nullable: true, type: 'string' })
prefix: string | null
Expand All @@ -33,7 +33,7 @@ export class Guild extends CustomBaseEntity {
export class GuildRepository extends EntityRepository<Guild> {

async updateLastInteract(guildId?: string): Promise<void> {
const guild = await this.findOne({ id: guildId })
const guild = await this.findOne({ guildId })

if (guild) {
guild.lastInteract = new Date()
Expand Down
3 changes: 0 additions & 3 deletions src/entities/Image.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,6 @@ export class Image extends CustomBaseEntity {

[EntityRepositoryType]?: ImageRepository

@PrimaryKey()
id: number

@Property()
fileName: string

Expand Down
10 changes: 7 additions & 3 deletions src/entities/Pastebin.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Entity, EntityRepositoryType, PrimaryKey, Property } from '@mikro-orm/core'
import { Entity, EntityRepositoryType, PrimaryKey, Property, SerializedPrimaryKey } from '@mikro-orm/core'
import { ObjectId } from '@mikro-orm/mongodb';
import { EntityRepository } from '@mikro-orm/sqlite'

// ===========================================
Expand All @@ -10,8 +11,11 @@ export class Pastebin {

[EntityRepositoryType]?: PastebinRepository

@PrimaryKey({ autoincrement: false })
id: string
@PrimaryKey()
_id: ObjectId;

@SerializedPrimaryKey()
id!: string; // won't be saved in the database

@Property()
editCode: string
Expand Down
8 changes: 6 additions & 2 deletions src/entities/Stat.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Entity, EntityRepositoryType, PrimaryKey, Property } from '@mikro-orm/core'
import { Entity, EntityRepositoryType, PrimaryKey, Property, SerializedPrimaryKey } from '@mikro-orm/core'
import { ObjectId } from '@mikro-orm/mongodb';
import { EntityRepository } from '@mikro-orm/sqlite'

// ===========================================
Expand All @@ -11,7 +12,10 @@ export class Stat {
[EntityRepositoryType]?: StatRepository

@PrimaryKey()
id: number
_id: ObjectId;

@SerializedPrimaryKey()
id!: string; // won't be saved in the database

@Property()
type!: string
Expand Down
8 changes: 4 additions & 4 deletions src/entities/User.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Entity, EntityRepositoryType, PrimaryKey, Property } from '@mikro-orm/core'
import { Entity, EntityRepositoryType, Property } from '@mikro-orm/core'
import { EntityRepository } from '@mikro-orm/sqlite'

import { CustomBaseEntity } from './BaseEntity'
Expand All @@ -12,8 +12,8 @@ export class User extends CustomBaseEntity {

[EntityRepositoryType]?: UserRepository

@PrimaryKey({ autoincrement: false })
id!: string
@Property()
userId!: string

@Property()
lastInteract: Date = new Date()
Expand All @@ -27,7 +27,7 @@ export class User extends CustomBaseEntity {
export class UserRepository extends EntityRepository<User> {

async updateLastInteract(userId?: string): Promise<void> {
const user = await this.findOne({ id: userId })
const user = await this.findOne({ userId })

if (user) {
user.lastInteract = new Date()
Expand Down
Loading
Loading