From 2ce14d1a89ca4337e6eddb00fa00272eab94e758 Mon Sep 17 00:00:00 2001 From: Moriz Wahl Date: Tue, 16 May 2023 16:38:59 +0200 Subject: [PATCH] refactor connection logic --- backend/src/server/createServer.ts | 4 ++-- backend/src/typeorm/connection.ts | 10 +++++++++- backend/src/util/klicktipp.ts | 6 +++--- 3 files changed, 14 insertions(+), 6 deletions(-) diff --git a/backend/src/server/createServer.ts b/backend/src/server/createServer.ts index d813c541e..ddc255268 100644 --- a/backend/src/server/createServer.ts +++ b/backend/src/server/createServer.ts @@ -8,7 +8,7 @@ import { Logger } from 'log4js' import { CONFIG } from '@/config' import { schema } from '@/graphql/schema' -import { connection } from '@/typeorm/connection' +import { getConnection } from '@/typeorm/connection' import { checkDBVersion } from '@/typeorm/DBVersion' import { elopageWebhook } from '@/webhook/elopage' @@ -37,7 +37,7 @@ export const createServer = async ( logger.debug('createServer...') // open mysql connection - const con = await connection() + const con = await getConnection() if (!con?.isConnected) { logger.fatal(`Couldn't open connection to database!`) throw new Error(`Fatal: Couldn't open connection to database`) diff --git a/backend/src/typeorm/connection.ts b/backend/src/typeorm/connection.ts index 7dec820b5..bd314fd3c 100644 --- a/backend/src/typeorm/connection.ts +++ b/backend/src/typeorm/connection.ts @@ -5,7 +5,15 @@ import { entities } from '@entity/index' import { CONFIG } from '@/config' -export const connection = async (): Promise => { +let connection: Connection | null + +export const getConnection = async (): Promise => { + if (connection) return connection + connection = await createMyConnection() + return connection +} + +const createMyConnection = async (): Promise => { try { return createConnection({ name: 'default', diff --git a/backend/src/util/klicktipp.ts b/backend/src/util/klicktipp.ts index f6c631205..a315d73e6 100644 --- a/backend/src/util/klicktipp.ts +++ b/backend/src/util/klicktipp.ts @@ -5,10 +5,10 @@ import { getKlickTippUser, addFieldsToSubscriber } from '@/apis/KlicktippControl import { EventType } from '@/event/EventType' import { lastDateTimeEvents } from '@/graphql/resolver/util/eventList' import { LogError } from '@/server/LogError' -import { connection } from '@/typeorm/connection' +import { getConnection } from '@/typeorm/connection' export async function retrieveNotRegisteredEmails(): Promise { - const con = await connection() + const con = await getConnection() if (!con) { throw new LogError('No connection to database') } @@ -40,7 +40,7 @@ async function klickTippSendFieldToUser( } export async function exportEventDataToKlickTipp(): Promise { - const connectionInstance = await connection() + const connectionInstance = await getConnection() if (!connectionInstance) { throw new LogError('No connection to database') }