Parse Cloud Code query not getting executed - objective-c

I have the below cloud code function and when I call this function from my OS X app, I get the success response as well. But none of the console log output messages inside the success and failure blocks of the query operation gets executed. Any ideas on where to look would be much appreciated.
Parse.Cloud.define("markAlertAsExpired", function(request, response) {
Parse.Cloud.useMasterKey();
var Alert = Parse.Object.extend("Alert");
var query = new Parse.Query(Alert);
query.get("vC6ppoxuqd", {
success: function(alertObj) {
// The object was retrieved successfully.
var status = alertObj.get("status");
console.log("RECEIVED OBJECT WITH STATUS:");
console.log(status);
if (status == "active") {
console.log("active");
markActiveAlertAsExpired(alertObj);
} else if (status == "inactive") {
console.log("inactive");
markInactiveAlertAsExpired(alertObj);
} else {
console.error("unknown_status");
}
},
error: function(object, error) {
// The object was not retrieved successfully.
// error is a Parse.Error with an error code and message.
console.error("alert_not_found");
response.error("alert_not_found");
}
});
response.success("available");
});

You need to wait for your queries to complete before calling response.success, the updated code below should work.
Parse.Cloud.define("markAlertAsExpired", function(request, response) {
Parse.Cloud.useMasterKey();
var Alert = Parse.Object.extend("Alert");
var query = new Parse.Query(Alert);
query.get("vC6ppoxuqd", {
success: function(alertObj) {
// The object was retrieved successfully.
var status = alertObj.get("status");
console.log("RECEIVED OBJECT WITH STATUS:");
console.log(status);
if (status == "active") {
console.log("active");
markActiveAlertAsExpired(alertObj);
} else if (status == "inactive") {
console.log("inactive");
markInactiveAlertAsExpired(alertObj);
} else {
console.error("unknown_status");
}
response.success("available");
},
error: function(object, error) {
// The object was not retrieved successfully.
// error is a Parse.Error with an error code and message.
console.error("alert_not_found");
response.error("alert_not_found");
}
});
});

Related

Display backend error message after Create call

In my controller I have the following code - The problem is when it is error, I want to display exact error that is being passed from backend. But in my error handling function I never get any data. What is wrong here?
Controller.js
var token = null;
$.ajax({
url: sServiceURl,
type: "GET",
async: true,
beforeSend: function(xhr) {
sap.ui.core.BusyIndicator.show(0);
xhr.setRequestHeader("X-CSRF-Token", "Fetch");
},
complete: function(xhr) {
token = xhr.getResponseHeader("X-CSRF-Token");
oContext.OdataModel.create("/materialsSet", oContext.Data, null, oContext.submitSuccess.bind(oContext), oContext.submitError.bind(oContext));
}
});
submitSuccess: function(data, response, oContext) {
// works fine
},
submitError: function(oError) {
// I never get anything in oError, so the below code is useless.
try {
if (oError.responseText) {
obj = JSON.parse(oError.responseText);
message = obj.error.message.value;
} else if (oError.response.body) {
var errorModel = new sap.ui.model.xml.XMLModel();
errorModel.setXML(oError.response.body);
//Read message node
if (errorModel.getProperty("/0/message") !== "") {
message = errorModel.getProperty("/0/message");
} else {
message = message1;
}
} else {
message = message1;
}
} catch (error) {
message = message1;
}
sap.m.MessageToast.show(message);
},
Hope this will help you, first of all check backend response. I have use the below code for error handling.
submitError: function(responseBody) {
try {
var body = JSON.parse(responseBody);
var errorDetails = body.error.innererror.errordetails;
if (errorDetails) {
if (errorDetails.length > 0) {
for (i = 0; i < errorDetails.length; i++) {
console.log(errorDetails[i].message);
}
} else
console.log(body.error.message.value);
} else
console.log(body.error.message.value);
} catch (err) {
try {
//the error is in xml format. Technical error by framework
switch (typeof responseBody) {
case "string": // XML or simple text
if (responseBody.indexOf("<?xml") > -1) {
var oXML = jQuery.parseXML(responseBody);
var oXMLMsg = oXML.querySelector("message");
if (oXMLMsg)
console.log(oXMLMsg.textContent);
} else
console.log(responseBody);
break;
case "object": // Exception
console.log(responseBody.toString());
break;
}
} catch (err) {
console.log("common error message");
}
}
}

Get JavaScript Array of Objects to bind to .Net Core List of ViewModel

