listener-rss/src/listener-rss.ts

90 lines
2.4 KiB
TypeScript
Raw Normal View History

2021-03-06 16:17:34 +01:00
import Parser from "rss-parser";
2021-02-14 15:00:33 +01:00
import { ListenerRSSInfos as ListenerInfo } from "./Models/ListenerRSSInfos";
2021-02-28 16:37:27 +01:00
import EventEmitter from "events";
2021-02-14 15:00:33 +01:00
const DEFAULT_TIMELOOP: number = 5 * 60; // default timeloop is 5 min
2021-02-28 16:37:27 +01:00
/**
* Emit 'update' when he's making a fetch during the start fun
* Emit 'update_err' when the fetch has an issue
*/
export class ListenerRss extends EventEmitter {
2021-02-14 15:00:33 +01:00
name: string = "";
address: string = "";
timeloop: number = DEFAULT_TIMELOOP; // time in seconds
customfields?: { [key: string]: string[] | string };
// private fields
2021-03-06 16:17:34 +01:00
parser: Parser;
loopRunning: boolean = false;
/**
* @brief constructor
* @param config ListenerRSSInfos interface who's contain the ListenerInfos
*/
constructor(config: ListenerInfo) {
2021-02-28 16:37:27 +01:00
super();
2021-03-06 16:17:34 +01:00
this.name = config.name;
this.address = config.address;
this.timeloop =
config.timeloop === undefined ? DEFAULT_TIMELOOP : config.timeloop;
this.customfields = config.customfields;
2021-03-06 16:17:34 +01:00
this.parser = this.generateParser();
}
/**
2021-03-06 16:17:34 +01:00
* @brief Private function. Is useed to initilize the parser object with the customfields var
*/
2021-03-06 16:17:34 +01:00
generateParser() {
const parserConfig = this.customfields && {
customFields: {
feed: [],
item: Object.entries(this.customfields).map(([, value]) => {
return Array.isArray(value) ? value[0] : value;
}),
},
};
return new Parser(parserConfig);
}
/**
* @brief use the parseURL function from rss-parser with the objects datas
* @return return a promise with the received data
*/
fetchRSS(): Promise<Parser.Output<any>> {
2021-03-06 16:17:34 +01:00
return this.parser.parseURL(this.address).catch((err) => {
throw new Error("bad address or no access : " + err);
});
}
/**
* @brief call the callback function each looptime
* @param callback function who's going to be called with the latest get
*/
2021-02-28 16:37:27 +01:00
start(): void {
this.loopRunning = true;
const fun: () => void = () => {
this.fetchRSS()
2021-02-28 16:37:27 +01:00
.then((obj: { [key: string]: any }) => this.emit("update", obj))
.catch((err) => this.emit("update_err", err));
};
(async () => {
while (this.loopRunning) {
await fun();
await new Promise((res) => setTimeout(res, this.timeloop * 1000));
}
})();
}
/**
* @brief stop the async function
*/
stop(): void {
this.loopRunning = false;
}
}