Search code examples
iosswiftparse-platformparse-cloud-code

How do I implement the cloud code?


I am very new to cloud code, and I am having trouble. I have already referred to this How to prevent duplicate entry on parse? and I am trying to do the same exact thing. I am trying to prevent a duplicate entry in my class. I keep getting the error in the cloud code "Song already exists" even though the class is empty.

This is the cloud code. I am confused on what the querySongs.equalTo("title", newEntrySong.get("title")); is doing. Is it looking for the actual word title? becuase I need it to find a specific title.

Parse.Cloud.beforeSave("Pointer", function(request, response) {

var newEntrySong = request.object;

var querySongs = new Parse.Query("Pointer");
querySongs.equalTo("title", newEntrySong.get("title"));
//querySongs.equalTo("description", newEntrySong.get("description"));

// this could be a sort of signature for your song, to make more unique     (skipping spaces and new lines for example)
// querySongs.equalTo("md5Title", newEntrySong.get("md5Title"));
querySongs.first({
  success: function(temp) {
    response.error({errorCode:123,errorMsg:"Song already exist!"});          
},
error: function(error) {
  response.success();
          }
    });
 });

Below is my code for finding duplicates in the class, but it doesn't work well. Do I need to replace the whole thing? or get rid of it? since I have the cloud code

 func getNowPlayingItem() {

    print("entered function")
    NSNotificationCenter.defaultCenter().removeObserver(self)

    if  let nowPlaying = musicPlayer.nowPlayingItem  {
        let title = nowPlaying[MPMediaItemPropertyTitle] as? String
        let artisttest = nowPlaying[MPMediaItemPropertyTitle]
        if let artist = nowPlaying[MPMediaItemPropertyArtist] as? String{

            let objectPointer = PFObject(className: "Pointer")
            let object = PFObject(className: "MasterSongs")


            let query = PFQuery(className: "Pointer")
            query.findObjectsInBackgroundWithBlock({
                (objects: [AnyObject]?, error: NSError?) -> Void in
                var objectIDs = objects as! [PFObject]

                for i in 0...objectIDs.count-1{
                    self.Parsearray.append((objectIDs[i].valueForKey("title") as? String)!)

                }


                if self.Parsearray.contains(title!){
                    print("already in db")
                       NSNotificationCenter.defaultCenter().addObserver(self, selector: "getNowPlayingItem", name: MPMusicPlayerControllerNowPlayingItemDidChangeNotification, object: nil)
                }else{
                    objectPointer["title"] = title
                    objectPointer["user"] = PFUser.currentUser()
                    objectPointer["artist"] = artist
                    print("about to save with artist")
                    objectPointer.saveInBackgroundWithBlock({ (success: Bool, error: NSError?) -> Void in
                        if(error != nil){
                            print(error)
                        }else{
                             NSNotificationCenter.defaultCenter().addObserver(self, selector: "getNowPlayingItem", name: MPMusicPlayerControllerNowPlayingItemDidChangeNotification, object: nil)
                            print("saved")
                        }

                    })



                }

            })




        }else{


            let objectPointer = PFObject(className: "Pointer")


            let query = PFQuery(className: "Pointer")
            query.findObjectsInBackgroundWithBlock({
                (objects: [AnyObject]?, error: NSError?) -> Void in
                var objectIDs = objects as! [PFObject]

                for i in 0...objectIDs.count-1{
                    self.Parsearray.append((objectIDs[i].valueForKey("title") as? String)!)

                    // print(self.Parsearray)
                }


                if self.Parsearray.contains(title!){
                    print("already in db with no artist")
                       NSNotificationCenter.defaultCenter().addObserver(self, selector: "getNowPlayingItem", name: MPMusicPlayerControllerNowPlayingItemDidChangeNotification, object: nil)
                }else{
                    objectPointer["title"] = title
                    objectPointer["user"] = PFUser.currentUser()
                    objectPointer["artist"] = "No artist found :("
                    print("about to save")
                        objectPointer.saveInBackgroundWithBlock({ (success: Bool, error: NSError?) -> Void in

                            if(error != nil){
                                print(error)
                            }else{
                                NSNotificationCenter.defaultCenter().addObserver(self, selector: "getNowPlayingItem", name: MPMusicPlayerControllerNowPlayingItemDidChangeNotification, object: nil)
                                print("saved")
                            }

                    })


                }

            })





        }


        }

}

Solution

  • The OP's beforeSave function fails to check whether or not the query identified a duplicate. As written, it always reports a duplicate, but can be fixed simply...

    var newEntrySong = request.object;
    var querySongs = new Parse.Query("Pointer");
    querySongs.equalTo("title", newEntrySong.get("title"));
    // whatever else you want to do that defines a duplicate
    
    querySongs.first().then(function(result) {
        // this is the check the code was missing
        if (result) {
            response.error({errorCode:123,errorMsg:"Song already exist!"}); 
        } else {
            response.success();
        }
    }, function(error) {
        response.error(error);
    })
    

    If you have this working to prevent duplicates, there's no need for the client code to do the same.