0

So i've tried to develop some pub/sub system based on node js

i am using express post request to publish the data that i wanted. it's send the data well, but my question is where should i put my code for the subscription

Right now i put the code at the root of my file like this

pubSub.subscribe()
.then(({results, subscription}) => {
    results[0].data.forEach((item) => {
        let key = ['UserId', fakeId(1, 100), 'FeedId', fakeId(100, 200), 'plugin', fakeId(1, 100)]
        upsert(key, item, () => {
            console.log('Sync Success')
            console.log(item)
        }, error => console.error(error))
    })
    subscription.ack(results.map((result) => result.ackId));
})
.catch(error => console.error(error))

i have some helper to subscribe like this

function subscribe () {
const subscription = pubSub.subscription('plugin_subscription')

return new Promise ((resolve, reject) => {
    return subscription.pull((error, results) => {
        console.log('ini ke trigger')
        if (error) reject(error)
        resolve({results, subscription})
    })
})

}

well it's kind of only work once. if i publish message i dont' have any response log from the subscriber, but if i restart the node js server my log is show that i successfully receive the data and could proceed to the next step.

Am i doing something wrong here?

thanks a lot man

1 Answers1

1

A couple ideas:

  • You're using promises to handle received messages. A promise on its own can only be triggered once - to trigger it multiple times, you'd need some sort of loop or recursive call.
  • Try using event handlers (see this example) instead of promises - those should trigger every time an event occurs without any additional looping or recursion. Note that for this example, you'll need to remove the code that removes the messageHandler listener.

Hopefully this helps!

Ace Nassri
  • 191
  • 5
  • Ok will use the second options by using event handlers, and i have more question if i see the bookshelf node sample in google, it show that they unsubscribe it. when is the right moment for unsubscribe the event? – Semmi Verian Mar 17 '17 at 02:55
  • the link to the example is not available anymore – vdolez Jan 10 '18 at 13:49