node opc-ua - how do i discover a variable in a server? - node.js

I am learning node opc-ua and have followed the example provided in the GitHub page for the sample_server.js and simple_client.js.
In the sample_server I add a variable when constructing the address space of the server such as:
//this code is in the server
addressSpace.addVariable({
componentOf: device,
nodeId: "ns=1;s=variable_1",
browseName: "MyVariable1",
dataType: "Double",
value: {
get: function () {
return new opcua.Variant({ dataType: opcua.DataType.Double, value: variable1 });
}
}
});
Here is the whole server code for reference:
var opcua = require("node-opcua");
var server = new opcua.OPCUAServer({
port: 4334, // the port of the listening socket of the server
resourcePath: "UA/MyLittleServer", // this path will be added to the endpoint resource name
buildInfo: {
productName: "MySampleServer1",
buildNumber: "7658",
buildDate: new Date(2014, 5, 2)
}
});
server.initialize(post_initialize);
function post_initialize() {
console.log("initialized");
construct_my_address_space(server, function () {
server.start(function () {
console.log("Server is now listening ... ( press CTRL+C to stop)");
console.log("port ", server.endpoints[0].port);
var endpointUrl = server.endpoints[0].endpointDescriptions()[0].endpointUrl;
console.log(" the primary server endpoint url is ", endpointUrl);
});
});
}
function construct_my_address_space(server, callback) {
var addressSpace = server.engine.addressSpace;
// declare a new object
var device = addressSpace.addObject({
organizedBy: addressSpace.rootFolder.objects,
browseName: "MyDevice"
});
// add a variable named MyVariable1 to the newly created folder "MyDevice"
var variable1 = 1;
// emulate variable1 changing every 500 ms
setInterval(function () { variable1 += 1; }, 500);
addressSpace.addVariable({
componentOf: device,
nodeId: "ns=1;s=variable_1",
browseName: "MyVariable1",
dataType: "Double",
value: {
get: function () {
return new opcua.Variant({ dataType: opcua.DataType.Double, value: variable1 });
}
}
});
callback();
}
Now, in the client i want to discover this variable by name or the full nodeId.
I am using the sample provided to browse the session to the server but in the return i only see FolderType, Objects, Types and Views and can not locate this variable anywhere.
Here is the client code:
var opcua = require("node-opcua");
var async = require("async");
var client = new opcua.OPCUAClient();
var endpointUrl = "opc.tcp://" + require("os").hostname() + ":4334/UA/MyLittleServer";
var the_session, the_subscription;
async.series([
// step 1 : connect to
function (callback) {
client.connect(endpointUrl, function (err) {
if (err) {
console.log(" cannot connect to endpoint :", endpointUrl);
} else {
console.log("connected !");
}
callback(err);
});
},
// step 2 : createSession
function (callback) {
client.createSession(function (err, session) {
if (!err) {
the_session = session;
}
callback(err);
});
},
// step 3 : browse
function (callback) {
the_session.browse("RootFolder", function (err, browse_result) {
if (!err) {
console.log('Result of browsing: ', browse_result);
browse_result[0].references.forEach(function (reference) {
console.log('browsing: ', reference.browseName);
console.log(reference);
console.log("**************************************");
});
}
callback(err);
});
},
/* step 4 : read a variable with readVariableValue
function (callback) {
the_session.readVariableValue("ns=1;s=variable_1", function (err, dataValue) {
if (!err) {
console.log(" var 1 = ", dataValue.toString());
}
callback(err);
});
},
// step 4' : read a variable with read
function (callback) {
var max_age = 0;
var nodes_to_read = [
{ nodeId: "ns=1;s=variable_1", attributeId: opcua.AttributeIds.Value }
];
the_session.read(nodes_to_read, max_age, function (err, nodes_to_read, dataValues) {
if (!err) {
console.log(" variable 1 = ", dataValues[0]);
}
callback(err);
});
},
*/
// step 5: install a subscription and install a monitored item for 10 seconds
function (callback) {
the_subscription = new opcua.ClientSubscription(the_session, {
requestedPublishingInterval: 1000,
requestedLifetimeCount: 10,
requestedMaxKeepAliveCount: 2,
maxNotificationsPerPublish: 10,
publishingEnabled: true,
priority: 10
});
the_subscription.on("started", function () {
console.log("subscription started for 2 seconds - subscriptionId=", the_subscription.subscriptionId);
}).on("keepalive", function () {
console.log("keepalive");
}).on("terminated", function () {
callback();
});
setTimeout(function () {
the_subscription.terminate();
}, 10000);
// install monitored item
var monitoredItem = the_subscription.monitor({
nodeId: opcua.resolveNodeId("ns=1;s=variable_1"),
attributeId: opcua.AttributeIds.Value
},
{
samplingInterval: 100,
discardOldest: true,
queueSize: 10
},
opcua.read_service.TimestampsToReturn.Both
);
console.log("-------------------------------------");
monitoredItem.on("changed", function (dataValue) {
console.log("variable_1 = ", dataValue.value.value);
});
},
// close session
function (callback) {
the_session.close(function (err) {
if (err) {
console.log("session closed failed ?");
} else{
console.log("session closed!");
}
callback();
});
}
],
function (err) {
if (err) {
console.log(" failure ", err);
} else {
console.log("done!");
}
client.disconnect(function () { });
});
Thanks in advance

