M
M
Mikhail2017-06-16 13:20:39
Node.js
Mikhail, 2017-06-16 13:20:39

Have I implemented the observer pattern correctly?

Hello. Now I am writing a more or less large application for myself on node.js + typescript, which has interaction with MySQL, Redis, Google Maps API and Telegram API. I decided to use design patterns (I didn’t do this before and wrote it somehow) in order to write readable and extensible code. And I ran into the problem of implementing Observer. The code is something like this:

сonst TelegramBot = new TelegramBot(config.token, {polling: true}); //telegram-бот
const redisApi= new RedisApi(redisClient); //обёртка для удобной работы с сессиями через Redis
const Observer = new Observer();

//обычное сообщение, требующее от пользователя нужного формата входных данных
observer.on('classic', (msg: Message, text: TextMessage) => {
    bot.sendMessage(msg.from.id, text.text, text.keyboard);
});

observer.on('classic', (msg: Message, text: TextMessage, level: string) => {
    if (level != undefined) redisApi.setSession(msg.from.id, level);
});

//classic - тип события
//msg - сообщение от пользователя telegram
//text - ответное сообщение пользователю
//level - аналог сессий, приспособленный для телеграм-бота

Have I implemented the observer correctly? It confuses me that so many parameters are passed. Perhaps it would be more correct to pass only the event type and the incoming message, and other modules would themselves determine which message to send in response and which "level" of the survey to transfer the user to. Or maybe I'm doing it all wrong? Help me figure it out, please
PS The full code is here - https://bitbucket.org/mak_tu/plantsbot/src
It's not very much there. If someone is not too lazy to look at it, it would be great.
PPS I will be glad to any criticism regarding the code and architecture of the application

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Fedorov, 2017-06-16
@qonand

Have I implemented the observer correctly?

It's hard to say because the repository you link to is apparently private. But you seem to be moving in the right direction.
Make a separate event class that will contain all the necessary data and work directly with it, and not with a bunch of parameters
It all depends solely on your system and its organization.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question