diff --git a/src/config/types.ts b/src/config/types.ts index f7cbbe5..3ddb1d3 100644 --- a/src/config/types.ts +++ b/src/config/types.ts @@ -1,12 +1,15 @@ +import { ConsumerConfig } from "../consumers/types"; export type Config = { /** * Tauron service configuration */ tauron: TauronConfig; + + consumers: Record; }; -export type TauronConfig = { +export type TauronConfig = ConsumerConfig & { /** * Path to file containing a username of Tauron account */ diff --git a/src/consumers/index.ts b/src/consumers/index.ts new file mode 100644 index 0000000..0e898f9 --- /dev/null +++ b/src/consumers/index.ts @@ -0,0 +1,11 @@ +import { Dayjs } from "dayjs"; +import { Config } from "../config"; +import { MQTTConsumer } from "./mqtt"; +import { Measurement } from "../fetcher/types"; + +const consumers = [ + new MQTTConsumer() +]; + +export const consume = (config: Config, date: Dayjs, measurement: Measurement) => + consumers.forEach(consumer => consumer.consume(config, date, measurement)); \ No newline at end of file diff --git a/src/consumers/types.ts b/src/consumers/types.ts new file mode 100644 index 0000000..1ab5528 --- /dev/null +++ b/src/consumers/types.ts @@ -0,0 +1,33 @@ +import { Dayjs } from "dayjs"; +import { Measurement } from "../fetcher/types"; +import { Config } from "../config"; + +export type ConsumerConfig = { + enable?: boolean; +} + +export abstract class Consumer { + public abstract readonly name: string; + protected abstract requiredFields: readonly (keyof C)[]; + protected abstract publish(config: C, date: Dayjs, measurement: Measurement): void; + + #validate(config: Partial): C { + for (const field of this.requiredFields) { + if (config[field] === undefined) { + throw new Error(`The '${String(field)}' configuration field of'${this.name}' consumer is required`) + } + } + + return config as C; + } + + consume(config: Config, date: Dayjs, measurement: Measurement): void { + const cfg = config.consumers[this.name] as Partial; + + if (cfg.enable !== true) { + return + } + + this.publish(this.#validate(cfg), date, measurement); + } +}; \ No newline at end of file