Search code examples
javascriptangularjsparse-platformparse-cloud-code

Parse.com beforesave wont work


I have an AngularJS app where people can comment on articles - like in a blog. The form works nicely, but I want to validate the input in cloud code before it is saved to parse.

My problem is, that no matter what I do, seemingly, input is saved - even with undefined values.

Parse.Cloud.define("saveComment", function(request, response) {
    "use strict";
    var Comment = Parse.Object.extend("Comment");
    var comment = new Comment();
    comment.set("commentName", request.params.commentName);
    comment.set("commentEmail", request.params.commentEmail);
    comment.set("commentWebsite", request.params.commentWebsite);
    comment.set("commentContent", request.params.commentContent);
    comment.set("commentFor", {__type:"Pointer", className:"Article", objectId:request.params.commentFor});
    comment.set("commentApproved", false); // need to add a check for Commenter status

    /* ADD PERMISSIONS */
    var acl = new Parse.ACL();
    acl.setPublicReadAccess(true);
    acl.setPublicWriteAccess(false);
    comment.setACL(acl);

    Parse.Cloud.useMasterKey();
    comment.save().then(function(comment) {
        response.success(comment);
    }, function(error) {
        // error handling
        response.error(error);
    });
});

Parse.Cloud.beforeSave("saveComment", function(request, response) {
    "use strict";

    var regexEmail = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2-10})?)$/i;

    if (request.object.get("commentTest").length === 0) {
        response.error(100);
    }
    else if (request.object.get("commentName").length === 0) {
        response.error(200);
    }
    else if (!regexEmail.test(request.object.get("commentEmail"))) {
        response.error(300);
    }
    else {
        response.success();
    }
});

In the above example I've also tried var === undefined and loads of other variations of simple input validation, along with regex as you can see.

The problem is, no matter what I type into my input fields in the form, it gets saved - it's as if the beforeSave function is never triggered.

Any help would be appreciated.


Solution

  • Found the mistake myself...

    Turns out, beforeSave() needs the object as first argument, not the function it's connected to:

    Parse.Cloud.beforeSave("Comment", function(request, response) {
        // stuff
    });
    

    As explained here: https://parse.com/docs/cloudcode/guide#cloud-code-beforesave-triggers