Removed commented code, implemented Singleton.

This commit is contained in:
elweyn 2023-05-19 15:55:29 +02:00
parent 471a746005
commit 81754449e9
6 changed files with 58 additions and 53 deletions

View File

@ -1,4 +1,3 @@
/* eslint-disable @typescript-eslint/restrict-template-expressions */
/* eslint-disable @typescript-eslint/no-unsafe-member-access */ /* eslint-disable @typescript-eslint/no-unsafe-member-access */
/* eslint-disable @typescript-eslint/no-unsafe-call */ /* eslint-disable @typescript-eslint/no-unsafe-call */
/* eslint-disable @typescript-eslint/no-unsafe-return */ /* eslint-disable @typescript-eslint/no-unsafe-return */
@ -43,10 +42,9 @@ export const getKlickTippUser = async (email: string): Promise<any> => {
const isLogin = await loginKlicktippUser() const isLogin = await loginKlicktippUser()
if (isLogin) { if (isLogin) {
try { try {
const subscriberId = await klicktippConnector.subscriberSearch(email) return klicktippConnector.subscriberGet(await klicktippConnector.subscriberSearch(email))
return klicktippConnector.subscriberGet(subscriberId)
} catch (e) { } catch (e) {
logger.error(`Could not find subscriber ${email}`) logger.error('Could not find subscriber', email)
return false return false
} }
} }
@ -68,17 +66,16 @@ export const addFieldsToSubscriber = async (
const isLogin = await loginKlicktippUser() const isLogin = await loginKlicktippUser()
if (isLogin) { if (isLogin) {
try { try {
const subscriberId = await klicktippConnector.subscriberSearch(email) logger.info(`Update of subscriber (${email}) has been successful`)
const result = await klicktippConnector.subscriberUpdate( const result = await klicktippConnector.subscriberUpdate(
subscriberId, await klicktippConnector.subscriberSearch(email),
fields, fields,
newemail, newemail,
newsmsnumber, newsmsnumber,
) )
logger.info(`Update of subscriber (${email}) has been successful, ${result}`)
return result return result
} catch (e) { } catch (e) {
logger.error(`Could not update subscriber ${email}, ${JSON.stringify(fields)}, ${e}`) logger.error('Could not update subscriber', email, JSON.stringify(fields), e)
return false return false
} }
} }

View File

@ -1,14 +1,14 @@
/* eslint-disable @typescript-eslint/no-unsafe-assignment */ /* eslint-disable @typescript-eslint/no-unsafe-assignment */
/* eslint-disable @typescript-eslint/restrict-template-expressions */ /* eslint-disable @typescript-eslint/restrict-template-expressions */
/* eslint-disable @typescript-eslint/unbound-method */ /* eslint-disable @typescript-eslint/unbound-method */
import { Connection } from '@dbTools/typeorm' import { Connection as DbConnection } from '@dbTools/typeorm'
import { ApolloServer } from 'apollo-server-express' import { ApolloServer } from 'apollo-server-express'
import express, { Express, json, urlencoded } from 'express' import express, { Express, json, urlencoded } from 'express'
import { Logger } from 'log4js' import { Logger } from 'log4js'
import { CONFIG } from '@/config' import { CONFIG } from '@/config'
import { schema } from '@/graphql/schema' import { schema } from '@/graphql/schema'
import { getConnection } from '@/typeorm/connection' import { Connection } from '@/typeorm/connection'
import { checkDBVersion } from '@/typeorm/DBVersion' import { checkDBVersion } from '@/typeorm/DBVersion'
import { elopageWebhook } from '@/webhook/elopage' import { elopageWebhook } from '@/webhook/elopage'
@ -24,7 +24,7 @@ import { plugins } from './plugins'
interface ServerDef { interface ServerDef {
apollo: ApolloServer apollo: ApolloServer
app: Express app: Express
con: Connection con: DbConnection
} }
export const createServer = async ( export const createServer = async (
@ -37,7 +37,7 @@ export const createServer = async (
logger.debug('createServer...') logger.debug('createServer...')
// open mysql connection // open mysql connection
const con = await getConnection() const con = await Connection.getInstance()
if (!con?.isConnected) { if (!con?.isConnected) {
logger.fatal(`Couldn't open connection to database!`) logger.fatal(`Couldn't open connection to database!`)
throw new Error(`Fatal: Couldn't open connection to database`) throw new Error(`Fatal: Couldn't open connection to database`)

View File

@ -1,21 +1,33 @@
// TODO This is super weird - since the entities are defined in another project they have their own globals. // TODO This is super weird - since the entities are defined in another project they have their own globals.
// We cannot use our connection here, but must use the external typeorm installation // We cannot use our connection here, but must use the external typeorm installation
import { Connection, createConnection, FileLogger } from '@dbTools/typeorm' import { Connection as DbConnection, createConnection, FileLogger } from '@dbTools/typeorm'
import { entities } from '@entity/index' import { entities } from '@entity/index'
import { CONFIG } from '@/config' import { CONFIG } from '@/config'
let connection: Connection | null // eslint-disable-next-line @typescript-eslint/no-extraneous-class
export class Connection {
private static instance: DbConnection
export const getConnection = async (): Promise<Connection | null> => { /**
if (connection) return connection * The Singleton's constructor should always be private to prevent direct
connection = await createMyConnection() * construction calls with the `new` operator.
return connection */
} // eslint-disable-next-line no-useless-constructor, @typescript-eslint/no-empty-function
private constructor() {}
const createMyConnection = async (): Promise<Connection | null> => { /**
* The static method that controls the access to the singleton instance.
*
* This implementation let you subclass the Singleton class while keeping
* just one instance of each subclass around.
*/
public static async getInstance(): Promise<DbConnection | null> {
if (Connection.instance) {
return Connection.instance
}
try { try {
return createConnection({ Connection.instance = await createConnection({
name: 'default', name: 'default',
type: 'mysql', type: 'mysql',
host: CONFIG.DB_HOST, host: CONFIG.DB_HOST,
@ -33,9 +45,11 @@ const createMyConnection = async (): Promise<Connection | null> => {
charset: 'utf8mb4_unicode_ci', charset: 'utf8mb4_unicode_ci',
}, },
}) })
return Connection.instance
} catch (error) { } catch (error) {
// eslint-disable-next-line no-console // eslint-disable-next-line no-console
console.log(error) console.log(error)
return null return null
} }
}
} }

View File

@ -1,9 +1,9 @@
import { getConnection } from '@/typeorm/connection' import { Connection } from '@/typeorm/connection'
import { exportEventDataToKlickTipp } from './klicktipp' import { exportEventDataToKlickTipp } from './klicktipp'
async function executeKlicktipp(): Promise<boolean> { async function executeKlicktipp(): Promise<boolean> {
const connection = await getConnection() const connection = await Connection.getInstance()
if (connection) { if (connection) {
await exportEventDataToKlickTipp() await exportEventDataToKlickTipp()
await connection.close() await connection.close()

View File

@ -50,7 +50,6 @@ describe('klicktipp', () => {
mutation: login, mutation: login,
variables: { email: 'bibi@bloxberg.de', password: 'Aa12345_' }, variables: { email: 'bibi@bloxberg.de', password: 'Aa12345_' },
}) })
// await con.close()
}) })
afterAll(() => { afterAll(() => {
@ -59,8 +58,6 @@ describe('klicktipp', () => {
describe('exportEventDataToKlickTipp', () => { describe('exportEventDataToKlickTipp', () => {
it('calls the KlicktippController', async () => { it('calls the KlicktippController', async () => {
// console.log(await lastDateTimeEvents('USER_LOGIN'))
// console.log(con)
await exportEventDataToKlickTipp() await exportEventDataToKlickTipp()
expect(addFieldsToSubscriber).toBeCalled() expect(addFieldsToSubscriber).toBeCalled()
}) })

View File

@ -24,11 +24,11 @@ export async function retrieveNotRegisteredEmails(): Promise<string[]> {
async function klickTippSendFieldToUser( async function klickTippSendFieldToUser(
events: { email: string; value: Date }[], events: { email: string; value: Date }[],
value: string, field: string,
): Promise<void> { ): Promise<void> {
for (const event of events) { for (const event of events) {
const time = event.value.setSeconds(0) const time = event.value.setSeconds(0)
await addFieldsToSubscriber(event.email, { [value]: Math.trunc(time / 1000) }) await addFieldsToSubscriber(event.email, { [field]: Math.trunc(time / 1000) })
} }
} }
@ -53,6 +53,3 @@ export async function exportEventDataToKlickTipp(): Promise<boolean> {
return true return true
} }
// void exportEventDataToKlickTipp()
// void retrieveNotRegisteredEmails()