Created
November 28, 2016 21:30
-
-
Save agoldis/90539d781a2742f0af61e586ed518de0 to your computer and use it in GitHub Desktop.
Request/response in Nodejs with postal and promises
This file contains 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 postal from 'postal' | |
import { v1 } from 'uuid' | |
export default class ReqRes { | |
static channel = 'reqres' | |
static request (topic, payload) { | |
var replyTo = { | |
channel: ReqRes.channel, | |
topic: topic + v1() | |
} | |
var result = new Promise((resolve, reject) => { | |
postal.subscribe({ | |
channel: replyTo.channel, | |
topic: replyTo.topic, | |
callback: function (msg, envelope) { | |
resolve(msg) | |
} | |
}).once() | |
postal.publish({ | |
channel: ReqRes.channel, | |
topic, | |
replyTo, | |
data: payload | |
}) | |
}) | |
return result | |
} | |
static respondTo (topic, handler) { | |
postal.subscribe({ | |
channel: ReqRes.channel, | |
topic, | |
callback: function (msg, envelope) { | |
let replyTo = envelope.replyTo | |
handler(msg) | |
.then(function (response) { | |
postal.publish({ | |
channel: ReqRes.channel, | |
topic: replyTo.topic, | |
data: response | |
}) | |
}) | |
} | |
}) | |
} | |
} |
This file contains 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 chai, { expect } from 'chai'; | |
import ReqRes from 'ReqRes'; | |
chai.config.includeStack = true; | |
describe('## ReqRes', () => { | |
it('should request and respond', done => { | |
ReqRes.respondTo('testRequest', data => { | |
expect(data.payload).to.be.true | |
return Promise.resolve({ payload: 42 }) | |
}) | |
ReqRes.request('testRequest', { payload: true }) | |
.then(response => { | |
expect(response.payload).to.equal(42) | |
done() | |
}) | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment