Getting a response from an Azure insert - azure-mobile-services

I have inherited the development of an iOS app that connects to an Azure mobile service, and I'm stuck on getting an acceptable response from my insert operations. Specifically I want to get back the object that was inserted, or at least the value of its id field, from a Custom API script that the previous developer on this project created.
A truncated version of the Custom API script I'm using looks like:
exports.post = function(request, response) {
var mssql = request.service.mssql;
var sql = "INSERT INTO Reservation (<field names>)" +
" VALUES (<field values>); "
+"SELECT id FROM Reservation WHERE __updatedAt = (SELECT MAX(__updatedAt) FROM Reservation);";
mssql.query(sql, {
success: function(results) {
console.log("after post - results = " + results);
response.send(statusCodes.OK, results);
}
});
};
When I run the iOS app and post a Reservation (using the AFNetworking class to communicate with the server), I get back a response object with an empty array. Furthermore, inspecting the Azure log for the results of the console.log statement in my function, I see two results: "after post - results = [object Object]" and "after post - results =".
I'm clearly doing something wrong, but I don't understand what. I have tried a number of other different approaches, all with similarly unsatisfactory results. For what it's worth, the "get" script for this class works just fine. I wonder if anybody can help me get this "post" script right.

As you noted in your logs, the success callback for the mssql.query call is being called twice - since you have two statements in your query. When you first call response.send, that's the response which is sent back to the client. The first callback will contain the results for the INSERT call, which is not what you want to return. You should use a flag to indicate which result you're receiving, and only return if it's the one you want:
exports.post = function(request, response) {
var mssql = request.service.mssql;
var sql = "INSERT INTO Reservation (<field names>)" +
" VALUES (<field values>); "
+"SELECT id FROM Reservation WHERE __updatedAt = (SELECT MAX(__updatedAt) FROM Reservation);";
var firstCall = true;
mssql.query(sql, {
success: function(results) {
console.log("after post - results = " + results);
if (firstCall) {
firstCall = false;
} else {
response.send(statusCodes.OK, results);
}
}
});
};

Related

error: function pgp_sym_encrypt(bytea, text) does not exist

I am trying to run a query from my nodejs app to update encrypted data into a column. However I am seeing the error below -
error: function pgp_sym_encrypt(unknown, unknown) does not exist
query snippet
client.query('UPDATE application_test set content = pgp_sym_encrypt($2,$3) where application_id = $1', [appId, data, password], function (dbErr: any, result: any) {
done();
if (dbErr) {
reject(dbErr);
} else {
resolve();
}
});
However the below sql works fine when I run using postgresql client :
update application_test set content = pgp_sym_encrypt('{"appId":"122345"}', 'password')
where application_id='122345';
EDIT: Turns out that I was running the query using client with my dba password. However from the code it is a different user which is connecting to same database. How can I make the pgp_sym_encrypt utility visible for othe users using the same database?
I guess you need to explicitly type cast the call of you function like this
client.query('UPDATE application_test set content = pgp_sym_encrypt($2 ::text,$3 ::text) where application_id = $1', [appId, data, password], function (dbErr: any, result: any) {
done();
if (dbErr) {
reject(dbErr);
} else {
resolve();
}
});
P.S. pgp_sym_encryp function is visible to all user.

Send two params in GET request

