From 287271638c3c0031080f93fb928353768ae0fb6c Mon Sep 17 00:00:00 2001 From: unional Date: Thu, 21 Apr 2022 02:29:53 -0700 Subject: [PATCH] feat: passing in logger --- ts/Emitter.ts | 4 ++-- ts/TestEmitter.ts | 22 +++++++++++++--------- 2 files changed, 15 insertions(+), 11 deletions(-) diff --git a/ts/Emitter.ts b/ts/Emitter.ts index 68a6913..cdad037 100644 --- a/ts/Emitter.ts +++ b/ts/Emitter.ts @@ -10,7 +10,7 @@ export class Emitter { protected eventQueues: { [k: string]: AnyFunction[] } = {} protected listenAlls: AnyFunction[] = [] protected listenMisses: AnyFunction[] = [] - constructor() { + constructor(protected log: { error(...args: any[]): void } = console) { this.emitter = new EventEmitter() } emit({ type, payload, meta, error }: FSA) { @@ -99,7 +99,7 @@ export class Emitter { listener(payload, meta, error) } catch (err) { - console.error('Error thrown in error event handler:', err) + this.log.error('Error thrown in error event handler:', err) } } return this.emitter.addListener(errorEvent.type, wrappedListener) diff --git a/ts/TestEmitter.ts b/ts/TestEmitter.ts index 3d08e40..0ab1ed6 100644 --- a/ts/TestEmitter.ts +++ b/ts/TestEmitter.ts @@ -12,10 +12,12 @@ import { errorEvent } from './errorEvent' */ export class TestEmitter extends Emitter { private calledListeners: { [k: string]: boolean } = {} - constructor() { - super() + private defaultMiss: ({ type, payload, meta }: FluxStandardAction) => void + constructor(protected log: { error(...args: any[]): void } = console) { + super(log) - this.listenMisses.push(defaultMiss) + this.defaultMiss = buildDefaultMiss(log) + this.listenMisses.push(this.defaultMiss) } addListener( event: TypedEvent | string, @@ -45,7 +47,7 @@ export class TestEmitter extends Emitter { return this.listenedToEventMap(events) } onMissed(listener: (fsa: FluxStandardAction) => void) { - if (this.listenMisses.length === 1 && this.listenMisses[0] === defaultMiss) { + if (this.listenMisses.length === 1 && this.listenMisses[0] === this.defaultMiss) { this.listenMisses.splice(0, 1) } return super.onMissed(listener) @@ -71,9 +73,11 @@ export class TestEmitter extends Emitter { } } -function defaultMiss({ type, payload, meta }: FluxStandardAction) { - console.error(`missed event: -type: ${type} -payload: ${tersify(payload, { maxLength: Infinity })} -meta: ${tersify(meta)}`) +function buildDefaultMiss(log: { error: (...args: any[]) => void }) { + return function defaultMiss({ type, payload, meta }: FluxStandardAction) { + log.error(`missed event: + type: ${type} + payload: ${tersify(payload, { maxLength: Infinity })} + meta: ${tersify(meta)}`) + } }