Skip to content

Commit

Permalink
fix(#100): mikro-orm global identity issue
Browse files Browse the repository at this point in the history
  • Loading branch information
barthofu committed Mar 7, 2023
1 parent 44a0e59 commit d5a803c
Show file tree
Hide file tree
Showing 9 changed files with 82 additions and 52 deletions.
19 changes: 14 additions & 5 deletions src/api/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,22 @@ import { singleton } from "tsyringe"

import * as controllers from "@api/controllers"
import { Log } from "@api/middlewares"
import { PluginsManager } from "@services"
import { MikroORM, UseRequestContext } from "@mikro-orm/core"
import { Database, PluginsManager } from "@services"

@singleton()
export class Server {

@Inject() app: PlatformApplication

orm: MikroORM

constructor(
private readonly pluginsManager: PluginsManager
) {}
private readonly pluginsManager: PluginsManager,
db: Database
) {
this.orm = db.orm
}

$beforeRoutesInit() {
this.app
Expand All @@ -24,7 +30,9 @@ export class Server {
return null
}

async start() {
@UseRequestContext()
async start(): Promise<void> {

const platform = await PlatformExpress.bootstrap(Server, {
rootDir: __dirname,
httpPort: parseInt(process.env['API_PORT']) || 4000,
Expand All @@ -46,6 +54,7 @@ export class Server {
}
})

await platform.listen()
platform.listen()

}
}
3 changes: 2 additions & 1 deletion src/client.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { GatewayIntentBits, Partials } from "discord.js"

import { generalConfig, logsConfig } from "@config"
import { ExtractLocale, Maintenance, NotBot } from "@guards"
import { ExtractLocale, Maintenance, NotBot, RequestContextIsolator } from "@guards"

export const clientConfig = {

Expand All @@ -28,6 +28,7 @@ export const clientConfig = {
silent: !logsConfig.debug,

guards: [
RequestContextIsolator,
NotBot,
Maintenance,
ExtractLocale
Expand Down
1 change: 0 additions & 1 deletion src/config/database.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,6 @@ const envMikroORMConfig: { production: Options, development?: Options } = {
// password: process.env['DATABASE_PASSWORD'],

highlighter: new SqlHighlighter(),
allowGlobalContext: true,
debug: false,

migrations: {
Expand Down
10 changes: 5 additions & 5 deletions src/events/ready.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,27 +62,28 @@ export default class ReadyEvent {

// synchronize guilds between discord and the database
await syncAllGuilds(client)

}

@Schedule('*/15 * * * * *') // each 15 seconds
async changeActivity() {

const ActivityTypeEnumString = ["PLAYING", "STREAMING", "LISTENING", "WATCHING", "CUSTOM", "COMPETING"] // DO NOT CHANGE THE ORDER

const client = await resolveDependency(Client)
const activity = generalConfig.activities[this.activityIndex]

activity.text = eval(`new String(\`${activity.text}\`).toString()`)

if (activity.type === 'STREAMING') {
//streaming activity
if (activity.type === 'STREAMING') { //streaming activity

client.user?.setStatus('online')
client.user?.setActivity(activity.text, {
'url': 'https://www.twitch.tv/discord',
'type': ActivityType.Streaming
})
} else {
//other activities

} else { //other activities

client.user?.setActivity(activity.text, {
type: ActivityTypeEnumString.indexOf(activity.type)
Expand All @@ -91,6 +92,5 @@ export default class ReadyEvent {

this.activityIndex++
if (this.activityIndex === generalConfig.activities.length) this.activityIndex = 0

}
}
3 changes: 2 additions & 1 deletion src/guards/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,5 @@ export * from './maintenance'
export * from './notBot'
export * from './nsfw'
export * from './match'
export * from './extractLocale'
export * from './extractLocale'
export * from './requestContextIsolator'
13 changes: 13 additions & 0 deletions src/guards/requestContextIsolator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { RequestContext } from '@mikro-orm/core'
import { Database } from '@services'
import { resolveDependency } from '@utils/functions'
import type { ArgsOf, GuardFunction } from 'discordx'

/**
* Isolate all the handling pipeline to prevent any MikrORM global identity map issues
*/
export const RequestContextIsolator: GuardFunction = async (_, client, next) => {

const db = await resolveDependency(Database)
RequestContext.create(db.orm.em, next)
}
83 changes: 44 additions & 39 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { NoBotTokenError } from "@errors"
import { Database, ErrorHandler, ImagesUpload, Logger, PluginsManager, WebSocket } from "@services"
import { initDataTable, resolveDependency } from "@utils/functions"
import { clientConfig } from "./client"
import { RequestContext } from '@mikro-orm/core'

async function run() {

Expand All @@ -35,56 +36,60 @@ async function run() {
// init the sqlite database
const db = await resolveDependency(Database)
await db.initialize()

// init the client
DIService.engine = tsyringeDependencyRegistryEngine.setInjector(container)
const client = new Client(clientConfig)

// Load all new events
discordLogs(client, { debug: false })
container.registerInstance(Client, client)

// import all the commands and events
await importx(__dirname + "/{events,commands}/**/*.{ts,js}")
await pluginManager.importCommands()
await pluginManager.importEvents()

// init the data table if it doesn't exist
await initDataTable()

// init plugins services
await pluginManager.initServices()

// init the plugin main file
await pluginManager.execMains()

// log in with the bot token
if (!process.env.BOT_TOKEN) throw new NoBotTokenError()
client.login(process.env.BOT_TOKEN)
.then(async () => {

// start the api server
if (apiConfig.enabled) {
const server = await resolveDependency(Server)
await server.start()
}

// connect to the dashboard websocket
if (websocketConfig.enabled) {
const webSocket = await resolveDependency(WebSocket)
await webSocket.init(client.user?.id || null)
}

// upload images to imgur if configured
if (process.env.IMGUR_CLIENT_ID && generalConfig.automaticUploadImagesToImgur) {
const imagesUpload = await resolveDependency(ImagesUpload)
await imagesUpload.syncWithDatabase()
}
})
.catch((err) => {
console.error(err)
process.exit(1)

RequestContext.create(db.orm.em, async () => {

// init the data table if it doesn't exist
await initDataTable()

// init plugins services
await pluginManager.initServices()

// init the plugin main file
await pluginManager.execMains()

// log in with the bot token
if (!process.env.BOT_TOKEN) throw new NoBotTokenError()
client.login(process.env.BOT_TOKEN)
.then(async () => {

// start the api server
if (apiConfig.enabled) {
const server = await resolveDependency(Server)
await server.start()
}

// connect to the dashboard websocket
if (websocketConfig.enabled) {
const webSocket = await resolveDependency(WebSocket)
await webSocket.init(client.user?.id || null)
}

// upload images to imgur if configured
if (process.env.IMGUR_CLIENT_ID && generalConfig.automaticUploadImagesToImgur) {
const imagesUpload = await resolveDependency(ImagesUpload)
await imagesUpload.syncWithDatabase()
}
})
.catch((err) => {
console.error(err)
process.exit(1)
})
})

}

run()
1 change: 1 addition & 0 deletions src/services/Database.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ export class Database {
) { }

async initialize() {

const pluginsManager = await resolveDependency(PluginsManager)

// get config
Expand Down
1 change: 1 addition & 0 deletions src/utils/decorators/Schedule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export const Schedule = (cronExpression: string, jobName?: string) => {
propertyKey: string,
descriptor: PropertyDescriptor
) => {

// associate the context to the function, with the injected dependencies defined
const oldDescriptor = descriptor.value
descriptor.value = function(...args: any[]) {
Expand Down

0 comments on commit d5a803c

Please sign in to comment.