routing/src/logWriter.ts
2021-05-23 16:07:33 +02:00

52 lines
1.3 KiB
TypeScript

import { ImplementableApi } from './implementableApi';
import {
appendFileSync,
closeSync,
openSync,
writeFile,
writeFileSync,
} from 'fs';
namespace LogWriter {
export type Config = ImplementableApi.Config & {
path: string;
};
}
class LogWriter extends ImplementableApi {
readonly path: string;
constructor(readonly config: LogWriter.Config) {
super(config);
this.path = config.path;
this.firstWrite();
}
private firstWrite() {
this.writeMsg('LogWriter is running');
}
private writeMsg(message: string): void;
private writeMsg(message: ImplementableApi.Message): void;
private writeMsg(message: ImplementableApi.Message | string) {
if (typeof message !== 'string')
message = `[${message.type} :: ${new Date().toLocaleString(
'fr-FR'
)}] ${message.rawContent} ${
message.idListener ?? `( listener_id : ${message.idListener} )`
}`;
const fd = openSync(this.path, 'a');
const str = `[${new Date().toLocaleString('fr-FR')}] ${message}`;
appendFileSync(fd, str);
closeSync(fd);
}
public receivedMessage(message: ImplementableApi.Message) {
this.writeMsg(message);
}
}
export { LogWriter };