Skip to content

Instantly share code, notes, and snippets.

@chapel
Created January 12, 2012 04:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chapel/1598764 to your computer and use it in GitHub Desktop.
Save chapel/1598764 to your computer and use it in GitHub Desktop.
Mongoose publish
function shim(obj) {
if (toString.call(obj) == '[object Function]') {
return obj()
}
return obj
}
module.exports = function(schema, options) {
options || (options = {})
var autoPublish = (options.autoPublish || false)
, hook = (option.hook || 'post')
, sep = (options.seperator || ':')
, prefix = (options.prefix || '')
, channel = (options.channel || schema.constructor.modelName)
, pub = options.publish
, sub = (options.subscribe || false)
if (autoPublish) {
;['init'
, 'save'
, 'remove'
].forEach(function(method) {
schema[hook](method, function(next) {
this.publish({method: method})
next()
})
})
}
schema.method('publish', function(opt) {
opt || (opt = {})
pub.publish(prefix + sep + shim(channel), JSON.stringify({
options: opt
data: this.toObject())
})
})
;['subscribe'
, 'unsubscribe'
].forEach(function(method) {
;['method'
, 'static'
].forEach(function(key) {
schema[key](method, function() {
sub[method](prefix + sep + shim(channel) + (key === 'method' ? (sep + this._id) : ''))
})
})
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment