I have an insert code inside of my tables in my Mobile Service in Azure, and I want to know if there is a better way to get the name of the current table my insert script is.
Today the code of my table "ClientTest1" look like this:
function insert(item, user, request) {
var payload = {
data: {
msg: "Nivel: " + item.Nivel
}
};
request.execute({
success: function() {
// If the insert succeeds, send a notification.
push.gcm.send("ClientTest1", payload, {
success: function(pushResponse) {
console.log("Sent push:", pushResponse, payload);
request.respond();
},
error: function (pushResponse) {
console.log("Error Sending push:", pushResponse);
request.respond(500, { error: pushResponse });
}
});
},
error: function(err) {
console.log("request.execute error", err)
request.respond();
}
});
}
I would like to have a code like this:
function insert(item, user, request) {
var payload = {
data: {
msg: "Nivel: " + item.Nivel
}
};
request.execute({
success: function() {
// If the insert succeeds, send a notification.
push.gcm.send(tables.current.name, payload, {
success: function(pushResponse) {
console.log("Sent push:", pushResponse, payload);
request.respond();
},
error: function (pushResponse) {
console.log("Error Sending push:", pushResponse);
request.respond(500, { error: pushResponse });
}
});
},
error: function(err) {
console.log("request.execute error", err)
request.respond();
}
});
}
I would like to not need hard code each name of the table in the "tag" parameter for my push.
Does anyone know a better way to do this? Thanks
You can use the current property of the tables global object, and that will return you the current table. So you can use this for the table name:
var tableName = tables.current.getTableName();
Related
I am trying to check if a user already exists in the database, I have managed to stop creating a user if one already exists with the same phone number , however I do not seem to get the error message displayed. I am not too sure why my error is not being handled correctly. Here is my code:
exports.usercreate = function (req, res)
{
users.create(req.body, function (err, result)
{
var phonenumber = req.body.phonenumber;
console.log(phonenumber);
if (phonenumber.length > 0)
{
res.status(200).json(
{
status: "error",
resCode: 400,
msg: 'cutomer added error'
});
}
else
{
res.status(200).json(
{
status: "success",
resCode: 200,
msg: "users Added Successfully",
});
}
else
{
console.log(error)
}
});
};
Getting error like customer added error. but records are inserted in couchbase
as #TommyBs mentioned, you are basically comparing an N1qlQuery object to whatever is coming on req.body.phonenumber
...
bucket.query(query, function(err, rows, meta) {
for (row in rows) {
if(row.phonenumber == req.body.phonenumber) {
res.status(500).json({status:"error", resCode: 500, msg:"users Already exist"});
}
}
}
up to now I have created my push notification service for my angular app using service worker, app manifest and fire-base.
I'm getting the server key and sender_id. I' m registering my service worker and subscribe to the push_messenger.
also I'm using google local server extension to host my server.
main.ts
Notification.requestPermission(function (status) {
console.log('Notification permission status:', status);
});
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('./service-worker.js', { scope: './' }).then(function (registration) {
// Registration was successful
console.log('ServiceWorker registration successful with scope: ', registration.scope);
console.log('registration: ', (registration));
navigator.serviceWorker.ready.then(reg => {
reg.pushManager.getSubscription().then(sub => {
if (sub == undefined) {
console.log('sub : ' + 'undefined');
navigator.serviceWorker.getRegistration().then((reg) => {
reg.pushManager.subscribe({
userVisibleOnly: true
}).then(sub => {
console.log('sub : ' + JSON.stringify(sub));
localStorage.setItem("sub", JSON.stringify(sub));
}, err => {
console.log('registration error occured: ' + err);
})
}, err => {
console.log('registration error occured: ' + err);
})
} else {
console.log('sub : ' + sub);
// subs = sub;
localStorage.setItem("sub", JSON.stringify(sub));
}
}, err => {
console.log('registration error occured: ' + err);
});
})
}).catch(function (err) {
// registration failed :(
console.log('ServiceWorker registration failed: ', err);
});
}
service-worker.js
self.addEventListener('notificationclose', function(e) {
var notification = e.notification;
var primaryKey = notification.data.primaryKey;
console.log('Closed notification: ' + primaryKey);
});
self.addEventListener('notificationclick', function(e) {
var notification = e.notification;
var primaryKey = notification.data.primaryKey;
var action = e.action;
if (action === 'close') {
notification.close();
} else {
clients.openWindow('samples/page' + primaryKey + '.html');
notification.close();
}
// TODO - close all notifications when one is clicked
});
self.addEventListener('push', function(e) {
var body;
if (e.data) {
body = e.data.text();
} else {
body = 'Push message no payload';
}
var options = {
body: body,
icon: 'images/notification-flat.png',
vibrate: [100, 50, 100],
data: {
dateOfArrival: Date.now(),
primaryKey: 1
},
actions: [
{action: 'explore', title: 'Explore this new world',
icon: 'images/checkmark.png'},
{action: 'close', title: "I don't want any of this",
icon: 'images/xmark.png'},
]
};
e.waitUntil(
self.registration.showNotification('Push Notification', options)
);
});
node server
var webPush = require('web-push');
var pushSubscription = {<subscription object>}
};
var payload = 'Sup Dude!';
var options = {
gcmAPIKey: *<server key>*,
TTL: 60,
};
webPush.sendNotification(
pushSubscription,
payload,
options
);
in the above main.ts I was able to get the subscription object when the app was initialized. and able to send the push notification at that moment. but when I open this same server IP from chrome I'm getting a different subscription object. also sometime I'm getting different subscription object using chrome.
the questions is How can I send push notifications for all users, since the subscription object is differ from time to time and browser to browser.
(cannot store all the data to a database which will be excessive amount of storage)
I think you should use FCM for this purpose. Where you can create a group and send notification to all of them. But even for creating group you would require deviceId for each device.
You can store all these id's with you in backend and send FCM web push to all.
https://firebase.google.com/docs/cloud-messaging/js/client
You can go through FCM documentation achieve this.
This is official firebase cloud-messaging documention very usefull...!
also checkout below link,
firebase cloud-messaging google
firebase cloud-messaging staring (subscribe this channel)
This is my working code for push notification token registration at client-side, may be work for you
<script>
messaging.requestPermission()
.then(function() {
console.log('Notification permission granted.');
// TODO(developer): Retrieve an Instance ID token for use with FCM.
messaging.getToken()
.then(function(currentToken) {
if (currentToken) {
console.log(currentToken);
settingTokenToServer(currentToken);
} else {
// Show permission request.
console.log('No Instance ID token available. Request permission to generate one.');
setTokenSentToServer(false);
refreshToken();
}
})
.catch(function(err) {
console.log('An error occurred while retrieving token............................... ', err);
});
})
.catch(function(err) {
console.log('Unable to get permission to notify.', err);
});
messaging.onTokenRefresh(function() {
messaging.getToken()
.then(function(refreshedToken) {
console.log('Token refreshed.');
// Indicate that the new Instance ID token has not yet been sent to the
// app server.
setTokenSentToServer(false);
// Send Instance ID token to app server.
sendTokenToServer(refreshedToken);
// ...
})
.catch(function(err) {
console.log('Unable to retrieve refreshed token ', err);
showToken('Unable to retrieve refreshed token ', err);
});
});
function settingTokenToServer(subscription_id) {
if (!isTokenSentToServer()) {
//setting token to FCM server
var ref = firebase.database().ref("notes/token");
ref.push({subscription_id}).then(function() {
console.log("Token saved Successfully..!");
}).catch(function(error) {
alert("Token not saved..." + error);
});
setTokenSentToServer(true);
} else {
console.log('Token already sent to server so won\'t send it again unless it changes');
}
}
function isTokenSentToServer() {
return window.localStorage.getItem('sentToServer') == 1;
}
function setTokenSentToServer(sent) {
window.localStorage.setItem('sentToServer', sent ? 1 : 0);
}
</script>
I have two modules. listingproperties and users' dashboard.
function propertyVerification(id){
listingproperty.propertyVerificationFlag = 1;
$http.put('/api/listingproperties/' + id, vm.ListingpropertiesService).success(function() {
listingproperty.propertyVerificationFlag = 1;
Notification.success('Property flagged successfully');
}).error(function() {
Notification.error('Property flagged successfully');
});
}
The above code is users' dashboard controller code. I'm trying to verify listed property by flag value to 1.
This code snippet runs perfectly but it is not reflecting on MongoDB database.
What is the wrong in above code?
Below is my server side code.
function ListingpropertiesService($resource) {
return $resource('/api/listingproperties/:listingpropertyId', {
listingpropertyId: '#_id'
}, {
update: {
method: 'PUT'
}
});
}
Also,
exports.update = function (req, res) {
var listingproperty = req.listingproperty;
listingproperty = _.extend(listingproperty, req.body);
listingproperty.save(function (err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(listingproperty);
}
});
};
Is this correct?
I am newbie with JavaScript, NodeJS and Express. I writing simple application which does the following
User makes a request.
Server makes mulitple rest calls and renders the response.
How can I make sure that all the calls are complete and I create an object that I can send to the user? I saw people said something about async.parallel. Is that the only way to go? Any examples would help.
You can use promises to run code in sequence.
Here is an example (a little scaled down) of a login functionality I made using promises.
In a module named LoginController I have placed this piece of code.
this.attemptLogin = function(body, res) {
var reason = "";
var user = null;
loginM.findUser(body.username)
.then(function(result) {
if (result.status) {
user = result.result[0];
return this.verifyPassword(body.password, result.result[0].Password);
} else {
reason = {status: false, message: "Incorrect username", result: null};
throw(reason);
}
})
.then(function(result) {
if (result.message) {
res.send({status: true, message: "Successfully logged in", result: user});
return;
} else {
reason = {status: false, message: "Incorrect password", result: null};
throw(reason);
}
}).catch(function(err) {
res.send(err);
});
}
And in another module named LoginModel (LoginM) I have placed this code
this.findUser = function(username, email) {
return new Promise(function (resolve, reject) {
pool.getConnection(function (err, connection) {
if (err) {
reject({status: false, message: err});
} else {
connection.query('select Id, Name, Email, Password from Users ' +
'where (Users.Name = ? OR Users.Email = ?) AND Removed = 0 LIMIT 1', [username, email], function (err, rows) {
connection.release();
if (!err) {
if(rows.length > 0) {
resolve({status: true, message: "Found user", result: rows});
}
else
resolve({status: false, message: null})
} else {
reject({status: false, message: err});
}
});
}
});
});
}
And a similar method for verifyPassword which also returns a promise.
Now, the things to note are that:
the code inside every then is run asynchronously
the then parts are executed in order, i.e, you won´t enter the next then until you have returned something from the previous then
whatever you resolve from the methods returning promises (findUser and verifyPassword) are passed as the variable named result in .then(function(result)
I am using Parse Server on AWS and mLab with great success, except for my Cloud Code. The main issue is surrounding my previous code for Create OR Update an object. I used to do this by querying for a user pointer on the Favourites class. If a row contains a user pointer then I need to update its content, if it doesn't exist a row needs to be created.
Old Parse.com Code
Parse.Cloud.define("saveFavourites", function(request, response) {
console.log(request.params.favourites);
var Favourites = Parse.Object.extend("Favourites");
var query = new Parse.Query("Favourites");
query.equalTo('user', request.user);
query.first({
success: function(results) {
console.log(JSON.stringify(results));
console.log(results)
if (results === undefined) {
var favourites = new Favourites();
favourites.save({
user: request.user,
favourites: request.params.favourites
}, {
success: function(favourites) {
// The object was saved successfully.
},
error: function(favourites, error) {
// The save failed.
// error is a Parse.Error with an error code and message.
}
});
} else {
results.set("favourites", request.params.favourites);
results.set("userId", request.user.id);
results.save();
}
response.success(results);
},
error: function(error) {
error.message("favourites lookup failed");
}
});
});
New Parse Server Code
Parse.Cloud.define("saveFavourites", function(request, response) {
console.log('user is : ' + JSON.stringify(request.user));
var Favourites = Parse.Object.extend("Favourites");
var query = new Parse.Query("Favourites");
query.equalTo("user", request.user);
query.first({
useMasterKey: true
}, {
success: function(results) {
if (results && results.length > 0) {
console.log('running found');
favourites.set("favourites", request.params.favourites);
favourites.set("userId", request.user.id);
favourites.save();
response.success();
} else {
var favourites = new Favourites();
favourites.set("user", request.user);
favourites.set("favourites", request.params.favourites);
favourites.set("userId", request.user.id);
favourites.save();
response.success();
}
},
error: function(error) {
console.log(error.message);
}
});
});
Do not response unless callback finished. Set response.error on each Parse requests error.
Parse.Cloud.define("saveFavourites", function(request, response) {
console.log(request.params.favourites);
var Favourites = Parse.Object.extend("Favourites");
var query = new Parse.Query("Favourites");
query.equalTo('user', request.user);
query.first({
//is this query need masterKey?
useMasterKey: true,
success: function(results) {
console.log(JSON.stringify(results));
console.log(results)
if (results === undefined) {
var favourites = new Favourites();
favourites.save({
user: request.user,
favourites: request.params.favourites
}, {
success: function(favourites) {
// The object was saved successfully.
response.success(results);
},
error: function(favourites, error) {
// The save failed.
// error is a Parse.Error with an error code and message.
response.error(error);
}
});
} else {
results.set("favourites", request.params.favourites);
results.set("userId", request.user.id);
results.save(null, { useMasterKey: true }).then(response.success, response.error);
}
},
error: function(error) {
error.message("favourites lookup failed");
response.error(error);
}
});
});