Skip to content

Commit

Permalink
fix(firestore): track all ref subs
Browse files Browse the repository at this point in the history
fix #1223
  • Loading branch information
posva committed Dec 19, 2022
1 parent b78dfa7 commit 1d46371
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 7 deletions.
14 changes: 7 additions & 7 deletions src/firestore/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,18 +87,18 @@ export function extractRefs(
) {
data[key] = ref
} else if (isDocumentRef(ref)) {
// key for the subscription
const refSubKey = path + key
// allow values to be null (like non-existent refs)
// TODO: better typing since this isObject shouldn't be necessary but it doesn't work
data[key] =
typeof oldDoc === 'object' &&
key in oldDoc &&
// only copy refs if they were refs before
// if the ref was already bound, keep the same object
// otherwise set the path as a string so it can be bound later
// https://github.com/vuejs/vuefire/issues/831
typeof oldDoc[key] != 'string'
? oldDoc[key]
: ref.path
// https://github.com/vuejs/vuefire/pull/1223
refSubKey in subs ? oldDoc[key] : ref.path
// TODO: handle subpathes?
refs[path + key] = ref
refs[refSubKey] = ref
} else if (Array.isArray(ref)) {
data[key] = Array(ref.length)
// fill existing refs into data but leave the rest empty
Expand Down
31 changes: 31 additions & 0 deletions tests/firestore/refs-in-documents.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,37 @@ describe('Firestore refs in documents', async () => {
expect(data.value).toEqual({ a: aRef.path })
})

// https://github.com/vuejs/vuefire/pull/1223
it('sets the path even if the value was null before', async () => {
const docRef = await addDoc(listOfRefs, { a: null })
const { data, pending, promise } = factory({
ref: docRef,
options: { maxRefDepth: 0 },
})

await promise.value
expect(data.value).toEqual({ a: null })
await updateDoc(docRef, { a: aRef })
expect(data.value).toEqual({ a: aRef.path })
})

it('keeps null for non existent docs refs when updating the doc', async () => {
const docRef = await addDoc(listOfRefs, { a: null })

const { data, promise } = factory({ ref: docRef })
await promise.value

expect(data.value).toEqual({ a: null })

await updateDoc(docRef, { a: emptyRef })

expect(data.value).toEqual({ a: null })

await updateDoc(docRef, { name: 'd' })

expect(data.value).toEqual({ a: null, name: 'd' })
})

it('does not fail with cyclic refs', async () => {
const docRef = await addDoc(listOfRefs, {})
await setDoc(docRef, { ref: docRef })
Expand Down

0 comments on commit 1d46371

Please sign in to comment.