Skip to content

Commit c268bd3

Browse files
authored
issue(afterFind): Fixes issue when using afterFind with relations (parse-community#4752)
* Adds failing test for the issue * Adds fix for the issue
1 parent 53e88f1 commit c268bd3

File tree

2 files changed

+45
-1
lines changed

2 files changed

+45
-1
lines changed

spec/ParseRelation.spec.js

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -801,4 +801,37 @@ describe('Parse.Relation testing', () => {
801801
done();
802802
});
803803
});
804+
805+
it('ensures beforeFind on relation doesnt side effect', (done) => {
806+
const parent = new Parse.Object('Parent');
807+
const child = new Parse.Object('Child');
808+
child.save().then(() => {
809+
parent.relation('children').add(child);
810+
return parent.save();
811+
}).then(() => {
812+
// We need to use a new reference otherwise the JS SDK remembers the className for a relation
813+
// After saves or finds
814+
const otherParent = new Parse.Object('Parent');
815+
otherParent.id = parent.id;
816+
return otherParent.relation('children').query().find();
817+
}).then((children) => {
818+
// Without an after find all is good, all results have been redirected with proper className
819+
children.forEach((child) => expect(child.className).toBe('Child'));
820+
// Setup the afterFind
821+
Parse.Cloud.afterFind('Child', (req) => {
822+
return Promise.resolve(req.objects.map((child) => {
823+
child.set('afterFound', true);
824+
return child;
825+
}));
826+
});
827+
const otherParent = new Parse.Object('Parent');
828+
otherParent.id = parent.id;
829+
return otherParent.relation('children').query().find();
830+
}).then((children) => {
831+
children.forEach((child) => {
832+
expect(child.className).toBe('Child');
833+
expect(child.get('afterFound')).toBe(true);
834+
});
835+
}).then(done).catch(done.fail);
836+
});
804837
});

src/RestQuery.js

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -590,7 +590,18 @@ RestQuery.prototype.runAfterFindTrigger = function() {
590590
}
591591
// Run afterFind trigger and set the new results
592592
return triggers.maybeRunAfterFindTrigger(triggers.Types.afterFind, this.auth, this.className,this.response.results, this.config).then((results) => {
593-
this.response.results = results;
593+
// Ensure we properly set the className back
594+
if (this.redirectClassName) {
595+
this.response.results = results.map((object) => {
596+
if (object instanceof Parse.Object) {
597+
object = object.toJSON();
598+
}
599+
object.className = this.redirectClassName;
600+
return object;
601+
});
602+
} else {
603+
this.response.results = results;
604+
}
594605
});
595606
};
596607

0 commit comments

Comments
 (0)