2022-03-02 21:16:30 +00:00
|
|
|
import api from "./Api";
|
2022-03-03 21:52:07 +00:00
|
|
|
import subscriptionManager from "./SubscriptionManager";
|
2022-03-02 21:16:30 +00:00
|
|
|
|
|
|
|
const delayMillis = 3000; // 3 seconds
|
|
|
|
const intervalMillis = 300000; // 5 minutes
|
|
|
|
|
|
|
|
class Poller {
|
|
|
|
constructor() {
|
|
|
|
this.timer = null;
|
|
|
|
}
|
|
|
|
|
|
|
|
startWorker() {
|
|
|
|
if (this.timer !== null) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
this.timer = setInterval(() => this.pollAll(), intervalMillis);
|
|
|
|
setTimeout(() => this.pollAll(), delayMillis);
|
|
|
|
}
|
|
|
|
|
|
|
|
async pollAll() {
|
|
|
|
console.log(`[Poller] Polling all subscriptions`);
|
2022-03-03 21:52:07 +00:00
|
|
|
const subscriptions = await subscriptionManager.all();
|
2022-03-02 21:16:30 +00:00
|
|
|
for (const s of subscriptions) {
|
|
|
|
try {
|
|
|
|
await this.poll(s);
|
|
|
|
} catch (e) {
|
|
|
|
console.log(`[Poller] Error polling ${s.id}`, e);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
async poll(subscription) {
|
|
|
|
console.log(`[Poller] Polling ${subscription.id}`);
|
|
|
|
|
|
|
|
const since = subscription.last;
|
|
|
|
const notifications = await api.poll(subscription.baseUrl, subscription.topic, since);
|
|
|
|
if (!notifications || notifications.length === 0) {
|
|
|
|
console.log(`[Poller] No new notifications found for ${subscription.id}`);
|
|
|
|
return;
|
|
|
|
}
|
2022-03-03 21:52:07 +00:00
|
|
|
console.log(`[Poller] Adding ${notifications.length} notification(s) for ${subscription.id}`);
|
|
|
|
await subscriptionManager.addNotifications(subscription.id, notifications);
|
|
|
|
}
|
|
|
|
|
|
|
|
pollInBackground(subscription) {
|
|
|
|
const fn = async () => {
|
|
|
|
try {
|
|
|
|
await this.poll(subscription);
|
|
|
|
} catch (e) {
|
|
|
|
console.error(`[App] Error polling subscription ${subscription.id}`, e);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
setTimeout(() => fn(), 0);
|
|
|
|
}
|
2022-03-02 21:16:30 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
const poller = new Poller();
|
|
|
|
export default poller;
|