listener-rss/src/listener-rss.ts

87 lines
2.3 KiB
TypeScript
Raw Normal View History

2021-02-14 16:30:23 +01:00
import Parser from "rss-parser/index";
2021-02-14 15:00:33 +01:00
import { ListenerRSSInfos as ListenerInfo } from "./Models/ListenerRSSInfos";
2021-02-14 15:00:33 +01:00
const DEFAULT_TIMELOOP: number = 5 * 60; // default timeloop is 5 min
2021-02-14 15:00:33 +01:00
export class ListenerRss {
name: string = "";
address: string = "";
timeloop: number = DEFAULT_TIMELOOP; // time in seconds
customfields?: { [key: string]: string[] | string };
// private fields
parser: Parser | undefined = undefined;
loopRunning: boolean = false;
constructor(config: ListenerInfo) {
this.setData(config);
this.setParser();
}
setParser() {
// set parser
this.parser = new Parser(
this.customfields !== undefined
? {
customFields: {
feed: [],
item: Object.entries(this.customfields).map(([, value]) => {
return Array.isArray(value) ? value[0] : value;
}),
},
}
: {}
); // if customfield is set -> let's set the parser with, else let the option empty
}
setData(infos: ListenerInfo) {
// Set data
this.name = infos.name;
this.address = infos.address;
this.timeloop =
infos.timeloop === undefined ? DEFAULT_TIMELOOP : infos.timeloop;
this.customfields = infos.customfields;
}
fetchRSS(): Promise<any> {
// TODO Pas Bien
if (this.parser !== undefined && this.address !== undefined) {
return this.parser.parseURL(this.address).catch((err) => {
throw new Error("bad address or no access : " + err);
});
} else throw new Error("listener must be first initialized");
}
/**
* @brief call the callback function each looptime
* @param callback function who's going to be called with the latest get
*/
start(
callback: (
obj: { [key: string]: any } | undefined,
err: Error | undefined
) => void
) {
this.loopRunning = true;
const fun = () => {
this.fetchRSS()
.then((obj: { [key: string]: any }) => callback(obj, undefined))
.catch((err) => callback(undefined, err));
};
let fun_loop = () => {
fun();
console.log("while");
if (this.loopRunning) setTimeout(fun_loop, this.timeloop * 1000);
};
fun_loop();
}
/**
* @brief stop the async function
*/
stop() {
this.loopRunning = false;
}
}