M
M
Mikhail2017-06-23 14:40:53
Node.js
Mikhail, 2017-06-23 14:40:53

How to apply the observer pattern correctly?

Hello. I ran into a problem when using the observer pattern. The situation is this: I receive a message from the user, and I need to do the following:
1) Get the time zone using an instance of the googleMapsAPI class 2) Get all previously recorded data in Redis
const zone = await geoTime.getTimeZone(msg.text)

const user = await redisApi.getUserForSave(msg.from.id)

3) Write it all in MySQL. And depending on the response code and the presence of an error, respond to the user
const code = await sql.saveUser(user);
code === 'good' ? bot.sendMessage(msg.from.id, 'Good') : bot.sendMessage(msg.from.id, 'Good');

As a result, the code is cumbersome. And the connectivity between modules is broken:
observer.on('end', (msg) => {
   const zone = await geoTime.getTimeZone(msg.text);
   const user = await redisApi.getUserForSave(msg.from.id);
   const code = await sql.saveUser(user);
   code === 'good' ? bot.sendMessage(msg.from.id, 'Good') : bot.sendMessage(msg.from.id, 'Good');
})

I simplified the code and logic a little. In real life, things are a little more complicated. What is the right way to be in such a situation?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Philipp, 2017-06-23
@mak_ufo

Since the message handler turns out to be cumbersome, it can be easily taken out into a separate module and imported like this.

const messageProcessor = require('path/to/message/processor');
// ваш код идет здесь ...
// далее навешиваем наш обработчик на шину сообщений
messageBus.on('end', messageProcessor);

You can also automatically register inside the handler.
// в вашем основном файле
messageProcessor.register(messageBus);

Inside the message processor
function messageProcessor() {
 // ...
}

module.exports.register = function(messageBus) {
   messageBus.on('end', messageProcessor);
};

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question