You need to drill down from from the rootFolder and investigate the various objects until you find the variable you want to monitor, with a series of browseNode.
The best option is to use a free OPCUA client from a commercial vendor such as UAExpert or Prosys OPC UA Client to name a few.
You can also use opcua-commander: This little utility will allow you to explore the address space of the server and find the node you're looking for. ( source code available on github )

Related

Nodejs OPCUA multiple monitored items in a subscription object

i need subscribe to mutliple monitored item on a subcripiton object. I build below codes in nodejs and working.
const itemToMonitor = {
nodeId: resolveNodeId("ns=2;s=Channel1.Device1.temprature"),
attributeId: AttributeIds.Value
};
const itemToMonitor2 = {
nodeId: resolveNodeId("ns=2;s=Channel1.Device1.altitude"),
attributeId: AttributeIds.Value
};
const monitoringParamaters = {
samplingInterval: 1000,
discardOldest: true
};
the_subscription.monitor(itemToMonitor, monitoringParamaters, TimestampsToReturn.Both, (err, monitoredItem) => {
monitoredItem.on("changed", function (dataValue) {
console.log("monitored item changed: temprature = ", dataValue.value.value);
});
});
the_subscription.monitor(itemToMonitor2, monitoringParamaters, TimestampsToReturn.Both, (err, monitoredItem) => {
monitoredItem.on("changed", function (dataValue) {
console.log("monitored item changed: altitude = ", dataValue.value.value);
});
});
but i need something like that :
the_subscription.monitor({itemToMonitor,itemToMonitor2}, monitoringParamaters, TimestampsToReturn.Both, (err, monitoredItem) => {
monitoredItem.on("changed", function (datavalues) {
datavalues.each(){
//
}
});
});
Is it possible ? I did something similar to this in .net core:
.net core codes (what i want sample)
_subscription.AddItems(_nodes);
_subscription.FastDataChangeCallback = new FastDataChangeNotificationEventHandler(DataChanged);
_session.AddSubscription(_subscription);
_subscription.Create();
private void DataChanged(Subscription subscription, DataChangeNotification notification, IList<string> stringTable)
{
//
}
I solved;
its wrong;
the_subscription.monitor({itemToMonitor,itemToMonitor2}, monitoringParamaters, TimestampsToReturn.Both, (err, monitoredItem) => {
monitoredItem.on("changed", function (datavalues) {
});
});
its true
//monitoredNodes is an monitoredItem list
the_subscription.monitorItems(monitoredNodes, monitoringParamaters, TimestampsToReturn.Both, (err, monitoredItems) => {
monitoredItems.on("changed", function (items,data) {
console.log("Node ID: ", items.itemToMonitor.nodeId.value);
console.log("Node value: ", data.value.value);
});
});
Document : https://node-opcua.github.io/api_doc/2.32.0/classes/node_opcua.clientsubscription.html#monitoritems

