Cloud code has what's called beforeSave
and afterSave
triggers. beforeSave
is what you need here.
A beforeSave trigger contains all of the new data (note: none of the old) and you can check object.dirty("key");
to see if that field has changed. You also don't have to do any checks for this specific case.
Parse.Cloud.beforeSave("ClassName", function(request, response) {
var object = request.params.object;
if( object.get("team_c_score") < 0 ) object.set("team_c_score", 0);
response.success();
});
Some notes: If you return response.error()
, the save will note go through, so this is how you validate input. A field contains illegal characters, or data you didn't expect? Throw an error so it doesn't get saved.
You also shouldn't put anything in the success response. That will cause an error.
This function gets called automatically if it exists, and will always be called. You can't skip it. Even if you update data from the dashboard, this gets called. Same with afterSave
triggers, although modifying an object in those will not do anything unless you save it.
This should go in your main.js, or a file required by main.js. I have a folder for each of my custom classes. Each class has a classNameController.js
, which contains the beforeSave, afterSave, initializer, and any cloud code functions relating directly to that object.
Main requires each of these controllers, which opens up all of the Parse.Cloud endpoints to the server.
beforeSave and afterSave triggers on hosted Parse.com had a 3 second timeout. I am not aware if there is a timeout for parse-server. I've never tested it. But don't have more than a couple server calls to be safe.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…