I'm looking a method to automatically updating data using cloud code.
Let say I have a class Table.
inside of it, I have three column : firstname, lastname, and fullname.
Currently, I only have firstname and lastname data only. Column fullname is still empty.
Is it possible to fill the fullname automatically, by just combining the value in firstname and lastname?
Thank you,
#RoyH is 100% right to maintain your computed column as new objects are created. To do an initial migration, try a cloud function, like:
var _ = require("underscore");
Parse.Cloud.define("addFullnames", function(request, response) {
// useMasterKey if the calling user doesn't have permissions read or write to Table
Parse.Cloud.useMasterKey();
var query = new Parse.Query("Table");
// we'll call tables > 1000 an 'advanced topic'
query.limit = 1000;
query.find().then(function(results) {
_.each(results, function(result) {
var firstname = result.get("firstname") || "";
var lastname = result.get("lastname") || "";
result.set("fullname", (firstname + " " + lastname).trim());
});
return Parse.Object.saveAll(results);
}).then(function(results) {
response.success(results);
}, function(error) {
response.error(error);
});
});
Call it like this:
curl -X POST \
-H "X-Parse-Application-Id: your_app_id_here" \
-H "X-Parse-REST-API-Key: your_rest_key_here" \
-H "Content-Type: application/json" \
https://api.parse.com/1/functions/addFullnames
You can factor out the code inside _.each() to make a function that's called here and by a beforeSave hook to maintain the data as it is added.
Yes, you can either just put a value for "fullname" when you are saving "firstname" and "lastname" (before cloudcode). Alternately, you can use the before save/ after save cloudcode functions to insert a value into that column:
Take a look at:
https://parse.com/docs/cloud_code_guide#webhooks-beforeSave
https://parse.com/docs/cloud_code_guide#webhooks-afterSave
Related
I'm using parse server cloud function to query a class using master key.
The class object has the ACL to allow read only to the user who created the object.
The query gives me zero results.
But as soon as I change ACL on my test object to public read/write, the cloud function query gives me the desired object.
As far as I know, using master key I should have got the objects on query.
Anyone knows what the issue here is?
const mQuery = new Parse.Query('MyClass');
mQuery.equalTo('objectId', mObjectId);
const result = await mQuery.first(null, {useMasterKey : true});
console.log("mQuery",mQuery);
console.log("result",result);
if (!result) {
throw new Error('no data found.');
}
Here the result is logged as undefined. Once the object is made public, the result is the public object. I'm using parse server 3.x.
first only takes a single argument, so re-write to:
const result = await mQuery.first({ useMasterKey : true });
Using Parse Server version equal to 3.x, you can do something like:
Parse.Cloud.define("TestCloudCode", async (request) => {
const query = new Parse.Query(Parse.User);
const objectId = request.params.objectId;
const results = await query.get(objectId, {useMasterKey:true});
return results;
});
To call it:
curl -X POST \
-H "X-Parse-Application-Id: ${APPLICATION_ID}" \
-H "X-Parse-REST-API-Key: ${REST_API_KEY}" \
-H "Content-Type: application/json" \
-d '{ "objectId": "${Replace_with_your_objectId}" }' \
https://parseapi.back4app.com/functions/TestCloudCode
I'm writing some client-side customisations for a model driven app and I need to update an entry in an N:N relationship. I have been following the documentation here. I can read from the relationship table, but trying to update an entry or create a new entry is failing.
The N:N relationship is between a custom entity new_lastask and the built-in systemuser entity. The name generated for the N:N relationship is new_new_lastask_systemuser. I have managed to create and update other records, and I understand that you need to use the Schema name with the exact casing, not the name of the field and also the #odata.bind syntax when updating a lookup field, but I can't figure out what the name of the field should be.
The example code below tries to find a N:N record with a given user and switch it for another user, I have given an example with the updateRecord method, but I have tried with createRecord too and I get the same error.
// taskId is the Guid of the custom task entity, and userId is the guid of the user
var query = "?$filter=new_lastaskid eq " + taskId;
Xrm.WebApi.retrieveMultipleRecords("new_new_lastask_systemuser", query).then(
function success(result) {
for (var i = 0; i < result.entities.length; i++) {
if (result.entities[i].systemuserid===oldUserId) {
// found the offering user, replace them
var data = {
"systemuserid#odata.bind": "/systemusers" + newUserId
}
// try to just change the value of the user attached to the N:N record
Xrm.WebApi.updateRecord(tableName, result.entities[i].new_new_lastask_systemuserid, data).then(
function success(result) {
console.log("Successfully updated");
// perform operations on record update
},
function (error) {
console.log(error.message);
// An error occurred while validating input parameters: Microsoft.OData.ODataException:
// An undeclared property 'systemuserid' which only has property annotations in the payload...
}
);
}
}
},
function (error) {
console.log(error.message);
// handle error conditions
}
);
This is the same error I was getting when trying to update any lookup field on my entity when I was trying to use the name instead of the Schema Name, so I thought it might be related to the capitalisation of the field, so I have tried many variations (SystemUserId, User, SystemUser, systemuser, user, userid) and nothing works.
What should the Schema name be of the lookup field on my N:N table, or am I going about handling modifications to these the wrong way via this API?
I just could not get it to work via the Client API, so i just made the call to the web api using fetch, following the document from the 8.2 api here:
fetch('https://yoururl.crm.dynamics.com/api/data/v9.0/new_lastasks' + taskId + "/new_new_lastask_licensee/$ref", {
method: 'post',
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
"OData-MaxVersion": "4.0",
"OData-Version": "4.0"
},
body: JSON.stringify(
{"#odata.id": "https://yoururl.crm.dynamics.com/api/data/v9.0/systemusers" + currentUser }
)
}).then(function(response) {
console.log(response)
})
If a post in my Parse database is liked, I want to send a push to the author via cloud code.
To be able to send pushes to specific users, all installations store the objectId of the current user. To find the author of the liked post, I use the query
var userWhosePostWasLikedQuery = new Parse.Query(Parse.Installation);
userWhosePostWasLikedQuery.equalTo(kClassInstallationKeyCurrentUserId, userWhosePostWasLiked.id);
This works fine: A single push is sent to the author.
Now I want to send this push only if the author has such pushes enabled. Thus each user stores a push settings array with enable flags for different pushes.
I use now another query for all users who have such pushes enabled:
const User = Parse.Object.extend(kClassUser);
var pushEnabledUserQuery = new Parse.Query(User);
pushEnabledUserQuery.equalTo(kClassUserKeyPushSettings, kPushNotificationTypePostLiked);
This query correctly returns all users who have such pushes enabled.
Eventually, I want to constrain the query for installations with the author as current user, by this query for users who have pushes enabled. This is done in the following way:
var userWhosePostWasLikedQuery = new Parse.Query(Parse.Installation);
userWhosePostWasLikedQuery.equalTo(kClassInstallationKeyCurrentUserId, userWhosePostWasLiked.id);
userWhosePostWasLikedQuery.matchesKeyInQuery(kClassInstallationKeyCurrentUserId, kPFObjectId, pushEnabledUserQuery);
Since the old query without the 3rd line returns 1 user, the new query with the additional constraint (matchesKeyInQuery) should return the same user, since the author has pushes enabled.
But it returns 2 users, the author and another user who liked the post.
To my understanding, this looks like a Parse bug, since all constraints to a query are ANDed.
Any ideas, maybe for a workaround?
your var "kPFObjectId" should be change to "user".
the default parse Installation come with the pointer named "user" and not "kPFObjectId".
I can tell you that Im using the same method ("matchesKeyInQuery") and it is working well:
Parse.Cloud.define("sendPushForChat", function(request, response) {
var userId = request.params.userId;
var groupId = request.params.groupId;
var query = new Parse.Query('RecentActivity');
query.equalTo('groupId',groupId);
query.include('user');
query.notEqualTo('user', {__type: "Pointer", className: "_User", objectId: userId});
var queryInstallation = new Parse.Query(Parse.Installation);
queryInstallation.matchesKeyInQuery('user', 'user', query);
var message = request.params.messageContent;
Parse.Push.send({
where: queryInstallation,
data: {
alert: message,
badge: "Increment",
title: "מה נשמע?"
}
}, {
success: function() {
console.log("Push for chat was successful");
response.success('Push for chat was successful');
},
error: function(error) {
console.error(error);
response.error('error');
},
useMasterKey:true,
});
})
I am trying to do a little script on Cloud Code that sends an email whenever an object of type Reservas is created. This email needs to contain the information about the user that created this object. I know that using a related field would be better, but this option is not possible at the moment.
What I thought of doing is a query using the email from the Reservas object and the email property from the user but I can't seem to get to the line console.log("--> Usuario encontrado")
Here's what I tried to do:
Parse.Cloud.afterSave("Reservas", function(request) {
var assunto = "Reserva App Criada - ";
var conteudo = "Reserva App CRIADA\n"
try {
query = new Parse.Query(Parse.User);
query.equalTo("email", request.object.get("email"));
query.find({
sucess: function(usuario) {
console.log("--> Usuario encontrado")
mandarEmail(conteudo, assunto, request, usuario)
}, error: function(error) {
console.log("--> Usuario não encontrado")
emailErro(request, error);
}
})
} catch(err) {
console.log("--> Erro:" + err);
}
});
It was just a silly typo. I wrote sucess instead of success
I try to get the current user with cloud code.
var verificationCode = (Math.floor(Math.random()*900000)) + 100000 ;
var user = Parse.User.current();
user.set("phoneVerificationCode", verificationCode);
user.save();
when I called the method in Xcode.
PFCloud.callFunctionInBackground("sendVerificationCode", withParameters:["phoneNumber": phoneNumberText])
it send but I get this error:
Error: TypeError: Cannot call method 'set' of null
what should I do?
The current user is available, if they are logged in. The user is passed in via the request object to your cloud function.
Parse.Cloud.define("myFunction", function(request, response) {
var verificationCode = (Math.floor(Math.random()*900000)) + 100000 ;
var user = request.user();
user.set("phoneVerificationCode", verificationCode);
user.save();
});
If you are logged in (have active session) then you can do following:
Parse.Cloud.define('get-current-user', async (request) => {
return request.user;
});
Once you call above end-point, it will return current user.
curl -X POST \
-H "X-Parse-Application-Id: test-app" \
-H "Content-Type: application/json" \
-H "X-Parse-Session-Token: r:8729a7099f8c3d87979f4dfd2e5b59df" \
http://localhost:1337/functions/get-current-user