Skip to content

Commit 4638537

Browse files
committed
feat(Object): implement save with options.query
1 parent 505d7af commit 4638537

File tree

3 files changed

+37
-4
lines changed

3 files changed

+37
-4
lines changed

src/object.js

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -832,7 +832,9 @@ module.exports = function(AV) {
832832
* }, function(error) {
833833
* // The save failed. Error is an instance of AV.Error.
834834
* });</pre>
835-
*
835+
* @param {Object} options Optional Backbone-like options object to be passed in to set.
836+
* @param {Boolean} options.fetchWhenSave fetch and update object after save succeeded
837+
* @param {AV.Query} options.query Save object only when it matches the query
836838
* @return {AV.Promise} A promise that is fulfilled when the save
837839
* completes.
838840
* @see AV.Error
@@ -918,6 +920,18 @@ module.exports = function(AV) {
918920
json._fetchWhenSave = true;
919921
}
920922

923+
if (options.fetchWhenSave) {
924+
json._fetchWhenSave = true;
925+
}
926+
if (options.query) {
927+
try {
928+
json._where = options.query.toJSON().where;
929+
} catch (e) {
930+
var error = new Error('options.query is not an AV.Query');
931+
return AV.Promise.error(error)._thenRunCallbacks(options, model);
932+
}
933+
}
934+
921935
var route = "classes";
922936
var className = model.className;
923937
if (model.className === "_User" && !model.id) {

src/utils.js

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -378,9 +378,15 @@ const init = (AV) => {
378378
if (objectId) {
379379
apiURL += "/" + objectId;
380380
}
381-
if ((route ==='users' || route === 'classes') && dataObject && dataObject._fetchWhenSave){
382-
delete dataObject._fetchWhenSave;
383-
apiURL += '?new=true';
381+
if ((route ==='users' || route === 'classes') && dataObject){
382+
if (dataObject._fetchWhenSave) {
383+
delete dataObject._fetchWhenSave;
384+
apiURL += '?new=true';
385+
}
386+
if (dataObject._where) {
387+
apiURL += ('?where=' + encodeURIComponent(JSON.stringify(dataObject._where)));
388+
delete dataObject._where;
389+
}
384390
}
385391

386392
dataObject = _.clone(dataObject || {});

test/object.js

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,19 @@ describe('Objects', function(){
119119
}
120120
});
121121
});
122+
it("should not update prop when query not match",function(done){
123+
gameScore.set("score", 10000);
124+
gameScore.save(null, {
125+
query: new AV.Query(GameScore).equalTo('score', -1),
126+
success: function(result) {
127+
done(new Error('should not success'));
128+
},
129+
error: function(gameScore, error) {
130+
expect(error.code).to.be.eql(305);
131+
done();
132+
}
133+
});
134+
});
122135
});
123136

124137
describe("Deleting Objects",function(){

0 commit comments

Comments
 (0)