Code 141 (error: success/error was not called) on Parse Cloud Code nested queries - ios

Background:
I have a Parse database of images. Simply, my code does this:
A user, through a Parse Cloud call requests an image ("getNewPicture"). Nested within I check if he has seen any pictures before (alongside other requirements) and if so deliver one specific picture (getSpecifiedPicture). If he has not, then I deliver a new picture (getNewPicture).
Issue:
Calling "getNewPicture" through Parse Cloud Code function I get an error code 141. What's strange is that it works through Android but not iOS.
My code:
Parse.Cloud.define("getNewPicture", function(request, response) {
var SeenPictures = Parse.Object.extend("SeenPictures");
var query = new Parse.Query(SeenPictures);
var username = request.params.username;
var notWantedPics = [];
query.ascending("createdAt");
query.equalTo("username", username);
query.find({
success: function(results) {
for (var i = 0; i < results.length; i++) {
if (results[i].get("likes") == 1 || results[i].get("dislikes") == 1) {
notWantedPics.push(results[i].get("pictureId"));
results.splice(i, 1);
i--;
}
}
if (results != 0) {
getSpecifiedPicture(results[0].get("pictureId"), {
success: function(returnValue) {
response.success(returnValue);
},
error: function(error) {
response.error(error);
}
});
} else {
getNewPicture(username, notWantedPics, {
success: function(returnValue) {
response.success(returnValue);
},
error: function(error) {
response.error(error);
}
});
}
},
error: function() {
response.error(error);
}
});
});
function getSpecifiedPicture(specifiedPic, callback) {
var Pictures = Parse.Object.extend("Pictures");
var pictures = new Parse.Query(Pictures);
pictures.get(specifiedPic, {
success: function(picture) {
callback.success(picture);
},
error: function(error) {
callback.error(error);
}
});
}
function getNewPicture(username, notWantedPics, callback) {
var Pictures = Parse.Object.extend("Pictures");
var pictures = new Parse.Query(Pictures);
pictures.notEqualTo("photographerUserName", username);
pictures.notContainedIn("objectId", notWantedPics);
pictures.ascending("createdAt");
pictures.find({
success: function(results) {
if (results.length > 0) {
var object = results[0];
//Some other fancy stuff
object.save();
callback.success(object);
}
},
error: function(error) {
callback.error(error);
}
});
}
Why am I getting code 141? Any help is appreciated.
Thanks.

Your callbacks are a mess. I rewrote it to follow more of a promise chain style. Much easier to follow. Also, underscore.js is your friend. Hopefully I got your idea right.
var _ = require('underscore'); // Javascript Library
Parse.Cloud.define("getNewPicture", function(request, response) {
var username = request.params.username;
var notWantedPics = [];
if (!username) {
return response.error('No username.');
}
var query1 = new Parse.Query("SeenPictures");
query1.ascending("createdAt");
query1.equalTo("username", username);
var SeenPictures = query1.find();
return Parse.Promise.when([SeenPictures]).then(function (SeenPictures) {
SeenPictures = _.filter(SeenPictures, function (SeenPicture) {
if (SeenPicture.get("likes") == 1 || SeenPicture.get("dislikes") == 1) {
notWantedPics.push(SeenPicture.get("pictureId"));
return false;
}
else {
return true;
}
});
// notWantedPics?
if (SeenPictures > 0) {
var query2 = new Parse.Query("Pictures");
var Pictures = [query2.get(SeenPictures[0].get('pictureId'))];
}
else {
var query2 = new Parse.Query("Pictures");
query2.notEqualTo("photographerUserName", username);
query2.notContainedIn("objectId", notWantedPics);
query2.ascending("createdAt");
var Pictures = query2.find();
}
return Parse.Promise.when([Pictures]);
}).then(function (Pictures) {
if (Pictures > 0) {
// Success
return response.success(Pictures[0]);
} else {
return Parse.Promise.error("No pictures.");
}
}, function (error) {
// Error
return response.error(error);
});
});

Related

Netlify functions with axios

I want to make my form submission happen server-side in order to not expose my API key. I plan to do this with netlify functions however I don't know how that would look with Axios. I've looked for examples on how to do this but I don't seem to find any. Could some help me I'm stuck as to what to put inside my the Netlify function? If anyone has worked with these two programs and could provide a hand that would be helpful here is my javascript with my submission function.
var form = document.querySelector("#user_form");
let reqHeaders = {
headers: {
Authorization: "Bearer",
}
}
let url = ""
let reqData = {
records: [
{
fields: null
}
]
}
let formData = {
firstName: "",
lastName: "",
email: ""
}
function logData(id, dataObj, value) {
dataObj[id] = value;
console.log(value)
}
function formMessg (id) {
document.querySelector(id).style.display = "block";
setTimeout(function(){
document.querySelector(id).style.display = "none";
form.reset();
}, 2500)
}
form.addEventListener("submit", function (e) {
e.preventDefault();
let spam = document.getElementById('spam').value;
try {
for(const data in formData){
if(formData[data] === "" || spam.length !== 0){
const error = new Error();
error.notVaild = true;
throw error;
}
}
reqData.records[0].fields = formData;
console.log(reqData);
axios.post(url, reqData, reqHeaders).then((res) => {
formMessg ('.success-messg');
form.style.display = "none";
})
.catch ((err) => {
throw err;
});
} catch (err){
if (err.reponse){
formMessg ('.fail-messg');
} else if (err.request) {
formMessg ('.fail-messg');
} else if ("Notvalid") {
formMessg ('.fill-messg');
}else {
console.log(err);
}
}
});

How to resolve `Uncaught (in promise) DOMException: Quota exceeded` error in service worker when browsing website in `Incognito mode` in Google chrome

How to resolve(or hide) Uncaught (in promise) DOMException: Quota exceeded error in service worker when browsing website in Incognito mode in Google chrome.
Every thing works fine in normal mode.
Service worker code of my progressive web app is
var version = 'v2:';
var offlineFundamentals = [
'/',
'/offline.html'
];
var updateStaticCache = function () {
return caches.open(version + 'fundamentals').then(function (cache) {
return Promise.all(offlineFundamentals.map(function (value) {
var request = new Request(value);
var url = new URL(request.url);
if (url.origin != location.origin) {
request = new Request(value, {
mode: 'no-cors'
});
}
return fetch(request).then(function (response) {
var cachedCopy = response.clone();
return cache.put(request, cachedCopy);
});
}))
})
};
var clearOldCaches = function () {
return caches.keys().then(function (keys) {
return Promise.all(keys.filter(function (key) {
return key.indexOf(version) != 0;
}).map(function (key) {
return caches.delete(key);
}));
});
};
var limitCache = function (cache, maxItems) {
cache.keys().then(function (items) {
if (items.length > maxItems) {
cache.delete(items[0]);
}
})
};
var trimCache = function (cacheName, maxItems) {
caches.open(cacheName).then(function (cache) {
cache.keys().then(function (keys) {
if (keys.length > maxItems) {
cache.delete(keys[0]).then(trimCache(cacheName, maxItems));
}
});
});
};
var hasUrlCacheExcludeMatch = function (url) {
var cacheExcludeUrls = [
"https:\/\/example.com\/user\/login",
"https:\/\/example.com\/user\/register"
];
return cacheExcludeUrls.some(path => url.includes(path));
};
self.addEventListener("install", function (event) {
event.waitUntil(updateStaticCache().then(function () {
return self.skipWaiting();
}));
});
self.addEventListener("message", function (event) {
var data = event.data;
if (data.command == "trimCache") {
trimCache(version + "pages", 80);
trimCache(version + "images", 50);
trimCache(version + "assets", 50);
}
});
self.addEventListener("fetch", function (event) {
var fetchFromNetwork = function (response) {
var cacheCopy = response.clone();
if (event.request.headers.get('Accept').indexOf('text/html') != -1) {
if (!hasUrlCacheExcludeMatch(event.request.url)) {
caches.open(version + 'pages').then(function (cache) {
cache.put(event.request, cacheCopy).then(function () {
limitCache(cache, 80);
})
});
}
} else if (event.request.headers.get('Accept').indexOf('image') != -1) {
caches.open(version + 'images').then(function (cache) {
cache.put(event.request, cacheCopy).then(function () {
limitCache(cache, 50);
});
});
} else {
caches.open(version + 'assets').then(function add(cache) {
cache.put(event.request, cacheCopy).then(function () {
limitCache(cache, 50);
});
});
}
return response;
}
var fallback = function () {
if (event.request.headers.get('Accept').indexOf('text/html') != -1) {
return caches.match(event.request).then(function (response) {
return response || caches.match('/offline.html');
})
}
}
if (event.request.method != 'GET') {
return;
}
if (event.request.headers.get('Accept').indexOf('text/html') != -1) {
event.respondWith(fetch(event.request).then(fetchFromNetwork, fallback));
return;
}
event.respondWith(caches.match(event.request).then(function (cached) {
return cached || fetch(event.request).then(fetchFromNetwork, fallback);
}))
});
self.addEventListener("activate", function (event) {
event.waitUntil(clearOldCaches().then(function () {
return self.clients.claim();
}));
});
Browsing website in Normal mode in Google chrome works fine no error occures in console.
I am not good in service worker so I am unable to resolve this issue.
This is a bit unobvious.
Quota exceed error means that your out of available space, which is 6% of total space for Chrome.
For incognito mode all storage and workers api is working, but quota space is equals zero bytes and, thus, you can not write to it.

Passing String parameter Value Through angular Service parameter Value is Automatically Appends Some Special Character

Here's my Angular controller
//Save And Update
$scope.AddUpdateBusinessType = function() {
var businessType = {
Code: $scope.businessCode,
BusiType: $scope.businessType
};
var getBusinessTypeAction = $scope.BusinessTypeAction;
if (getBusinessTypeAction == "Update") {
businessType.BusinessTypeId = $scope.businessTypeId;
var getBusinessTypeData = businessTypeService.updateBusinessType(businessType);
getBusinessTypeData.then(function (msg) {
GetAllBusinessType();
$scope.ClearBusinessTypeForm();
alert("Record Updated Successful");
$scope.BusinessTypeAction = "";
$scope.divBusinessType = false;
}, function () {
alert('Error in Updating Record');
});
} else {
**// Save Section**
var getExistBusinessCode = businessTypeService.checkBusinessTypeCode(businessType.Code);
getExistBusinessCode.then(function (businessTypeCode) {
debugger;
if (businessTypeCode == true) {
alert('Business Type Code Already Exist');
} else {
debugger;
var getBusinessTypeData = businessTypeService.addBusinessType(businessType);
getBusinessTypeData.then(function (msg) {
GetAllBusinessType();
$scope.ClearBusinessTypeForm();
alert("Record Added Successful");
$scope.divBusinessType = false;
}, function () {
alert("Error Occured In Saving Data");
});
}
},function() {
alert('Error Occured While Checking Records');
});
}
}
In the above code Save Section I am trying to check if a value is exists in a database so I'm passing a string value to: checkBusinessTypeCode(businessType.Code) Service.When I Debug and See Value its Seems Normal.
Here's My Service:
//Check Business Code
this.checkBusinessTypeCode = function (businessTypeCode) {
debugger;
var response = $http({
method: "post",
url: "/BusinessType/CheckBusinessTypeDetailByCode",
params: {
businessTypeCode: JSON.stringify(businessTypeCode)
}
});
return response;
}
But when Passing To Controller string value I get some unexpected behavior.
two \\ always appear automatically
example
"\"stringvalue\""
I'm Still Having Above Problem
but as a quick solution i did code as follows
public bool _CheckBusinessTypeDetailByCode(string businessTypeCode)
{
string bisCode = businessTypeCode.Replace("\"", "");
bool isExist;
isExist = _IBusinessTypeRepository.IsExist(x => x.IsActive && !x.IsDelete && x.Code == bisCode);
return isExist;
}
I don't know is it bad practice or not , any way it is solved my problem.
Before did this modification
string businessTypeCode always gives value as
"\"somevalue\""

Parse: Failed with: success/error was not called

I am trying to authenticate my social media accounts through Parse via OAuth and it authenticates fine but i keep getting a Failed with success/error was not called; my code is below, can anyone help?
Parse.Cloud.define("createNewNetwork", function(request, response) {
Parse.Cloud.useMasterKey();
//console.log(request.user.id);
userHasRole(request.user.id, 'AllUsers').then(function(hasRole){
if (hasRole){
var Network = Parse.Object.extend("Network");
var query = new Parse.Query(Network);
query.equalTo("userId", request.params.userId);
query.equalTo("owner", request.user);
query.first({useMasterKey:true}).then(function(network) {
var newNetwork;
if (!network) {
newNetwork = new Network();
var custom_acl = new Parse.ACL();
custom_acl.setWriteAccess(request.user, true);
custom_acl.setPublicReadAccess(true);
newNetwork.setACL(custom_acl);
newNetwork.set("userId", request.params.userId);
newNetwork.set("followingCount", request.params.followingCount);
newNetwork.set("owner", request.user);
newNetwork.set("userData", request.params.userData);
newNetwork.set("networkName", request.params.networkName);
newNetwork.set("screenName", request.params.screenName);
} else {
newNetwork = network;
}
newNetwork.set("tokenExpired", false);
//console.log(request.params.oAuthData["access_token"]);
if (request.params.networkName == "facebook-page") {
Parse.Cloud.httpRequest({
url: 'https://graph.facebook.com/v2.1/oauth/access_token?grant_type=fb_exchange_token&client_id=**************&client_secret=***************&fb_exchange_token='+request.params.oAuthData["access_token"],
success: function(httpResponse2) {
//console.log(httpResponse2);
if (httpResponse2.status == 200) {
var data = {};
data["access_token"] = httpResponse2.text.substring(13);
newNetwork.save({oAuthData : data}, {
success: function(savedNetwork) {
response.success(savedNetwork);
},
error: function(error) {
response.error(error);
}
});
} else {
response.error("invalid token");
}
},
error: function(httpResponse2) {
console.log(httpResponse2);
response.error('Request failed with response code ' + httpResponse2.status);
}
});
} else {
newNetwork.save({oAuthData : request.params.oAuthData}, {
success: function(savedNetwork) {
response.success(savedNetwork);
},
error: function(error) {
response.error(error);
}
});
}
});
} else {
response.error("not in role");
}
});
});
Parse.Cloud.define("fetchNetworks", function(request, response) {
var attributesToHide = ["oAuthData"];
Parse.Cloud.useMasterKey();
userHasRole(request.user.id, 'AllUsers').then(function(hasRole){
if (hasRole){
var Network = Parse.Object.extend("Network");
var query = new Parse.Query(Network);
query.descending("followingCount");
var user = new Parse.User();
user.id = request.params.userToFetch;
user.fetch({}).then(function(user) {
query.equalTo("owner", user);
query.find().then(function(networks) {
networks.forEach(function(network) {
attributesToHide.forEach(function(attr) {
delete network.attributes[attr];
});
});
return response.success(networks);
});
});
} else{
response.success({super: false});
}
});
});
Line No - 101 - Removal of return should work.

Private_pub : How to unsubscribe from a channel

I am making a private chatting application using private_pub, my question is how to unsubscribe from a channel using private_pub?
thanks for your help
if you are using pjax or ajax a lot in your site and the page you are loading with ajax you have private_pub subscribe method there you will find that It's subscribing many times
after searching a lot about that I found these fork from privat_pub javascript file which solved these problem
var PrivatePub = (function (doc) {
var self = {
connecting: false,
fayeClient: null,
fayeCallbacks: [],
subscriptions: {},
subscriptionCallbacks: {},
faye: function(callback) {
if (self.fayeClient) {
callback(self.fayeClient);
} else {
self.fayeCallbacks.push(callback);
if (self.subscriptions.server && !self.connecting) {
self.connecting = true;
if (typeof Faye === 'undefined') {
var script = doc.createElement("script");
script.type = "text/javascript";
script.src = self.subscriptions.server + ".js";
script.onload = self.connectToFaye;
doc.documentElement.appendChild(script);
} else {
self.connectToFaye();
}
}
}
},
connectToFaye: function() {
self.fayeClient = new Faye.Client(self.subscriptions.server);
self.fayeClient.addExtension(self.fayeExtension);
for (var i=0; i < self.fayeCallbacks.length; i++) {
self.fayeCallbacks[i](self.fayeClient);
};
},
fayeExtension: {
outgoing: function(message, callback) {
if (message.channel == "/meta/subscribe") {
// Attach the signature and timestamp to subscription messages
var subscription = self.subscriptions[message.subscription];
if (!message.ext) message.ext = {};
message.ext.private_pub_signature = subscription.signature;
message.ext.private_pub_timestamp = subscription.timestamp;
}
callback(message);
}
},
sign: function(options) {
if (!self.subscriptions.server) {
self.subscriptions.server = options.server;
}
if (!self.subscriptions[options.channel]) {
self.subscriptions[options.channel] = options;
self.faye(function(faye) {
faye.subscribe(options.channel, self.handleResponse);
});
}
},
handleResponse: function(message) {
if (message.eval) {
eval(message.eval);
}
if (callback = self.subscriptionCallbacks[message.channel]) {
callback(message.data, message.channel);
}
},
subscribe: function(channel, callback) {
self.subscriptionCallbacks[channel] = callback;
}
};
return self;
}(document));
try it.

Resources