refactor connection logic

This commit is contained in:
Moriz Wahl 2023-05-16 16:38:59 +02:00
parent 013ea81614
commit 2ce14d1a89
3 changed files with 14 additions and 6 deletions

View File

@ -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`)

View File

@ -5,7 +5,15 @@ import { entities } from '@entity/index'
import { CONFIG } from '@/config'
export const connection = async (): Promise<Connection | null> => {
let connection: Connection | null
export const getConnection = async (): Promise<Connection | null> => {
if (connection) return connection
connection = await createMyConnection()
return connection
}
const createMyConnection = async (): Promise<Connection | null> => {
try {
return createConnection({
name: 'default',

View File

@ -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<string[]> {
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<void> {
const connectionInstance = await connection()
const connectionInstance = await getConnection()
if (!connectionInstance) {
throw new LogError('No connection to database')
}