Calling Azure SQL from Azure Functions node.js

I'm trying to use tedious library to inject simple insert from the incoming body. No error is thrown, but context.logs placed inside the functions are not displaying in logs. As a result in DB I have row with NULL values instead of what is passed. Any idea what am I doing wrong?
Is there any other library/method of accessing the Azure DB from Azure Functions or I am stuck with Tedious?
Of course I could probably use Azure Logic App but its more expensive to run than Azure Functions.
var Connection = require('tedious').Connection;
var Request = require('tedious').Request;
var TYPES = require('tedious').TYPES;
var globalheaders = {
Id: '1233',
Name: 'Ant',
Payment: "2019-10-09",
Type: 'Fixed cost',
Value: 156,
Cycle: '1',
Frequency: 'month'
}
module.exports = async function (context, req) {
context.log('JavaScript HTTP trigger function processed a request.');
globalheaders = req.body;
context.log(globalheaders);
var config = {
server: '********.database.windows.net', //update me
authentication: {
type: 'default',
options: {
userName: '*******', //update me
password: '*******' //update me
}
},
options: {
// If you are on Microsoft Azure, you need encryption:
encrypt: true,
database: 'cashmandb' //update me
}
};
var connection = new Connection(config);
await connection.on('connect', function(err) {
if (err) {
context.log(err);
context.res = {
status: 500,
body: "Unable to establish a connection."
};
context.done();
} else {
context.log('before execution');
executeStatement();
}
});
context.log('connection executed')
async function executeStatement() {
request = new Request("INSERT dbo.cost (Id, Name, Payment, Type, Value, Cycle, Frequency) OUTPUT INSERTED.Id VALUES (#Id, #Name, #Payment, #Type, #Value, #Cycle, #Frequency);", function(err) {
if (err) {
context.log(err);}
});
context.log('executestatement')
request.addParameter('Id', TYPES.NChar,globalheaders.id);
request.addParameter('Name', TYPES.NVarChar , globalheaders.name);
request.addParameter('Payment', TYPES.Date, globalheaders.payment);
request.addParameter('Type', TYPES.NVarChar,globalheaders.type);
request.addParameter('Value', TYPES.Int,globalheaders.value);
request.addParameter('Cycle', TYPES.NChar,globalheaders.cycle);
request.addParameter('Frequency', TYPES.NChar,globalheaders.frequency);
request.on('row', function(columns) {
columns.forEach(function(column) {
if (column.value === null) {
context.log('NULL');
} else {
context.log("Product id of inserted item is " + column.value);
}
});
});
await connection.execSql(request);
}
context.done();
};
Try this :
var Connection = require('tedious').Connection;
var Request = require('tedious').Request;
var TYPES = require('tedious').TYPES;
module.exports = async function (context, req) {
context.log('JavaScript HTTP trigger function processed a request.');
var config = {
server: 'xxxx.database.windows.net', //update me
authentication: {
type: 'default',
options: {
userName: 'xxx', //update me
password: 'xxx' //update me
}
},
options: {
// If you are on Microsoft Azure, you need encryption:
encrypt: true,
database: 'xxx' //update me
}
};
var connection = new Connection(config);
await connection.on('connect', function(err) {
if (err) {
context.log(err);
context.res = {
status: 500,
body: "Unable to establish a connection."
};
context.done();
} else {
executeStatement(req.body);
}
});
async function executeStatement(globalheaders) {
request = new Request("INSERT dbo.cost (Id, Name, Payment, Type, Value, Cycle, Frequency) OUTPUT INSERTED.Id VALUES (#Id, #Name, #Payment, #Type, #Value, #Cycle, #Frequency);", function(err) {
if (err) {
context.log(err);}
});
request.addParameter('Id', TYPES.NChar,globalheaders.Id);
request.addParameter('Name', TYPES.NVarChar , globalheaders.Name);
request.addParameter('Payment', TYPES.Date,globalheaders.Payment);
request.addParameter('Type', TYPES.NVarChar,globalheaders.Type);
request.addParameter('Value', TYPES.Int,globalheaders.Value);
request.addParameter('Cycle', TYPES.NChar,globalheaders.Cycle);
request.addParameter('Frequency', TYPES.NChar,globalheaders.Frequency);
request.on('row', function(columns) {
columns.forEach(function(column) {
if (column.value === null) {
context.log('NULL');
} else {
context.log("Product id of inserted item is " + column.value);
}
});
});
await connection.execSql(request);
}
context.done();
};
Test result on local :
Data has been insetted into Azure SQL DB successfully:
I believe the problem here is that you are mixing async/await and context.done(). You should just use 1 of the 2 as required.
Also, I believe tedious doesn't support async/await in the first place. So, removing the that and just having context.done() should do.
After long battle it appears that for some reason Azure Functions prefers adressing the property by value string:
request.addParameter('Id', TYPES.NChar,globalheaders['Id']);
request.addParameter('Name', TYPES.NVarChar , globalheaders['Name']);
request.addParameter('Payment', TYPES.Date, globalheaders['Payment']);
request.addParameter('Type', TYPES.NVarChar,globalheaders['Type']);
request.addParameter('Value', TYPES.Int,globalheaders['Value']);
request.addParameter('Cycle', TYPES.NChar,globalheaders['Cycle']);
request.addParameter('Frequency', TYPES.NChar,globalheaders['Frequency']);
After changing to this everything started to work
The correct way to achieve it is by using sync code. Tedious uses event based programming paradigm and do not support async programming paradigms. So to explicitly mark the completion of azure function we use context.done() method. So the right code would be as follows:
var Connection = require('tedious').Connection;
var Request = require('tedious').Request;
var TYPES = require('tedious').TYPES;
module.exports = function (context, req) {
context.log('JavaScript HTTP trigger function processed a request.');
var config = {
server: 'xxxx.database.windows.net', //update me
authentication: {
type: 'default',
options: {
userName: 'xxx', //update me
password: 'xxx' //update me
}
},
options: {
// If you are on Microsoft Azure, you need encryption:
encrypt: true,
database: 'xxx' //update me
}
};
var connection = new Connection(config);
connection.connect();
connection.on('connect', function(err) {
if (err) {
context.res = {
status: 500,
body: "Unable to establish a connection."
};
context.done();
} else {
executeStatement(req.body);
}
});
function executeStatement(globalheaders) {
request = new Request("INSERT dbo.cost (Id, Name, Payment, Type, Value, Cycle, Frequency) OUTPUT INSERTED.Id VALUES (#Id, #Name, #Payment, #Type, #Value, #Cycle, #Frequency);", function(err) {
if (err) {
context.log(err);}
});
request.addParameter('Id', TYPES.NChar,globalheaders.Id);
request.addParameter('Name', TYPES.NVarChar , globalheaders.Name);
request.addParameter('Payment', TYPES.Date,globalheaders.Payment);
request.addParameter('Type', TYPES.NVarChar,globalheaders.Type);
request.addParameter('Value', TYPES.Int,globalheaders.Value);
request.addParameter('Cycle', TYPES.NChar,globalheaders.Cycle);
request.addParameter('Frequency', TYPES.NChar,globalheaders.Frequency);
request.on('row', function(columns) {
columns.forEach(function(column) {
if (column.value === null) {
context.log('NULL');
} else {
context.log("Product id of inserted item is " + column.value);
}
});
});
request.on("requestCompleted", function (rowCount, more) {
connection.close();
context.res = {
status: 200, /* Defaults to 200 */
body: JSON.stringify(result),
headers: {
' Content-Type': 'application/json'
}
};
context.done();
});
connection.execSql(request);
}
};

