I’ve recently started playing with the Parse.com JS api for building apps. It’s a pretty simple API and I love how easy it is to create and add new data to each object. The one thing I kept running into was having to check if an object already existed on the server. The save() function in the API simply creates the object unless you’ve already retrieved it. Seeing as often times I don’t want to remember to check, and the objects will pretty much always have the unique column, I wrote a little class to allow me to forget the unique constraint.

The code is sitting on github as a single .js file

Basically, if an object has a column that needs to be unique, just specify it when the class is declared.

var myUniqueClass = Parse.UniqueObject("uniqueClass", {uniqueKey:"keyColumnName"});
var obj = new myUniqueClass();
obj.keyColumnName = 'uniqueValue';
obj.saveUnique();

The saveUnique function does much of the heavy lifting and checks prior to calling the Parse.Object.save. Of course this isn’t always the easiest way, if there was an array of objects, it’s possible to use the saveAllUnique function to save all in one go. It checks each type of objects for their unique column and queries each before saving.

Of course the best laid plans can go astray. The above simply checks before attempting to save, but that means if there are multiple processes trying to save, a few requests may get thru. Having a Parse.Cloud.beforeSave function in place means any that get thru to the server will get one last check before it gets saved as a duplicate.

Go ahead, give it a try.