-
Notifications
You must be signed in to change notification settings - Fork 191
Envelopes
One of the advantages of postal.js is that every subscriber gets the same method signature:
someChannel.subscribe( "the.topic", function( data, envelope ) {
// Usually you're just worried about the data argument
} );
99% of the time, you're only going to care about the first argument: data
. However, it's beneficial to understand the second argument: envelope
.
The envelope is an object that contains, at a minimum, the channel
, topic
, data
and a timestamp
(indicating when the message was published). So, in a nutshell, every postal envelope will look something like this:
{
channel: "presidents",
topic: "constitution.contributors",
timeStamp: "1787-09-17T16:59:55.009Z",
data: {
firstName: "James",
lastName: "Madison"
}
}
If you publish a message using the ChannelDefinition.prototype.publish
method, the envelope is created for you:
someChannel.publish( "the.topic", { firstName: "James", lastName: "Madison" } );
In my own usage, I typically already have a handle to a channel (like the above snippet). However, there are times where you may decide to use the postal namespace's publish
method. If you do so, you have to provide the basic envelope structure yourself:
postal.publish( {
channel: "presidents",
topic: "constitution.contributors",
data: {
firstName: "James",
lastName: "Madison"
}
} );
Once the above message is published, postal will add the timestamp
property to the envelope. (It's also worth noting that the channel
property is optional, as postal will plug in a default channel if you don't specify one.)
Aside from the core metadata that postal expects to be present on an envelope (channel
, topic
, data
and timestamp
), you can customize the envelope by adding your own. Writing a postal add-on (like postal.request-response) is a good example of when you'd need to do this.
If you find you do need to add values to the envelope, it's recommended that you use the headers
property. For example, here's an envelope after postal.request-response has added headers:
{
"topic": "last.login",
"data": {
"userId": 8675309
},
"headers": {
"replyable": true,
"requestId": "d76b71be-d8d7-44ac-95d4-1d2f87251715",
"replyTopic": "d76b71be-d8d7-44ac-95d4-1d2f87251715",
"replyChannel": "postal.request-response"
},
"channel": "channel1",
"timeStamp": "2014-04-23T04:03:56.814Z"
}
NOTE: Using the
headers
property is recommended so that postal add-ons can have a consistent & predictable place to put metadata, and to also reduce the chances of collision with current or future envelope properties. If you're concerned about potential header key collision with other add-ons, you can namespace your header values on theheaders
property, or prefix them.