What is the query to fetch result from database in deployd server? - deployd

I am new in delpoyd server and need to validate email address already exist.
I read his document but unable to achieve result as expected.
According to deployd doc, I was trying this.
dpd['to-do'].get(query, function (result) { console.log(result); });
Please help me if anyone know.

This is the code I use for validating whether email already exists.I use this code in the Validate event.The need for checking the method 'PUT' is to prevent users from changing the email id to something that already exists after registering.
function validate(result, field) {
if (method === 'PUT') {
if (result.length === 0) {
} else if (!(result.length === 1 && result[0].id === id)) {
error(field, field + " is already in use");
}
} else if (result.length !== 0) {
error(field, field + " is already in use");
}
}
if (!internal) {
var email;
var method = ctx.method;
email = {
"email": this.email
};
dpd.users.get(email, function (result) {
validate(result, "email");
});
}

Related

selec2 search - Return no results found message if a specific criteria didnt match

I am using select2 4.0.3 for search drop down. As per my understanding its default functionality is not to match with the start of entries the drop down have. So I have implemented the below given code
function matchStart(params, data) {
params.term = params.term || '';
if (data.text.toUpperCase().indexOf(params.term.toUpperCase()) == 0) {
return data;
}
return false;
}
$("select").select2({
placeholder : "Input country name or select region",
matcher : function (params, data) {
return matchStart(params, data);
},
});
My problem is, the dropdown is not showing "No results found" message even if there is no matching results found. Can anyone help me on this.
Thanks in advance.
Try changing the return value of matchStart from false to null.
Also you can remove the extra function around the matcher argument. The result:
function matchStart(params, data) {
params.term = params.term || '';
if (data.text.toUpperCase().indexOf(params.term.toUpperCase()) == 0) {
return data;
}
return null;
}
$("select").select2({
placeholder: "Input country name or select region",
matcher: matchStart
});

IOS 10.3.1 cordova based App crashes when trying to write to IndexedDB

