Skip to content

fix: Operations in afterSave triggers aren't decoded #8481

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 1 commit into
base: alpha
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 66 additions & 0 deletions spec/CloudCode.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -1666,6 +1666,72 @@ describe('Cloud Code', () => {
expect(obj.get('count')).toBe(0);
});

it('operations in beforeSave should return to client', async () => {
Parse.Cloud.afterSave('MyObject', ({ object }) => {
object.unset('foo');
object.increment('count');
object.addUnique('unique', 2);
object.add('array', 2);
object.remove('remove', 2);
});
const saveResponse = await request({
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Parse-Application-Id': 'test',
'X-Parse-REST-API-Key': 'rest',
'X-Parse-Installation-Id': 'yolo',
},
url: 'http://localhost:8378/1/classes/MyObject',
body: JSON.stringify({
unique: [2],
remove: [2],
}),
}).catch(e => {
console.log({ e });
});
console.log(saveResponse.data);
const { array, count, foo, unique, remove } = saveResponse.data;
expect(array).toEqual([2]);
expect(count).toEqual(1);
expect(foo).toEqual(null);
expect(unique).toBeUndefined();
expect(remove).toEqual([]);
});

it('operations in afterSave should return to client', async () => {
Parse.Cloud.afterSave('MyObject', ({ object }) => {
object.unset('foo');
object.increment('count');
object.addUnique('unique', 2);
object.add('array', 2);
object.remove('remove', 2);
});
const saveResponse = await request({
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Parse-Application-Id': 'test',
'X-Parse-REST-API-Key': 'rest',
'X-Parse-Installation-Id': 'yolo',
},
url: 'http://localhost:8378/1/classes/MyObject',
body: JSON.stringify({
unique: [2],
remove: [2],
}),
}).catch(e => {
console.log({ e });
});
console.log(saveResponse.data);
const { array, count, foo, unique, remove } = saveResponse.data;
expect(array).toEqual([2]);
expect(count).toEqual(1);
expect(foo).toEqual(null);
expect(unique).toBeUndefined();
expect(remove).toEqual([]);
});

it('pointer should not be cleared by triggers', async () => {
Parse.Cloud.afterSave('MyObject', () => {});
const foo = await new Parse.Object('Test', { foo: 'bar' }).save();
Expand Down
82 changes: 70 additions & 12 deletions src/RestWrite.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ var cryptoUtils = require('./cryptoUtils');
var passwordCrypto = require('./password');
var Parse = require('parse/node');
var triggers = require('./triggers');
var ClientSDK = require('./ClientSDK');
const util = require('util');
import RestQuery from './RestQuery';
import _ from 'lodash';
Expand All @@ -38,7 +37,9 @@ function RestWrite(config, auth, className, query, data, originalData, clientSDK
this.auth = auth;
this.className = className;
this.clientSDK = clientSDK;
this.storage = {};
this.storage = {
fieldsChangedByTrigger: [],
};
this.runOptions = {};
this.context = context || {};

Expand Down Expand Up @@ -281,17 +282,19 @@ RestWrite.prototype.runBeforeSaveTrigger = function () {
);
})
.then(response => {
if (response && response.object) {
this.storage.fieldsChangedByTrigger = _.reduce(
response.object,
this.storage.fieldsChangedByTrigger.push(
..._.reduce(
response?.object || updatedObject.toJSON(),
(result, value, key) => {
if (!_.isEqual(this.data[key], value)) {
result.push(key);
}
return result;
},
[]
);
)
);
if (response && response.object) {
this.data = response.object;
// We should delete the objectId for an update write
if (this.query && this.query.objectId) {
Expand Down Expand Up @@ -349,7 +352,6 @@ RestWrite.prototype.setRequiredFieldsIfNeeded = function () {
(typeof this.data[fieldName] === 'object' && this.data[fieldName].__op === 'Delete'))
) {
this.data[fieldName] = schema.fields[fieldName].defaultValue;
this.storage.fieldsChangedByTrigger = this.storage.fieldsChangedByTrigger || [];
if (this.storage.fieldsChangedByTrigger.indexOf(fieldName) < 0) {
this.storage.fieldsChangedByTrigger.push(fieldName);
}
Expand Down Expand Up @@ -1599,6 +1601,18 @@ RestWrite.prototype.runAfterSaveTrigger = function () {
this.context
)
.then(result => {
this.storage.fieldsChangedByTrigger.push(
..._.reduce(
updatedObject.toJSON(),
(result, value, key) => {
if (!_.isEqual(this.data[key], value)) {
result.push(key);
}
return result;
},
[]
)
);
const jsonReturned = result && !result._toFullJSON;
if (jsonReturned) {
this.pendingOps.operations = {};
Expand Down Expand Up @@ -1737,18 +1751,62 @@ RestWrite.prototype._updateResponseWithData = function (response, data) {
if (_.isEmpty(this.storage.fieldsChangedByTrigger)) {
return response;
}
const clientSupportsDelete = ClientSDK.supportsForwardDelete(this.clientSDK);
this.storage.fieldsChangedByTrigger.forEach(fieldName => {
const dataValue = data[fieldName];
let dataValue = deepcopy(data[fieldName]);

if (!Object.prototype.hasOwnProperty.call(response, fieldName)) {
response[fieldName] = dataValue;
}

// Strips operations from responses
if (response[fieldName] && response[fieldName].__op) {
delete response[fieldName];
if (clientSupportsDelete && dataValue.__op == 'Delete') {
const value = response[fieldName];
const op = value?.__op;
if (op) {
switch (op) {
case 'Increment': {
if (!dataValue) {
dataValue = 0;
}
dataValue += value.amount;
break;
}
case 'Delete': {
dataValue = null;
break;
}
case 'AddUnique':
case 'Add': {
if (!dataValue) {
dataValue = [];
}
for (const obj of value.objects) {
if (op === 'AddUnique' && dataValue.includes(obj)) {
continue;
}
dataValue.push(obj);
}
break;
}
case 'Remove': {
if (!dataValue) {
dataValue = [];
}
for (const obj of value.objects) {
let i = dataValue.length;
while (i--) {
const current = dataValue[i];
if (current === obj) {
dataValue.splice(i, 1);
}
}
}
break;
}
default:
}
if (util.isDeepStrictEqual(dataValue, this.data[fieldName])) {
delete response[fieldName];
} else {
response[fieldName] = dataValue;
}
}
Expand Down