Parse open source server sending push using cloud - javascript

I am now on the new parse open source server and I am trying to send a push notification using the cloud main.js. I sent a push using curl but can not in the .js file. Here is the code I have.
Parse.Cloud.define("PushNotification", function(request, response) {
console.log('sending push');
var Installation = new Parse.Query(Parse.Installation);
console.log(Installation);
Parse.Push.send({
where: Installation,
data: {
alert: request.params.Message,
badge: 0,
sound: 'default'
}
}, {
useMasterKey: true,
success: function() {
// Push sent!
console.log('Push sent');
response.success('success');
},
error: function(error) {
// There was a problem :(
response.error("Error push did not send");
console.log('sending push error: '+error);
}
});
It says that it sent but It did not. If any one could help that would be great!

I got a answer on github and I hope this will help any one else with the same problem. Here is the code I used.
Parse.Cloud.define("PushNotification", function(request, response) {
console.log('sending push');
var Installation = new Parse.Query(Parse.Installation);
console.log(Installation);
Parse.Push.send({
useMasterKey: true,
where: Installation,
data: {
//or you can put "" to not do a custom alert
alert: request.params.Message,
badge: 0,
sound: 'default'
}
}, {
useMasterKey: true,
success: function() {
// Push sent!
console.log('Push sent');
response.success('success');
},
error: function(error){
console.error(error);
}
});
});

Related

Why have error 'Internal Server Error' at create authorization request header in Hawk?

I am trying to encrypt my request data using Hawk on node.I use client code.
But when I create the request header,have an error:
{ Error: Invalid credentials
at Object.exports.header (E:\work\spinarak\node_modules\#hapi\hawk\lib\client.js:69:15)
at _push (E:\work\spinarak\Task\getResult.js:237:30)
at _pushByApps (E:\work\spinarak\Task\getResult.js:222:4)
at process._tickCallback (internal/process/next_tick.js:68:7)
data: null,
isBoom: true,
isServer: true,
output:
{ statusCode: 500,
payload:
{ statusCode: 500,
error: 'Internal Server Error',
message: 'An internal server error occurred' },
headers: {} },
reformat: [Function],
typeof: [Function: Error] }
There is my code:
const Hawk = require('#hapi/hawk');
const Request = require('request');
async function _push(userinfo, content) {
try {
let credentials = {
key: userinfo['secret'],
algorithm: 'sha256',
user: userinfo['id']
}
// The error at function that locates the following line
let { header } = Hawk.client.header(userinfo['webhook'], 'POST', {
credentials: credentials,
payload: content
});
} catch (e) {
console.log(e);
}
}
I have been looking online for a long time and have not found a solution. Why do I get an error when I create a request header? I have not officially sent a request yet.
Oh,I am very careless,I find error keyword at my code.
from:
let credentials = {
key: userinfo['secret'],
algorithm: 'sha256',
user: userinfo['id']
}
to:
let credentials = {
key: userinfo['secret'],
algorithm: 'sha256',
id: userinfo['id']
}
It can run.
This issue is not worth learning((

Parse Cloud Code function get deviceToken By username

I am kinda new to the whole cloud code and I am having a bit of trouble fetching some data.
So what I basically want is a function that by giving it a 'username' that is located in the Parse.User database, it will return the user's objectId which I will then use to locate the user's session in the Parse.Session, from there I will get the installationId which I will then use in the Parse.Installation to get the device token.
Note: I have written a function that keeps only 1 session active per user.
My issue:
The Query of Parse.Session has a result which only contains 3 objects, and the installationId is not included,therefor I can not find out what is the installation id and then use it to search the Parse.Installation to get the device token.
input example:
Input:
{"from":"user1",
"msg":"hello",
"title":"Whatever title",
"to":"user2"}
Here is the existing code I currently have which doesn't work.
Parse.Cloud.define('gcm', function(request,response){
var username = request.params.to;
console.log("usr "+username);
var userQuery = new Parse.Query(Parse.User);
userQuery.equalTo('username', username);
userQuery.find({
success: function(results){
var objectId = results[0].id;
console.log("obj id "+objectId);
var user = new Parse.User();
//Set your id to desired user object id
user.id = objectId;
var sessionQuery = new Parse.Query(Parse.Object.extend('Session'));
sessionQuery.include(user);
sessionQuery.find({
success: function(results1){
console.log("result classname type: "+typeof(results1[0]));
var installId = results1[0].installationId ; //here is the value which I want from the result, but the object is type of _Session which does not have installationId.
console.log("inst id "+installId);
var InstallationQuery = new Parse.Query(Parse.Installation);
InstallationQuery.equalTo('installationId',installId);
InstallationQuery.find({
success: function(results2){
var deviceToken = results2[0].get("deviceToken");
console.log("token "+deviceToken);
Parse.Cloud.httpRequest({
method: "POST",
url: " https://gcm-http.googleapis.com/gcm/send",
headers: {'Authorization' : 'key=AIzaSyDj4ISkLW7CzAQEQEhTsq3JYZK5OP8tSzY',
'Content-Type' : 'application/json'},
body: {
"data":
{
"title": request.params.title,
"msg": request.params.msg
},
"to" : deviceToken
},
success: function(httpResponse) {
response.success("Message Sent!");
console.log(httpResponse.text);
},
error: function(httpResponse) {
response.error("Error, Something went wrong.");
console.log("error 4: " + httpResponse.status);
}
});
},
error: function(error) {
//error
console.log("error 3: " + error);
}
});
},
error: function(error) {
//error
console.log("error 2: " + error);
}
});
},
error: function(error) {
//error
console.log("error 1: " + error);
}
});
});

jQuery ignoring status code from Express

I'm making an application where a form has to be validated with AJAX. Nothing too fancy. When a form submit is triggered I'm posting to a URL on a Node.js server and routing with Express. If the data does not pass all of the validation requirements, I'm sending a status code of 400, like so:
app.post('/create', checkAuth, function (req,res)
{
var errors = new Errors();
if (req.body['game-name'].length < 3 || req.body['game-name'].length > 15)
{
res.send({
msg: 'Game name must be between 3 and 15 characters.'
}).status(500).end();
}
else
{
GameModel.find({id: req.body.roomname}, function (err,result)
{
if (result.length !== 0)
{
errors.add('A game with that name already exists.');
}
//Some more validation
if (errors.get().length > 0)
{
res.status(400).send({
msg: errors.get()[0]
}).end();
return;
}
else
{
var data = new GameModel({
roomname: req.body['roomname'],
owner: req.session.user,
id: req.body['roomname'].toLowerCase(),
config: {
rounds: req.body['rounds'],
timeLimit: req.body['time-limit'],
password: req.body['password'],
maxplayers: req.body['players'],
words: words
},
finished: false,
members:
[
req.session.user
]
});
data.save(function (err, game)
{
if (err) {
console.log(err);
res.send({
msg: 'Something funky happened with our servers.'
}).status(500).end();
}
else
{
res.send({
msg: 'All good!'
}).status(200).end();
}
});
}
});
}
});
On the client side, I have the following code:
$.ajax({
type: "POST",
url: "/someURL",
data: $("form").serialize(),
statusCode:
{
200: function (data)
{
//All good.
},
400: function (data)
{
//Uh oh, an error.
}
}
});
Strangely, jQuery is calling the 200 function whenever I send a 400 error. I believe this is because I'm sending an object along with the status code. How can I resolve this?
First guess is you need a return; statement in your express code inside that if block. I bet the error code is running then the success code and the last values for the statusCode/body are being sent to the browser.

Parse Cloud Code beforeSave not running on update

I have defined a Parse Cloud Code function for beforeSave below.
Parse.Cloud.beforeSave(Parse.User, function(request, response) {
Parse.Cloud.useMasterKey();
var publicACL = new Parse.ACL();
publicACL.setPublicReadAccess(true);
publicACL.setPublicWriteAccess(true);
request.object.setACL(publicACL);
response.success();
});
This code runs correctly whenever I save a new Parse.User. However, when I try to update a pre-existing Parse.User, the code does not execute. Any thoughts? Below is the code I am using to update my user.
function updateStudentTypes(id, studentType, chkBox) {
var query = new Parse.Query(Parse.User);
query.get(id, {
success: function(user) {
var typeList = user.get("studentType");
if(!chkBox.checked)
typeList = removeStudentType(typeList, studentType);
else
typeList = addStudentType(typeList, studentType);
user.set("studentType", typeList);
user.save(null, {
success: function(user) {
//alert('New object created with objectId: ' + user.id);
},
error: function(user, error) {
alert('Failed to update user: ' + error.message);
}
});
},
error: function(object, error) {
alert("Error querying user: " + error);
}
});
}
Add this to the beginning of your updateStudent method:
Parse.Cloud.useMasterKey();
Edit: I thought your code was cloud code, not client side javascript.

stripe params using javascript

I'm using Stripe in conjunction with Parse Cloud Code.
I can pass the token ID and the customer email, but I need their name too. Stripe doesn't have any straight JS docs so it's difficult to understand. How can I pass the name?
Here's my client side code:
Parse.Cloud.run('createCustomer',{
token: token.id,
email: token.email,
}, {
// Success handler
success: function(message) {
alert('Success: ' + message);
},
// Error handler
error: function(message) {
alert('Error: ' + message);
}
})
and the backend Cloud Code:
Parse.Cloud.define("createCustomer", function(request, response) {
console.log(request.params)
Stripe.Customers.create({
account_balance: 0,
email: request.params.email,
description: "stripe customer",
metadata: {
userId: request.params.objectId, // e.g PFUser object ID
createWithCard: true
}
}, {
success: function(httpResponse) {
response.success(name + userId); // return customerId
},
error: function(httpResponse) {
console.log(httpResponse");
response.error("Cannot create a new customer.");
}
});
});
This works for me. And yes, there is little documentation on this. :)
Parse.Cloud.define("createCustomer", function(request, response) {
Stripe.Customers.create({
card: request.params.cardToken, // the token id should be sent from the client
// account_balance: 0,
email: request.params.email,
description: 'new stripe user',
metadata: {
name: request.params.name
}
},
{
success: function(httpResponse) {
response.success(httpResponse); // return customerId
},
error: function(httpResponse) {
console.log(httpResponse);
response.error(httpResponse);
}
});
});

Categories

Resources