I have a JS Array of Objects which, at time of Post contains three variables per object:
ParticipantId,
Answer,
ScenarioId
During post, there is an Array the size of 8 (at current anyway) which all correctly contain data. When I call post request, the Controller does get hit as the breakpoint triggers, the issue is when I view the List<SurveyResponse> participantScenarios it is shown as having 0 values.
The thing I always struggle to understand is that magic communication and transform between JS and .Net so I am struggling to see where it is going wrong.
My JS Call:
postResponse: function () {
var data = JSON.stringify({ participantScenarios: this.scenarioResponses})
// POST /someUrl
this.$http.post('ScenariosVue/PostScenarioChoices', data).then(response => {
// success callback
}, response => {
// error callback
});
}
My .Net Core Controller
[HttpPost("PostScenarioChoices")]
public async Task<ActionResult> PostScenarioChoices(List<SurveyResponse> participantScenarios)
{
List<ParticipantScenarios> addParticipantScenarios = new List<ParticipantScenarios>();
foreach(var result in participantScenarios)
{
bool temp = false;
if(result.Answer == 1)
{
temp = true;
}
else if (result.Answer == 0)
{
temp = false;
}
else
{
return StatusCode(400);
}
addParticipantScenarios.Add(new ParticipantScenarios
{
ParticipantId = result.ParticipantId,
Answer = temp,
ScenarioId = result.ScenarioId
});
}
try
{
await _context.ParticipantScenarios.AddRangeAsync(addParticipantScenarios);
await _context.SaveChangesAsync();
return StatusCode(201);
}
catch
{
return StatusCode(400);
}
}

How to call to external function in axios.spread function in VueJS?

I can't call any external functions inside an axios promise. My error is
[Uncaught (in promise) TypeError: this.showNotification is not a function]
showNotification is an external function inside mixin but i can't call it in userCompInfo function
var mixin = {
methods: {
//function to get all user info
userInfo:function(){
//alert(localStorage.getItem("sessionKey"))
if(localStorage.getItem("sessionKey")==null)
session = "null";
else
session= localStorage.getItem("sessionKey");
return axios.post("/api/user/info",{
user_id:localStorage.getItem("userId"),
session_key:session
});
},
//function to get all competition info
compInfo:function()
{ //calling API competition info to get the avaliable competition for now
return axios.post("/api/competition/info",{
lang:source.lang
});
},
userCompInfo:function()
{
axios.all([this.userInfo(),this.compInfo()])
.then(axios.spread(function (user, comp){
if(comp.data.result.errorcode == 0)
{
source.competition = comp.data.competiton_detail;
}
//set the user id in local storage
localStorage.setItem("userId",user.data.user_info.user_id);
//check on session key to save it in local storage
if(user.data.user_info.session_key != "") // for testing
localStorage.setItem("sessionKey",user.data.user_info.session_key);
// get user data successfuly
if(user.data.result.errorcode == 0)
{ //set response data in user
source.user = user.data.user_info;
//to set this user status
this.renderUserInfo();
///////////
//source.competition.is_active=1;
//check on user status to show notification
if(source.user.vip && source.user.suspended)
{
this.showNotification(context.suspended_vip.title+" "+source.user.msisdn, context.suspended_vip.body,["btn_notifi_ok"]);
}
//check if this valid competition is active or not to show notification according to it and to user status
if(source.competition.is_active==1)
{
if(source.user.registered && newUser==1)
{
this.showNotification(context.registered_firstTime.title, context.registered_firstTime.body, ["btn_notifi_start_play"]);
}
else if(source.user.free && source.user.newFreeUser)
{
this.showNotification(context.freeUser_firstTime.title, context.freeUser_firstTime.body, ["btn_notifi_start_play"]);
}
}
}
}));
},
// function to show notification modal
showNotification:function(title, body, buttons)
{
//to hide all modal buttons first
$("#notification").find(".btn").hide();
//set the modal title
$("#notification_title").html(title);
//set the modal body
$("#notification_body").html(body);
//for on buttons array to show all buttons that we want
for(i=0;i<buttons.length;i++)
{
$("#notification").find("#"+buttons[i]).show();
}
//to display modal
$("#notification").modal("show");
},
//function to show the current user statue VIP, registered,free or suspended
renderUserInfo:function()
{ // intialize all flags of user status to false
source.user.vip = false;
source.user.registered = false;
source.user.free = false;
//check on user mode and set the according flag to it to true
if(source.user.sub_mode == "vip")
{
source.user.vip = true;
}
else if(source.user.sub_mode == "sub")
{
source.user.registered = true;
}
else
{
source.user.free = true;
}
},}}
This is a very common mistake. this in userCompInfo doesn't refer to the Vue because of they way you have written the callback.
In your code, make this change.
userCompInfo:function()
{
axios.all([this.userInfo(),this.compInfo()])
.then(axios.spread(function (user, comp){
// a bunch of code...
}.bind(this)));
},
Or
userCompInfo:function()
{
let self = this;
axios.all([this.userInfo(),this.compInfo()])
.then(axios.spread(function (user, comp){
// a bunch of code...
self.showNotification(...)
// some more code...
}));
},
See How to access the correct this inside a callback?