I'm pretty new using vertx framework, and in the documentation I cannot see the silly thing about how to send two parameters in a GET request. So far I tried this.
$.getJSON('/user/'+ attributeName + ":"+value, function (data) {
userListData = data;
$.each(data, function () {
$('#userInfoName').text(data.fullname);
$('#userInfoAge').text(data.age);
$('#userInfoGender').text(data.gender);
$('#userInfoLocation').text(data.location);
});
});
And then in server side
router.get("/user/:attributeName:value").handler(routingContext -> {
JsonObject query = new JsonObject();
query.put(routingContext.request().getParam("attributeName"), routingContext.request().getParam("value"));
But then I can see how attributeName not only gets the value of the first param but part of the second, very weird.
You're probably doing it wrong. You can get it as a single param and later split with ":" or have two parameters defined in the url as... /:attribname/:value/...
Both will handle your requirement

Azure Mobile Services Node.js update column field count during read query

I would like to update a column in a specific row in Azure Mobile Services using server side code (node.js).
The idea is that the column A (that stores a number) will increase its count by 1 (i++) everytime a user runs a read query from my mobile apps.
Please, how can I accomplish that from the read script in Azure Mobile Services.
Thanks in advance,
Check out the examples in the online reference. In the table Read script for the table you're tracking you will need to do something like this. It's not clear whether you're tracking in the same table the user is reading, or in a separate counts table, but the flow is the same.
Note that if you really want to track this you should log read requests to another table and tally them after the fact, or use an external analytics system (Google Analytics, Flurry, MixPanel, Azure Mobile Engagement, etc.). This way of updating a single count field in a record will not be accurate if multiple phones read from the table at the same time -- they will both read the same value x from the tracking table, increment it, and update the record with the same value x+1.
function read(query, user, request) {
var myTable = tables.getTable('counting');
myTable.where({
tableName: 'verses'
}).read({
success: updateCount
});
function updateCount(results) {
if (results.length > 0) {
// tracking record was found. update and continue normal execution.
var trackingRecord = results[0];
trackingRecord.count = trackingRecord.count + 1;
myTable.update(trackingRecord, { success: function () {
request.execute();
});
} else {
console.log('error updating count');
request.respond(500, 'unable to update read count');
}
}
};
Hope this helps.
Edit: fixed function signature and table names above, adding another example below
If you want to track which verses were read (if your app can request one at a time) you need to do the "counting" request and update after the "verses" request, because the script doesn't tell you up front which verse records the user requested.
function read(query, user, request) {
request.execute( { success: function(verseResults) {
request.respond();
if (verseResults.length === 1) {
var countTable = tables.getTable('counting');
countTable.where({
verseId: verseResults[0].id
}).read({
success: updateCount
});
function updateCount(results) {
if (results.length > 0) {
// tracking record was found. update and continue normal execution.
var trackingRecord = results[0];
trackingRecord.count = trackingRecord.count + 1;
countTable.update(trackingRecord);
} else {
console.log('error updating count');
}
}
}
});
};
Another note: make sure your counting table has an index on the column you're selecting by (tableName in the first example, verseId in the second).

Sails GET request doesn't return data from all columns in my Postgres DB

I'm using $sailsSocket to make my GET and POST requests. My POST request looks like this;
$sailsSocket.post('/schedules/toDateObj',
{ jobSchedObj:
{ repair_shop_equipment_id: response.config.data.schedEquip.rsrcId,
repair_history_id: response.data.id,
technician_id: response.data.technician_id,
allotted_time: response.data.allotted_time,
times: timeObj,
repair_shop_id: $localstorage.get('shopId')
}
})
.success(function(){
$location.path('/app/checkin');
})
.error(function (response){
console.log(response);
});
And here is the table it saves to...
Everything saves fine I even threw a console.log in my ScheduleController to check what was being inserted in the database with my POST request. Here is the output;
The problem is when I make a GET request to the Schedule table it comes back with everything except repair_shop_equipment_id. Here is the get request;
var firstDay = scope.getJobsFor[0];
var lowerBound = firstDay.open_time;
var lastDay = scope.getJobsFor[scope.getJobsFor.length - 1];
var upperBound = lastDay.close_time;
$sailsSocket.get("/schedules", {params:
{where: {
repair_shop_id: scope.shopId,
technician_id: scope.schedTech.id,
repair_shop_equipment_id: scope.schedEquip.rsrcId,
scheduled_start_time:{ date: {'>':lowerBound, '<':upperBound}}
}
}
})
.success(function (response){
And this is the response...
Here is a link to a Gist with my associated Sails models and the schedule controller;
Is there something wrong with one of my model configurations? Thanks.

SugarCRM REST API Session expires frequently

I use REST API in JavaScript. When I request REST API multiple times, it returns(response) invalid session id, but I am providing a valid session id, because I have pulled data with this session id.
Anyone came across this issue?
function sugarLogin(url, user, password) {
var request = new XMLHttpRequest();
var params = {
user_auth: {
user_name: user,
password: password
},
name_value_list: [{
name: 'notifyonsave',
value: 'true'
}]
};
var json = $.toJSON(params);
var crm_api = url;
request.open("POST", crm_api, true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.onreadystatechange = function () {
if (request.readyState == 4 && request.status == 200) {
var response = request.responseText;
var response_obj = jQuery.parseJSON(response);
if (response_obj) {
if (response_obj.name && response_obj.name == "Invalid Login") {
//invalid login
ProcessingFlag = 3;
} else {
session_id = response_obj.id;
ProcessingFlag = 1;
}
}
} else if (request.readyState == 4 && request.status == 404) {
ProcessingFlag = 2;
}
}
request.send("method=login&input_type=JSON&response_type=JSON&rest_data=" + json);}
I have used above code to login and set session_id (global scope)
and then using this session id I am calling search_by_module function of REST API.
It is working fine but if made multiple requests frequently then it says invalid session id.
Although I have tried to call login function again before making search_by_module call.
Main issue is when I tried calling other REST function after response returned from search_by_module and rendered HTML, it says me invalid session. I can't figure out why session expires immediately while we know that on server session expires after 24 minutes (server where our sugar instance hosted)
I bet you're getting this because of item number 3 :
1/ Defined an error callback that checks for that particular response -invalid login- and calls the login function. Reading your code, I guess this is ProcessingFlag = 3; job.
2/ make sure the login function updates the session_id correctly and globally so that future function calls will get the correct value.
3/ make sure you're passing that new session_id to all your subsequent calls as FIRST parameter in all you rest_data. I got caught on this and lost many hours only to find out that SugarCRM DOESN'T support named parameters in its rest_data (is it poorely implemented function-arguments-wise ?) This is because I was adding session_id as last parameter and all of my REST calls were returning invalid ID.