loopback-connector-natsgetter
Advanced tools
Comparing version 1.0.0 to 1.1.0
@@ -11,3 +11,2 @@ // Copyright IBM Corp. 2013,2016. All Rights Reserved. | ||
const app = require('../../server/server'); | ||
const uid = require('uuid/v4'); | ||
const bson = require('bson'); | ||
@@ -24,7 +23,4 @@ const assert = require('assert'); | ||
function NatsGetter(settings) { | ||
this.subscribeName = settings.natsSubscribeName; | ||
this.publishName = settings.natsPublishName; | ||
assert(this.subscribeName, 'subscribeName must be defined in datasource settings'); | ||
assert(this.publishName, 'publishName must be defined in datasource settings'); | ||
this._callbacks = new Map(); | ||
this.constructor.super_.call(this, 'natsgetter', settings); | ||
@@ -35,32 +31,21 @@ } | ||
NatsGetter.prototype.connect = function (callback) { | ||
NatsGetter.prototype.all = function all(model, filter, options, callback) { | ||
const self = this; | ||
process.nextTick(() => { | ||
app.models.Nats.subscribe(self.subscribeName).then(subscribeHandler).catch(callback); | ||
app.models.Nats.publish(self.publishName, { command: 'all', model, data: filter }, (err, reply) => { | ||
if (err) return callback(err); | ||
reply.forEach(val => { | ||
if (val.created && !(val.created instanceof Date)) | ||
val.created = new Date(val.created); | ||
val.id = ObjectID(val.id); | ||
}); | ||
return callback(null, reply); | ||
}); | ||
function subscribeHandler(subscriber) { | ||
let res; | ||
subscriber.on('message', msg => { | ||
res = JSON.parse(msg.getData()); | ||
if (self._callbacks.has(res.guid)) { | ||
res.data.forEach(val => { | ||
if (val.created && !(val.created instanceof Date)) | ||
val.created = new Date(val.created); | ||
val.id = ObjectID(val.id); | ||
}); | ||
self._callbacks.get(res.guid)(null, res.data); | ||
self._callbacks.delete(res.guid); | ||
} | ||
}); | ||
} | ||
callback(); | ||
} | ||
NatsGetter.prototype.all = function all(model, filter, options, callback) { | ||
NatsGetter.prototype.create = function create(model, data, options, callback) { | ||
const self = this; | ||
const guid = uid(); | ||
app.models.Nats.publish(self.publishName, { data: { model, filter }, guid }).then(() => { | ||
self._callbacks.set(guid, callback); | ||
}).catch(callback); | ||
} | ||
app.models.Nats.publish(self.publishName, { command: 'create', model, data }, (err, id) => { | ||
return callback(err, id); | ||
}); | ||
}; | ||
@@ -67,0 +52,0 @@ NatsGetter.prototype.getDefaultIdType = function () { |
{ | ||
"name": "loopback-connector-natsgetter", | ||
"version": "1.0.0", | ||
"version": "1.1.0", | ||
"description": "", | ||
@@ -5,0 +5,0 @@ "main": "natsgetter.js", |
2246
57