Files
dwatcher/src/lib/watchers/abstract/url-watcher.ts
2020-09-20 10:58:20 +02:00

91 lines
2.4 KiB
TypeScript

import {watcherLoop} from "../../watcherLoop";
import {Conf, ConfURL} from "../../types/conf";
import Axios from "axios";
import {mail} from "../../mail";
import {Watcher} from "../../types/state";
export function urlWatcher(conf: Conf, checkValidity: (data: any) => Promise<UrlWatcherResult>) {
return async (urlConf: ConfURL,
getOkTitle: () => string,
getKoTitle: () => string,
getRecoveredTitle: () => string): Promise<Watcher> => {
let nodeDownRes: () => void
let nodeDownPromise: Promise<void> = new Promise(res => nodeDownRes = res)
async function checkResult(data: any) {
const validity = await checkValidity(data)
if (validity.error) {
throw new UrlWatcherError('Validity error')
}
}
return watcherLoop(
urlConf.name,
async () => {
let interval: NodeJS.Timer;
const res = await Axios.get(urlConf.address)
await checkResult(res.data)
interval = setInterval(async () => {
try {
const res = await Axios.get(urlConf.address)
await checkResult(res.data)
} catch (e) {
if (interval) {
clearInterval(interval)
}
nodeDownRes()
// Re-create down promise for future connection trial
nodeDownPromise = new Promise(res => nodeDownRes = res)
}
}, urlConf.frequency)
},
() => nodeDownPromise,
conf.waitingDelay,
conf.recallDelay,
mail.onEstablished(urlConf.address, getOkTitle()),
// When a disconnection is detected
(waitingDelay: number, recallDelay, error?: any) => {
let koTitle: string|undefined
let koMessage: (() => string)|undefined
if (error && error instanceof UrlWatcherError) {
koTitle = getKoTitle()
koMessage = () => `<p>${error.errorMessage}</p>`
}
return mail.onDisconnect(urlConf.address, koTitle, koMessage)(waitingDelay, recallDelay)
},
async () => {
console.log('Trying to connect to %s', urlConf.address)
},
mail.onRestartSuccess(urlConf.address, getRecoveredTitle()),
)
}
}
export class UrlWatcherError {
constructor (public errorMessage: string) {
}
}
export class UrlWatcherResult {
error?: string
public static ok() {
return {}
}
public static ko(errorMessage: string) {
return { error: errorMessage }
}
}