Backbone and Express: concatinating (duplicating) routes on res.redirect

I have an action where I need to update MongoDB entry including _id field, which requires deleting old entry and making a new one, here is server side:
exports.update = function(req, res, next){
var outcome = [];
outcome.previousId = req.params.id;
outcome.newId = req.body.name;
var getPreviousRecord = function(callback) {
req.app.db.models.AccountGroup
.findOne({ _id: req.params.id })
.lean()
.exec(function(err, accountGroups) {
if (err) {
return callback(err, null);
}
outcome.accountGroups = accountGroups;
return callback(null, 'done');
});
};
var makeNewRecord = function(callback) {
var permissions = outcome.accountGroups.permissions;
var fieldsToSet = {
_id: outcome.newId.toLowerCase(),
name: outcome.newId,
permissions: permissions
};
req.app.db.models.AccountGroup
.create(fieldsToSet, function(err, record) {
if (err) {
return callback(err, null);
}
outcome.record = record;
return callback(null, 'done');
});
};
var deletePreviousRecord = function() {
req.app.db.models.AccountGroup
.findByIdAndRemove(outcome.previousId)
.exec(function(err) {
if (err) {
return next(err);
}
res.redirect('admin/account-groups/' + outcome.newId + '/');
});
};
var asyncFinally = function(err) {
if (err) {
return next(err);
}
};
require('async').series([getPreviousRecord, makeNewRecord, deletePreviousRecord], asyncFinally);
};
It works fine, but I can't make this work normally on the front-end, it returns me both old route and a new route, for example:
PUT /admin/account-groups/customers22/admin/account-groups/Customers2233/ 404 213.749 ms - 31
where customers22 is old _id and customers2233 is new _id. If I navigate from another page to new entry it gets route normally.
On client side:
(function() {
'use strict';
app = app || {};
app.Details = Backbone.Model.extend({
idAttribute: '_id',
defaults: {
success: false,
errors: [],
errfor: {},
name: ''
},
url: function() {
return '/admin/account-groups/'+ app.mainView.model.id +'/';
},
parse: function(response) {
if (response.accountGroup) {
app.mainView.model.set(response.accountGroup);
delete response.accountGroup;
}
return response;
}
});
app.DetailsView = Backbone.View.extend({
el: '#details',
events: {
'click .btn-update': 'update'
},
template: Handlebars.compile( $('#tmpl-details').html() ),
initialize: function() {
this.model = new app.Details();
this.syncUp();
this.listenTo(app.mainView.model, 'change', this.syncUp);
this.listenTo(this.model, 'sync', this.render);
this.render();
},
syncUp: function() {
this.model.set({
_id: app.mainView.model.id,
name: app.mainView.model.get('name')
});
},
render: function() {
this.$el.html(this.template( this.model.attributes ));
for (var key in this.model.attributes) {
if (this.model.attributes.hasOwnProperty(key)) {
this.$el.find('[name="'+ key +'"]').val(this.model.attributes[key]);
}
}
},
update: function() {
this.model.save({
name: this.$el.find('[name="name"]').val()
});
}
});
app.MainView = Backbone.View.extend({
el: '.page .container',
initialize: function() {
app.mainView = this;
this.model = new app.AccountGroup( JSON.parse( unescape($('#data-record').html()) ) );
// ...
app.detailsView = new app.DetailsView();
}
});
$(document).ready(function() {
app.mainView = new app.MainView();
});
}());
It probably requires to trigger both model.save and model.destroy or prevent URL being used. Any advice on how to do it is appreciated, thank you.
Edit
Just a typo mistake here that is not related to the question, recklessly checking routes, see as cancelled
I believe the problem is here:
res.redirect('admin/account-groups/' + outcome.newId + '/');
That's a relative path so it'll be appended onto the current URL. I suspect you want something like this:
res.redirect('/admin/account-groups/' + outcome.newId + '/');

