Created
July 25, 2023 17:30
-
-
Save oleh-zaporozhets/2e5ce708937b85e68ba31d8797114042 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { RequestHandler } from 'express'; | |
import { ITelegramBot } from '@/application/telegram-bot'; | |
import { Timer } from '@/application/timer'; | |
import { ITimerStore } from '@/application/timer-store'; | |
import { Controller } from './controller'; | |
const FIVE_MINUTES = 1000 * 60 * 5; | |
class WebhooksController extends Controller { | |
private telegramBot: ITelegramBot; | |
private timerStore: ITimerStore; | |
public constructor(telegramBot: ITelegramBot, timerStore: ITimerStore) { | |
super('/webhooks'); | |
this.telegramBot = telegramBot; | |
this.timerStore = timerStore; | |
this.initializeRoutes(); | |
} | |
private initializeRoutes = (): void => { | |
this.router.get('/electricity/:id', this.electricityWebhook); | |
}; | |
private electricityWebhook: RequestHandler = async (req, res) => { | |
const { id } = req.params; | |
const timer = this.timerStore.getTimerById(id); | |
if (!timer) { | |
const newTimer = new Timer( | |
[() => this.telegramBot.sendMessage(id, 'The electricity is OFF. 🔴')], | |
FIVE_MINUTES, | |
); | |
newTimer.reset(); | |
this.timerStore.addTimer(id, newTimer); | |
await this.telegramBot.sendMessage( | |
id, | |
'The controller was connected. 🟡', | |
); | |
return res.sendStatus(200); | |
} | |
if (timer.isTimerRunning()) { | |
timer.refresh(); | |
return res.sendStatus(200); | |
} | |
await this.telegramBot.sendMessage(id, 'The electricity is ON. 🟢'); | |
timer.reset(); | |
return res.sendStatus(200); | |
}; | |
} | |
export { WebhooksController }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment