Skip to content

Commit 56e7027

Browse files
committed
feat(proxy-state-tree): don't allow nesting proxies in state tree
1 parent b6e9ac0 commit 56e7027

File tree

2 files changed

+44
-1
lines changed

2 files changed

+44
-1
lines changed

packages/node_modules/proxy-state-tree/src/index.test.ts

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,19 @@ describe('OBJECTS', () => {
6666
tree.get().foo = 'bar2'
6767
}).toThrow()
6868
})
69+
test('should throw if parts of state are nested', () => {
70+
const state = {
71+
foo: {
72+
nested: 'bar',
73+
},
74+
}
75+
const tree = new ProxyStateTree(state)
76+
expect(() => {
77+
tree.startMutationTracking()
78+
tree.get().foo = tree.get().foo
79+
tree.clearMutationTracking()
80+
}).toThrowError(/exists in the state tree on path "foo"/i)
81+
})
6982
test('should track SET mutations', () => {
7083
const state = {
7184
foo: 'bar',
@@ -228,6 +241,23 @@ describe('ARRAYS', () => {
228241
tree.get().foo.push('foo')
229242
}).toThrow()
230243
})
244+
test('should throw if parts of state are nested', () => {
245+
const state = {
246+
foo: [undefined],
247+
bar: {
248+
nested: 'baz',
249+
},
250+
}
251+
const tree = new ProxyStateTree(state)
252+
tree.startMutationTracking()
253+
254+
// Property mutation
255+
expect(() => {
256+
tree.get().foo[0] = tree.get().bar
257+
}).toThrowError(/exists in the state tree on path "bar"/i)
258+
259+
tree.clearMutationTracking()
260+
})
231261
test('should track PUSH mutations', () => {
232262
const state = {
233263
foo: [],

packages/node_modules/proxy-state-tree/src/proxify.ts

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,13 @@ function createArrayProxy(tree, value, path) {
8484
`proxy-state-tree - You are mutating the path "${nestedPath}", but it is not allowed`
8585
)
8686
}
87-
87+
if (value[IS_PROXY] === true) {
88+
throw new Error(
89+
`proxy-state-tree - You are trying to insert a value that already exists in the state tree on path "${
90+
value[PATH]
91+
}"`
92+
)
93+
}
8894
tree.currentMutations.push({
8995
method: 'set',
9096
path: nestedPath,
@@ -131,6 +137,13 @@ function createObjectProxy(tree, value, path) {
131137
`proxy-state-tree - You are mutating the path "${nestedPath}", but it is not allowed`
132138
)
133139
}
140+
if (value[IS_PROXY] === true) {
141+
throw new Error(
142+
`proxy-state-tree - You are trying to insert a value that already exists in the state tree on path "${
143+
value[PATH]
144+
}"`
145+
)
146+
}
134147
if (shouldTrackMutations(tree, nestedPath)) {
135148
if (!(prop in target)) {
136149
tree.objectChanges.add(path)

0 commit comments

Comments
 (0)