nodejs - test failing but callback being called

I have a module which I export and which has a method editHeroImage which I am trying to test using mocha, chai and sinon. The modules has two objects that are passed as arguments, connection and queries. These are mySql objects, one containing the connection to the database and the other the query strings which are defined in their separate modules. The expObj which I am exporting and trying to test is a "helper" module.
I have successfully tested other methods of this module in the same way I am trying to test this method, but, however when I run into methods which use the async module for some reason, my tests no longer behave as expected. I wonder if I am missing something in this particular case, because I have tested other modules and methods which also use async and have not come across this behaviour.
When I run the tests, it logs "HELLO!" as expected but the assertion that the callbackSpy has been called, fails.
I am losing my mind here! Please help! What is going on? Could there be contamination between test suits?
Method under test:
expObj.editHeroImage = function(connection, queries, postId, postData, callback) {
async.waterfall([
function(next) {
var qString = queries.getSinglePostById();
connection.query(qString, [postId], function(err, results) {
if (err) {
return next(err);
}
if (!results.length) {
console.log('NO POST FOUND WITH ID ' + postId);
return callback();
}
next(null, results[0].hero_image);
});
},
function(heroImageId, next) {
if (!heroImageId) {
console.log('HERO IMAGE IS NEW - NEXT TICK!');
return next();
}
// Delete resized images of hero image
var queryStr = queries.deleteResizedImages();
var resizedVals = [heroImageId];
connection.query(queryStr, resizedVals, function(err) {
if (err) {
return callback(err);
}
console.log('DELETED RESIZED IMAGES OF HERO IMAGE ' + heroImageId);
var qString = queries.updateHeroImagePath();
var values = [postData.hero_image, heroImageId];
return connection.query(qString, values, function(err, results) {
if (err) {
return next(err);
}
console.log('UPDATED HERO IMAGE ' + heroImageId + ' WITH PATH ' + postData.hero_image);
next('break');
});
});
},
function addHeroImage(next) {
var qString = queries.insertImage();
var values = [postData.hero_image, postId];
connection.query(qString, values, function(err, results) {
if (err) {
return next(err);
}
next(null, results.insertId);
});
},
function addHeroImagePathToPost(heroImageId, next) {
var qString = queries.saveHeroImageId();
var values = [heroImageId, postId];
connection.query(qString, values, function(err) {
if (err) {
return next(err);
}
next();
});
}
], function(err) {
if (err && err !== 'break') {
return callback(err);
}
console.log('HELLO!');
callback(null);
});
};
Test, with set-up:
'use strict';
var chai = require('chai');
var sinonChai = require("sinon-chai");
var proxyquire = require('proxyquire');
var sinon = require('sinon');
chai.use(sinonChai);
var expect = chai.expect;
describe('HELPERS', function() {
var testedModule,
callbackSpy,
fakeConnectionObj,
fakeQueriesObj,
fakePost,
fakeSnakeCaseObj,
queryStub,
connectionStub,
manageStub,
fakeCamelCaseObj;
beforeEach(function() {
fakePost = {};
fakeConnectionObj = {};
fakeQueriesObj = {
getPostIdFromImage: function() {},
insertResizedImages: function() {},
createPost: function() {},
getPostImages: function() {},
getPostsAlternativesImages: function() {},
getSinglePostById: function() {},
getAllImages: function() {},
insertImage: function() {},
deleteMainImage: function() {},
deleteResizedImages: function() {},
updateHeroImagePath: function() {},
saveHeroImageId: function() {}
};
afterEach(function() {
queryStub.resetBehavior();
});
fakeSnakeCaseObj = {
sub_title: '123',
hero_image: '456'
};
fakeCamelCaseObj = {
subTitle: '123',
heroImage: '456'
};
callbackSpy = sinon.spy();
queryStub = sinon.stub();
manageStub = sinon.stub();
connectionStub = {query: queryStub};
testedModule = proxyquire('./../../../../lib/modules/mySql/workers/helpers', {
'./../../../factories/notification-service': {
select: function() {
return {manageSns: manageStub};
}
}
});
});
it('edits hero image', function() {
var _post = {
id: '123',
title: 'vf',
sub_title: 'vf',
slug: 'vf',
reading_time: 4,
created_at: '123',
published_at: '123',
deleted_on: false,
hero_image: 'hero_image_path'
};
var _postId = '123';
queryStub.onCall(0).callsArgWith(2, null, [{hero_image: '55'}]);
queryStub.onCall(1).callsArgWith(2, null);
queryStub.onCall(2).callsArgWith(2, null);
testedModule.editHeroImage(connectionStub, fakeQueriesObj, _postId, _post, function() {
console.log(arguments); // --> {'0': null} as expected
callbackSpy.apply(null, arguments);
});
expect(callbackSpy).has.been.calledWith(null);
});
});
Your assertion is probably executing before your async function has returned.
There are a number of ways to ensure your async functions have finished executing. The cleanest is to format your mocha test differently.
describe('...', function () {
var callbackSpy;
before(function () {
var _post = {
id: '123',
title: 'vf',
sub_title: 'vf',
slug: 'vf',
reading_time: 4,
created_at: '123',
published_at: '123',
deleted_on: false,
hero_image: 'hero_image_path'
};
var _postId = '123';
queryStub.onCall(0).callsArgWith(2, null, [{
hero_image: '55'
}]);
queryStub.onCall(1).callsArgWith(2, null);
queryStub.onCall(2).callsArgWith(2, null);
return testedModule.editHeroImage(connectionStub, fakeQueriesObj, _postId, _post, function () {
console.log(arguments); // --> {'0': null} as expected
callbackSpy.apply(null, arguments);
});
});
it('edits hero image', function () {
expect(callbackSpy).has.been.calledWith(null);
});
});
Notice that I have wrapped your assertion in a describe block so we can use before. Your actual logic for setting up stubs and executing the class has been moved to the before block and a return added, this ensures the async function is complete before moving on to your assertions.
Your other tests may have passed, but they will also be susceptible to this and it is purely a timing issue.
Indeed #Varedis was right about it being a timing issue. However using your suggestion of wrapping the assertion in a describe bloack and using the before function to set-up the test resulted in my stubs no longer working correctly. However taking your suggestion about timing into account I managed to solve the issue by using the done callback within my test suit. By keeping the set-up I made a slight change and my tests suddenly passed:
it('edits hero image', function(done) {
var _post = {
id: '123',
title: 'vf',
sub_title: 'vf',
slug: 'vf',
reading_time: 4,
created_at: '123',
published_at: '123',
deleted_on: false,
hero_image: 'hero_image_path'
};
var _postId = '123';
queryStub.onCall(0).callsArgWith(2, null, [{hero_image: '55'}]);
queryStub.onCall(1).callsArgWith(2, null);
queryStub.onCall(2).callsArgWith(2, null);
testedModule.editHeroImage(connectionStub, fakeQueriesObj, _postId, _post, function() {
callbackSpy.apply(null, arguments);
expect(callbackSpy).has.been.calledWith(null);
expect(callbackSpy).has.not.been.calledWith('FDgdjghg');
done();
});
});