I'm developing a cordova-based multi-platform web-app using sapui5 framework v1.44 and indexedDB for storing data.The app was working fine untill last ios update, 10.3.1, now it crashes when trying to write to indexedDB. I'm using put method for updating data and i did a clean install of the app. The code frame where i try to write to indexedDB is this:
writeToIDB: function (objStoreName, result, success, error) {
//Asynchronous function
var defer = Q.defer();
var res = [];
if (!!result && Array.isArray(result)) {
res = result;
} else if (!!result && result.hasOwnProperty("results") && Array.isArray(result.results)) {
res = result.results;
} else if (!!result && typeof result === 'object') {
res.push(result);
}
if (res.length >= 0) {
if (window.myDB) {
if (!window.myDB.objectStoreNames.contains(objStoreName)) {
console.log("ObjectStore for " + objStoreName + " doesn't exist");
if (error) {
error("ko")
} else {
defer.reject("ko");
}
} else {
var oTransaction = window.myDB.transaction([objStoreName], "readwrite");
var oDataStore = oTransaction.objectStore(objStoreName);
oTransaction.oncomplete = function (event) {
console.log("Transaction completed: database modification for " + objStoreName + " finished.");
if (success) {
success();
} else {
defer.resolve("ok");
}
};
oTransaction.onerror = function (event) {
console.log("Transaction for " + objStoreName + " not opened due to error. Check for duplicate items or missing properties!");
console.log(event.target.error);
if (error) {
error("ko")
} else {
defer.reject("ko");
}
};
var oRecord = {};
for (var i = 0; i < res.length; i++) {
oRecord = res[i];
oDataStore.put(oRecord);
}
}
} else {
this.createIDB().then(
function (resCreate) {
console.log("DB Created successfully");
if (!window.myDB.objectStoreNames.contains(objStoreName)) {
console.log("ObjectStore for " + objStoreName + " doesn't exist");
if (error) {
error("ko")
} else {
defer.reject("ko");
}
} else {
var oTransaction = window.myDB.transaction([objStoreName], "readwrite");
var oDataStore = oTransaction.objectStore(objStoreName);
oTransaction.oncomplete = function (event) {
console.log("Transaction completed: database modification for " + objStoreName + " finished.");
if (success) {
success();
} else {
defer.resolve("ok");
}
};
oTransaction.onerror = function (event) {
console.log("Transaction for " + objStoreName + " not opened due to error. Check for duplicate items or missing properties!");
console.log(event.target.error);
if (error) {
error("ko")
} else {
defer.reject("ko");
}
};
var oRecord = {};
for (var i = 0; i < res.length; i++) {
oRecord = res[i];
oDataStore.put(oRecord);
}
}
}.bind(this),
function (err) {
console.log("DB Creation failed");
if (error) {
error("ko")
} else {
defer.reject("ko");
}
}.bind(this)
);
}
} else {
if (error) {
error("ko")
} else {
defer.reject("ko");
}
}
if (typeof success === 'undefined' && typeof error === 'undefined') {
return defer.promise;
}
},
P.S.I have omitted parts of the code.
This was working fine with the previous version of ios, i think i had installed the 10.2.1, now it simply crashes after calling the put method. I tried upgrading now ios to the beta of 10.3.2 but the result is the same. Anyone else noticed this or have any idea of how to resolve this problem?
Thanks
K
UPDATE
I've found the issue: the complex dataTypes. Since IndexedDB supports saving and retrieving complex dataTypes, i had some properties which were arrays or objects that i used to save in some of my ObjectStores. This is definitely a big problem for me because the only workaround i can think for this is to stingify the complex fields but since i work with a lot of data this would create a big performance issue. I hope the ios developer team will find a solution for this soon enough
Are you sure every key in the res[] array is a valid key? There is a closed bug here:
https://bugs.webkit.org/show_bug.cgi?id=170000
It looks if you pass in an invalid key it will cause webkit to crash.
This fix for this will likely be contained in the next public release of iOS.
To determine what a valid key is see this section of the W3.org spec:
3.1.3 Keys
In order to efficiently retrieve records stored in an indexed database, each record is organized according to its key. A value is said to be a valid key if it is one of the following ECMAScript [ECMA-262] types: Number primitive value, String primitive value, Date object, or Array object. An Array is only a valid key if every item in the array is defined and is a valid key (i.e. sparse arrays can not be valid keys) and if the Array doesn't directly or indirectly contain itself. Any non-numeric properties on an Array are ignored, and thus do not affect whether the Array is a valid key. If the value is of type Number, it is only a valid key if it is not NaN. If the value is of type Date it is only a valid key if its [[PrimitiveValue]] internal property, as defined by [ECMA-262], is not NaN. Conforming user agents must support all valid keys as keys.
This was taken from here:
https://www.w3.org/TR/IndexedDB/#key-construct
Not sure if it's the same issue, but I had a crash on iOS 10.3 that I didnt get in any other browser. Using Dexie wrapper for indexedDB, I did a get all records from table search:
db.table.toArray(function (results) {
// process...
})
and got flames from Xcode to what looked like a threading issue in WebKit so I just added setTimeout( ... ,1) and that hacked around the problem for me.

Is there a way to enforce single device login on parse.com?

I am developing an app where I need to be very API request frugal, the less requests the better. The problem is every user has settings and messages and I want to avoid to pull for possible changes on every wake up. And I can't rely on that every user enables push notifications.
My approach is as a compromise to enforce that a user can only be logged in with one device. If they try to login with another device (via facebook) they get an error message where they can choose to either cancel the login or go ahead and logout the other device remotely.
Is this possible?
I found a solution to this problem.
Query number of sessions after login
If the number is greater than 1 ask user what do
logout other device (and go ahead) -> call "deleteAllOtherSessions"
cancel login (and go back to login screen) -> call "deleteLastSession"
Cloud code:
Parse.Cloud.define("getSessionCount", function(request, response) {
if (request.user == null) {
reportError("findSessions", "userCheck", 0);
response.error("invalid user");
return
}
var query = new Parse.Query(Parse.Session);
query.find({
success: function(results) {
response.success(results.length);
},
error: function(error) {
response.error(error);
}
});
});
Parse.Cloud.define("deleteAllOtherSessions", function(request, response) {
if (request.user == null) {
reportError("deleteAllOtherSessions", "userCheck", 0);
response.error("invalid user");
return
}
var sessionToken = request.params.sessionToken;
var query = new Parse.Query(Parse.Session);
// this query will find only sessions owned by the user since
// we are not using the master key
query.find().then(function(results) {
var promises = [];
_.each(results, function (result) {
if(result.get("sessionToken") != sessionToken) {
promises.push(result.destroy());
}
});
return Parse.Promise.when(promises);
}).then(function() {
response.success(true);
},
function(error) {
response.error(error)
});
});
Parse.Cloud.define("deleteLastSession", function(request, response) {
if (request.user == null) {
reportError("deleteLastSession", "userCheck", 0);
response.error("invalid user");
return
}
var sessionToken = request.params.sessionToken;
var query = new Parse.Query(Parse.Session);
query.descending("createdAt");
// this query will find only sessions owned by the user since
// we are not using the master key
query.find().then(function(results) {
var promises = [];
console.log(results);
promises.push(results[0].destroy());
return Parse.Promise.when(promises);
}).then(function() {
response.success(true);
},
function(error) {
response.error(error)
});
});
Hope that helps somebody.

Login via Titanium sync adapter for Rails

I want to be able to log in my Titanium app with credentials from my Rails app database.
In Titanium, I created the following model:
exports.definition = {
config: {
'adapter': {
'type': 'myAdapter',
'base_url': 'http://server:3000/api/users/'
}
},
extendModel: function(Model) {
_.extend(Model.prototype, {
// custom functions
login: function() {
this.sync("login", this);
}
});
return Model;
},
extendCollection: function(Collection) {
_.extend(Collection.prototype, {});
return Collection;
}
}
The sync adapter I created, from the Twitter example given in the official Appcelerator doc:
// Global URL variable
var BASE_URL = 'http://server:3000/api/';
// Override the Backbone.sync method with the following
module.exports.sync = function(method, model, options) {
var payload = model.toJSON();
var error;
switch(method) {
// custom cases
case 'login':
http_request('POST', BASE_URL + 'login', payload, callback);
break;
// This case is called by the Model.fetch and Collection.fetch methods to retrieve data.
case 'read':
// Use the idAttribute property in case the model ID is set to something else besides 'id'
if (payload[model.idAttribute]) {
// If we have an ID, fetch only one tweet
http_request('GET', BASE_URL + '', {
id : payload[model.idAttribute]
}, callback);
} else {
// if not, fetch as many as twitter will allow us
http_request('GET', BASE_URL + '', null, callback);
}
break;
// This case is called by the Model.save and Collection.create methods
// to a initialize model if the IDs are not set.
// For example, Model.save({text: 'Hola, Mundo'})
// or Collection.create({text: 'Hola, Mundo'}) executes this code.
case 'create':
if (payload.text) {
http_request('POST', BASE_URL + 'update.json', {
status : payload.text
}, callback);
} else {
error = 'ERROR: Cannot create tweet without a status!';
}
break;
// This case is called by the Model.destroy method to delete the model from storage.
case 'delete':
if (payload[model.idAttribute]) {
// Twitter uses a POST method to remove a tweet rather than the DELETE method.
http_request('POST', BASE_URL + 'destroy/' + payload[model.idAttribute] + '.json', null, callback);
} else {
error = 'ERROR: Model does not have an ID!';
}
break;
// This case is called by the Model.save and Collection.create methods
// to update a model if they have IDs set.
case 'update':
// Twitter does not have a call to change a tweet.
error = 'ERROR: Update method is not implemented!';
break;
default :
error = 'ERROR: Sync method not recognized!';
};
if (error) {
options.error(model, error, options);
Ti.API.error(error);
model.trigger('error');
}
// Simple default callback function for HTTP request operations.
function callback(success, response, error) {
res = JSON.parse(response);
console.log("response |" + response);
console.log("res |" + res);
console.log("res str |" + JSON.stringify(res))
console.log("options |" + options);
if (success) {
// Calls the default Backbone success callback
// and invokes a custom callback if options.success was defined.
options.success(res, JSON.stringify(res), options);
}
else {
// res.errors is an object returned by the Twitter server
var err = res.errors[0].message || error;
Ti.API.error('ERROR: ' + err);
// Calls the default Backbone error callback
// and invokes a custom callback if options.error was defined.
options.error(model, err, options);
model.trigger('error');
}
};
};
// Helper function for creating an HTTP request
function http_request(method, url, payload, callback) {
// Generates the OAuth header - code not included
var header;
//= generate_header(method, url, payload);
var client = Ti.Network.createHTTPClient({
onload : function(e) {
if (callback)
callback(true, this.responseText, null);
},
onerror : function(e) {
if (callback)
callback(false, this.responseText, e.error);
},
timeout : 5000
});
// Payload data needs to be included for the OAuth header generation,
// but for GET methods, the payload data is sent as a query string
// and needs to be appended to the base URL
if (method == 'GET' && payload) {
var values = [];
for (var key in payload) {
values.push(key + '=' + payload[key]);
}
url = url + '?' + values.join('&');
payload = null;
}
client.open(method, url);
//client.setRequestHeader('Authorization', header);
client.send(payload);
};
// Perform some actions before creating the Model class
module.exports.beforeModelCreate = function(config, name) {
config = config || {};
// If there is a base_url defined in the model file, use it
if (config.adapter.base_url) {
BASE_URL = config.adapter.base_url;
}
return config;
};
// Perform some actions after creating the Model class
module.exports.afterModelCreate = function(Model, name) {
// Nothing to do
};
The rails app responds with JSON and it works but the problem is in the callback function:
[INFO] : response |{"email":"huhu#gmail.com","password":null}
[ERROR] : Script Error {
[INFO] : res |[object Object]
[INFO] : res str |{"email":"huhu#gmail.com","password":null}
[INFO] : options |[object Object]
[ERROR] : backtrace = "#0 () at file://localhost/.../xxx.app/alloy/sync/myAdapter.js:4";
[ERROR] : line = 30;
[ERROR] : message = "'undefined' is not a function (evaluating 'options.success(res, JSON.stringify(res), options)')";
[ERROR] : name = TypeError;
[ERROR] : sourceId = 216868480;
[ERROR] : sourceURL = "file://localhost/.../xxx.app/alloy/sync/myAdapter.js";
[ERROR] : }
So, does somebody have an idea why options is undefined...? Note that if I call the fetch method to get users using the read method, it works. By the way, is there a good way in authenticating somebody?
you are not passing in an options parameter in your model try making a change like this below
this.sync("login", this, {
success: function() {},
error: function(){}
});

How can we send/get the http headers information with AJAX?

Is there any way to send/get the http headers (like, content-type... ) through AJAX?. Then, can please explain me, what will we archive by passing the http headers in AJAX and where will use this technique?.
Thanks
I'm no expert,
But you should look at the AJAX object XmlHttpHeader and the wikipedia article here.
EDIT: quoting the www.w3.org reference:
function test(data) {
// taking care of data
}
function handler() {
if(this.readyState == 4 && this.status == 200) {
// so far so good
if(this.responseXML != null && this.responseXML.getElementById('test').firstChild.data)
// success!
test(this.responseXML.getElementById('test').firstChild.data);
else
test(null);
} else if (this.readyState == 4 && this.status != 200) {
// fetched the wrong page or network error...
test(null);
}
}
var client = new XMLHttpRequest();
client.onreadystatechange = handler;
client.open("GET", "unicorn.xml");
client.send();
If you just want to log a message to the server:
function log(message) {
var client = new XMLHttpRequest();
client.open("POST", "/log");
client.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
client.send(message);
}
Or if you want to check the status of a document on the server:
function fetchStatus(address) {
var client = new XMLHttpRequest();
client.onreadystatechange = function() {
// in case of network errors this might not give reliable results
if(this.readyState == 4)
returnStatus(this.status);
}
client.open("HEAD", address);
client.send();
}

Resources