Skip to content

Commit 06f409d

Browse files
committed
Allow cloning of objects with readonly attributes
1 parent 222efeb commit 06f409d

File tree

3 files changed

+43
-2
lines changed

3 files changed

+43
-2
lines changed

src/ParseObject.js

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -780,12 +780,25 @@ export default class ParseObject {
780780
* @return {Parse.Object}
781781
*/
782782
clone(): any {
783-
var clone = new this.constructor();
783+
let clone = new this.constructor();
784784
if (!clone.className) {
785785
clone.className = this.className;
786786
}
787+
let attributes = this.attributes;
788+
if (typeof this.constructor.readOnlyAttributes === 'function') {
789+
let readonly = this.constructor.readOnlyAttributes() || [];
790+
// Attributes are frozen, so we have to rebuild an object,
791+
// rather than delete readonly keys
792+
let copy = {};
793+
for (let a in attributes) {
794+
if (readonly.indexOf(a) < 0) {
795+
copy[a] = attributes[a];
796+
}
797+
}
798+
attributes = copy;
799+
}
787800
if (clone.set) {
788-
clone.set(this.attributes);
801+
clone.set(attributes);
789802
}
790803
return clone;
791804
}

src/__tests__/ParseSession-test.js

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,4 +127,17 @@ describe('ParseSession', () => {
127127
done();
128128
});
129129
}));
130+
131+
it('can be cloned', () => {
132+
var s = ParseObject.fromJSON({
133+
className: '_Session',
134+
sessionToken: '123abc',
135+
foo: 12
136+
});
137+
138+
var clone = s.clone();
139+
expect(clone.className).toBe('_Session');
140+
expect(clone.get('foo')).toBe(12);
141+
expect(clone.get('sessionToken')).toBe(undefined);
142+
});
130143
});

src/__tests__/ParseUser-test.js

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,21 @@ describe('ParseUser', () => {
8585
expect(u2.getEmail()).toBe('[email protected]');
8686
});
8787

88+
it('can clone User objects', () => {
89+
var u = ParseObject.fromJSON({
90+
className: '_User',
91+
username: 'user12',
92+
93+
sessionToken: '123abc'
94+
});
95+
96+
var clone = u.clone();
97+
expect(clone.className).toBe('_User');
98+
expect(clone.get('username')).toBe('user12');
99+
expect(clone.get('email')).toBe('[email protected]');
100+
expect(clone.get('sessionToken')).toBe(undefined);
101+
});
102+
88103
it('makes session tokens readonly', () => {
89104
var u = new ParseUser();
90105
expect(u.set.bind(u, 'sessionToken', 'token')).toThrow(

0 commit comments

Comments
 (0)