node js mongo db dependencies (doc not being found)

I have the following code:
var method = PushLoop.prototype;
var agent = require('./_header')
var request = require('request');
var User = require('../models/user_model.js');
var Message = require('../models/message_model.js');
var async = require('async')
function PushLoop() {};
method.startPushLoop = function() {
getUserList()
function getUserList() {
User.find({}, function(err, users) {
if (err) throw err;
if (users.length > 0) {
getUserMessages(users)
} else {
setTimeout(getUserList, 3000)
}
});
}
function getUserMessages(users) {
// console.log("getUserMessages")
async.eachSeries(users, function (user, callback) {
var params = {
email: user.email,
pwd: user.password,
token: user.device_token
}
messageRequest(params)
callback();
}, function (err) {
if (err) {
console.log(err)
setTimeout(getUserList, 3000)
}
});
}
function messageRequest(params) {
var url = "https://voip.ms/api/v1/rest.php?api_username="+ params.email +"&api_password="+ params.pwd +"&method=getSMS&type=1&limit=5"
request(url, function(err, response, body){
if (!err) {
var responseObject = JSON.parse(body);
var messages = responseObject.sms
if (responseObject["status"] == "success") {
async.eachSeries(messages, function(message, callback){
console.log(params.token)
saveMessage(message, params.token)
callback();
}, function(err) {
if (err) {
console.log(err)
}
// setTimeout(getUserList, 3000)
})
} else {
// setTimeout(getUserList, 3000)
}
} else {
console.log(err)
// setTimeout(getUserList, 3000)
}
});
setTimeout(getUserList, 3000)
}
function saveMessage(message, token) {
// { $and: [ { price: { $ne: 1.99 } }, { price: { $exists: true } }
// Message.find({ $and: [{ message_id: message.id}, {device_token: token}]}, function (err, doc){
Message.findOne({message_id: message.id}, function (err, doc){
if (!doc) {
console.log('emtpy today')
var m = new Message({
message_id: message.id,
did: message.did,
contact: message.contact,
message: message.message,
date: message.date,
created_at: new Date().toLocaleString(),
updated_at: new Date().toLocaleString(),
device_token: token
});
m.save(function(e) {
if (e) {
console.log(e)
} else {
agent.createMessage()
.device(token)
.alert(message.message)
.set('contact', message.contact)
.set('did', message.did)
.set('id', message.id)
.set('date', message.date)
.set('message', message.message)
.send();
}
});
}
}) //.limit(1);
}
};
module.exports = PushLoop;
Which actually works perfectly fine in my development environment - However in production (i'm using Openshift) the mongo documents get saved in an endless loop so it looks like the (if (!doc)) condition always return true therefore the document gets created each time. Not sure if this could be a mongoose issue - I also tried the "find" method instead of "findOne". My dev env has node 0.12.7 and Openshift has 0.10.x - this could be the issue, and i'm still investigating - but if anybody can spot an error I cannot see in my logic/code please let me know
thanks!
I solved this issue by using a "series" like pattern and using the shift method on the users array. The mongoose upsert findOneOrCreate is good however if there is a found document, the document is returned, if one isn't found and therefore created, it's also returned. Therefore I could not distinguish between the newly insert doc vs. a found doc, so used the same findOne function which returns null if no doc is found I just create it and send the push notification. Still abit ugly, and I know I could have used promises or the async lib, might refactor in the future. This works for now
function PushLoop() {};
var results = [];
method.go = function() {
var userArr = [];
startLoop()
function startLoop() {
User.find({},function(err, users) {
if (err) throw err;
users.forEach(function(u) {
userArr.push(u)
})
function async(arg, callback) {
var url = "https://voip.ms/api/v1/rest.php?api_username="+ arg.email +"&api_password="+ arg.password +"&method=getSMS&type=1&limit=5"
request.get(url, {timeout: 30000}, function(err, response, body){
if (!err) {
var responseObject = JSON.parse(body);
var messages = responseObject.sms
var status = responseObject.status
if (status === "success") {
messages.forEach(function(m) {
var message = new Message({
message_id: m.id,
did: m.did,
contact: m.contact,
message: m.message,
date: m.date,
created_at: new Date().toLocaleString(),
updated_at: new Date().toLocaleString(),
device_token: arg.device_token
});
var query = { $and : [{message_id: m.id}, {device_token: arg.device_token}] }
var query1 = { message_id: m.id }
Message.findOne(query).lean().exec(function (err, doc){
if (!doc || doc == null) {
message.save(function(e) {
console.log("message saved")
if (e) {
console.log("there is an error")
console.log(e)
} else {
console.log(message.device_token)
var messageStringCleaned = message.message.toString().replace(/\\/g,"");
var payload = {
"contact" : message.contact,
"did" : message.did,
"id" : message.message_id,
"date" : message.date,
"message" : messageStringCleaned
}
var note = new apns.Notification();
var myDevice = new apns.Device(message.device_token);
note.expiry = Math.floor(Date.now() / 1000) + 3600; // Expires 1 hour from now.
note.badge = 3;
note.alert = messageStringCleaned;
note.payload = payload;
apnsConnection.pushNotification(note, myDevice);
}
})
}
});
});
}
else {
console.log(err)
}
}
});
setTimeout(function() {
callback(arg + "testing 12");
}, 1000);
}
// Final task (same in all the examples)
function series(item) {
if(item) {
async( item, function(result) {
results.push(result);
return series(userArr.shift());
});
} else {
return final();
}
}
function final() {
console.log('Done');
startLoop();
}
series(userArr.shift())
});
}
}
module.exports = PushLoop;

Resources