Karma unit test fails in phantomjs

After fixing alot of erros in the testing, now Karma output is this:
PhantomJS 1.9.8 (Windows 8 0.0.0) Controller: MainCtrl should attach a list of t hings to the scope FAILED
Error: Unexpected request: GET /api/marcas
No more request expected at ....
api/marcas is an endpoint i've created. code for MainCtrl:
'use strict';
angular.module('app')
.controller('MainCtrl', function ($scope, $http, $log, socket, $location, $rootScope) {
window.scope = $scope;
window.rootscope = $rootScope
$scope.awesomeThings = [];
$scope.things = ["1", "2", "3"];
$http.get('/api/things').success(function(awesomeThings) {
$scope.awesomeThings = awesomeThings;
socket.syncUpdates('thing', $scope.awesomeThings);
});
$scope.addThing = function() {
if($scope.newThing === '') {
return;
}
$http.post('/api/things', { name: $scope.newThing });
$scope.newThing = '';
};
$scope.deleteThing = function(thing) {
$http.delete('/api/things/' + thing._id);
};
$scope.$on('$destroy', function () {
socket.unsyncUpdates('thing');
});
$http.get('/api/marcas').success(function(marcas) {
$scope.marcas = marcas;
socket.syncUpdates('marcas', $scope.response);
$scope.marcasArr = [];
$scope.response.forEach(function(value) {
$scope.marcas.push(value.name);
});
$scope.marcaSel = function() {
for (i = 0; i < $scope.response.length; i++) {
if ($scope.selectedMarca == $scope.response[i].name) {
$scope.modelos = $scope.response[i].modelos;
};
};
};
});
until you didn't posted your test-code, I guess that your test doesn't includes the following code:
beforeEach(inject(function () {
httpBackend.expectGET('/api/marcas').respond(function(){
return {/*some status code*/, {/*some data*/}, {/*any headers*/}};
});
}));
if the karma-runner tries to execute your test-code, there are to get-requests to the $http-service, $http.get('/api/marcas') and $http.get('/api/things'). if one of these backend calls is not expected, karma cannot run the testcode successfully.
if you don't want to do special stuff for each but only return a default with success code for both calls, you can write so:
beforeEach(inject(function () {
httpBackend.expectGET(/api/i).respond(function(){
return {/*some status code*/, {/*some data*/}, {/*any headers*/}};
});
}));

Parse cloud query returns null result

I have the following cloud function
Parse.Cloud.define("test", function(request, response) {
Parse.Cloud.useMasterKey()
var query = new Parse.Query("Verification");
query.equalTo("objectId", "lHBL87Sg2H");
query.find({
success: function(results)
{
response.success(results[0].get("objectId"));
},
error: function()
{
response.error("failed");
}
});
})
I call this cloud function in Objective C with the following code,
[PFCloud callFunctionInBackground:#"test"
withParameters:nil
block:^(NSString *result, NSError *error) {
if (!error) {
NSLog(#"%#",result);
}
}];
The result of this call is (null).
The parse log shows the following record
I2015-04-20T20:07:29.383Z] v81: Ran cloud function test1 for user zOpfIOyZQ1 with:
Input: {}
Result: undefined
I also tried the promise but the output is still null.
To get an object given its id, use Query.get() as follows ...
Parse.Cloud.define("test", function(request, response) {
Parse.Cloud.useMasterKey();
var query = new Parse.Query("Verification");
query.get("lHBL87Sg2H").then(function(object) {
var objectId = object.id;
var someAttribute = object.get("foo");
response.success({"the id is":objectId, "foo is": someAttribute});
}, function(error) {
response.error("error " + error.message);
});
});