简体   繁体   中英

Parse Server [Cloud Code]: Handle concurrent requests

Let's say I have some Cloud Code on Parse Server:

Parse.Cloud.beforeSave("UserProfiles", function(request, response) {
    const query = new Parse.Query("UserProfiles");
    query.equalTo("user", request.user);
    query.count({
        success: function(count) {
            if(count == 0)
                response.success();
            else 
                response.error("only one profile is allowed");  
            },
        error: function(error) {
                response.error(error.message);
            }
    });
});

It works fine unless concurrency happen. If two or more requests at the same time execute creation of new classes then this code wouldn't check that profile under pointer field user already exist.

My question is how properly handle concurrent requests in beforeSave trigger?

You can start by ensuring your UserProfile collection has an index by user in your database. You'll have to figure out how to do this yourself based on your database provider. This will speed up your queries.

Otherwise, you don't have a lot of options here. I'd say the best bet is to put the code that creates the UserProfile object inside the beforeSave trigger for Parse.User, inside a block that checks for .isNew(), so it only gets created when a new user is created. Any other solution I can think of would have similar concurrency issues.

If you want to use BeforeSave() you can set the the UserProfiles pointer to the user object before saving like so:

Parse.Cloud.beforeSave(Parse.User, function(request, respone){
    // only apply to new users
      if(request.object.isNew()){
        var UserProfile = new Parse.Object.extend("UserProfiles");
        var userProfile = new UserProfile();
        return userProfile.save().then(function(savedUserProfile){
          request.object.set("key", savedUserProfile);
          return request.object.save();
        });
      }
});

you can achive that by either Cloud jobs , beforeSave or afterSave callbacks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM