Skip to content

Support union types and optional fields with dot separation on UpdateData #5394

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

Merged
merged 13 commits into from
Sep 20, 2021
5 changes: 5 additions & 0 deletions .changeset/clean-cameras-check.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@firebase/firestore': minor
---

Fixed a bug where `UpdateData` did not recognize optional, dot-separated string fields.
7 changes: 5 additions & 2 deletions common/api-review/firestore-lite.api.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@ export class Bytes {
toUint8Array(): Uint8Array;
}

// @public
export type ChildUpdateFields<T, K extends string> = T extends Record<string, any> ? AddPrefixToKeys<K, UpdateData<T>> : never;

// @public
export function collection(firestore: Firestore, path: string, ...pathSegments: string[]): CollectionReference<DocumentData>;

Expand Down Expand Up @@ -191,7 +194,7 @@ export { LogLevel }

// @public
export type NestedUpdateFields<T extends Record<string, unknown>> = UnionToIntersection<{
[K in keyof T & string]: T[K] extends Record<string, unknown> ? AddPrefixToKeys<K, UpdateData<T[K]>> : never;
[K in keyof T & string]: ChildUpdateFields<T[K], K>;
}[keyof T & string]>;

// @public
Expand Down Expand Up @@ -332,7 +335,7 @@ export class Transaction {
export type UnionToIntersection<U> = (U extends unknown ? (k: U) => void : never) extends (k: infer I) => void ? I : never;

// @public
export type UpdateData<T> = T extends Primitive ? T : T extends Map<infer K, infer V> ? Map<UpdateData<K>, UpdateData<V>> : T extends {} ? {
export type UpdateData<T> = T extends Primitive ? T : T extends {} ? {
[K in keyof T]?: UpdateData<T[K]> | FieldValue;
} & NestedUpdateFields<T> : Partial<T>;

Expand Down
7 changes: 5 additions & 2 deletions common/api-review/firestore.api.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ export class Bytes {
// @public
export const CACHE_SIZE_UNLIMITED = -1;

// @public
export type ChildUpdateFields<T, K extends string> = T extends Record<string, any> ? AddPrefixToKeys<K, UpdateData<T>> : never;

// @public
export function clearIndexedDbPersistence(firestore: Firestore): Promise<void>;

Expand Down Expand Up @@ -265,7 +268,7 @@ export function namedQuery(firestore: Firestore, name: string): Promise<Query |

// @public
export type NestedUpdateFields<T extends Record<string, unknown>> = UnionToIntersection<{
[K in keyof T & string]: T[K] extends Record<string, unknown> ? AddPrefixToKeys<K, UpdateData<T[K]>> : never;
[K in keyof T & string]: ChildUpdateFields<T[K], K>;
}[keyof T & string]>;

// @public
Expand Down Expand Up @@ -481,7 +484,7 @@ export interface Unsubscribe {
}

// @public
export type UpdateData<T> = T extends Primitive ? T : T extends Map<infer K, infer V> ? Map<UpdateData<K>, UpdateData<V>> : T extends {} ? {
export type UpdateData<T> = T extends Primitive ? T : T extends {} ? {
[K in keyof T]?: UpdateData<T[K]> | FieldValue;
} & NestedUpdateFields<T> : Partial<T>;

Expand Down
1 change: 1 addition & 0 deletions packages/firestore/lite/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ export {
export {
Primitive,
NestedUpdateFields,
ChildUpdateFields,
AddPrefixToKeys,
UnionToIntersection
} from '../src/lite-api/types';
Expand Down
1 change: 1 addition & 0 deletions packages/firestore/src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,7 @@ export { AbstractUserDataWriter } from './lite-api/user_data_writer';
export {
Primitive,
NestedUpdateFields,
ChildUpdateFields,
AddPrefixToKeys,
UnionToIntersection
} from '../src/lite-api/types';
Expand Down
3 changes: 0 additions & 3 deletions packages/firestore/src/lite-api/reference.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,12 +78,9 @@ export type WithFieldValue<T> = T extends Primitive
*/
export type UpdateData<T> = T extends Primitive
? T
: T extends Map<infer K, infer V>
? Map<UpdateData<K>, UpdateData<V>>
: T extends {}
? { [K in keyof T]?: UpdateData<T[K]> | FieldValue } & NestedUpdateFields<T>
: Partial<T>;

/**
* An options object that configures the behavior of {@link @firebase/firestore/lite#(setDoc:1)}, {@link
* @firebase/firestore/lite#(WriteBatch.set:1)} and {@link @firebase/firestore/lite#(Transaction.set:1)} calls. These calls can be
Expand Down
23 changes: 17 additions & 6 deletions packages/firestore/src/lite-api/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,15 +35,26 @@ export type NestedUpdateFields<T extends Record<string, unknown>> =
UnionToIntersection<
{
// Check that T[K] extends Record to only allow nesting for map values.
[K in keyof T & string]: T[K] extends Record<string, unknown>
? // Recurse into the map and add the prefix in front of each key
// (e.g. Prefix 'bar.' to create: 'bar.baz' and 'bar.qux'.
AddPrefixToKeys<K, UpdateData<T[K]>>
: // TypedUpdateData is always a map of values.
never;
// Union with `undefined` to allow for optional nested fields
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

outdated

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, thanks

[K in keyof T & string]: ChildUpdateFields<T[K], K>;
}[keyof T & string] // Also include the generated prefix-string keys.
>;

/**
* Helper for calculating the nested fields for a given type T. This is needed
* to distribute union types such as `undefined | {...}` (happens for optional
* props) or `{a: A} | {b: B}`.
* https://www.typescriptlang.org/docs/handbook/advanced-types.html#distributive-conditional-types
*/
export type ChildUpdateFields<T, K extends string> =
// Only allow nesting for map values
T extends Record<string, unknown>
? // Recurse into the map and add the prefix in front of each key
// (e.g. Prefix 'bar.' to create: 'bar.baz' and 'bar.qux'.
AddPrefixToKeys<K, UpdateData<T>>
: // UpdateData is always a map of values.
never;

/**
* Returns a new map where every key is prefixed with the outer key appended
* to a dot.
Expand Down
100 changes: 100 additions & 0 deletions packages/firestore/test/lite/integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1542,6 +1542,106 @@ describe('withConverter() support', () => {
});
});

it('supports optional fields', () => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you add a test for null?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

interface TestObjectOptional {
optionalStr?: string;
nested?: {
requiredStr: string;
};
}

const testConverterOptional = {
toFirestore(testObj: WithFieldValue<TestObjectOptional>) {
return { ...testObj };
},
fromFirestore(snapshot: QueryDocumentSnapshot): TestObjectOptional {
const data = snapshot.data();
return {
optionalStr: data.optionalStr,
nested: data.nested
};
}
};

return withTestDocAndInitialData(initialData, async docRef => {
const testDocRef: DocumentReference<TestObjectOptional> =
docRef.withConverter(testConverterOptional);

await updateDoc(testDocRef, {
optionalStr: 'foo'
});
await updateDoc(testDocRef, {
'optionalStr': 'foo'
});

await updateDoc(testDocRef, {
nested: {
requiredStr: 'foo'
}
});
await updateDoc(testDocRef, {
'nested.requiredStr': 'foo'
});
});
});

it('supports union fields', () => {
interface TestObjectUnion {
optionalStr?: string;
nested?:
| {
requiredStr: string;
}
| { requiredStrObject: string };
}

const testConverterUnion = {
toFirestore(testObj: WithFieldValue<TestObjectUnion>) {
return { ...testObj };
},
fromFirestore(snapshot: QueryDocumentSnapshot): TestObjectUnion {
const data = snapshot.data();
return {
optionalStr: data.optionalStr,
nested: data.nested
};
}
};

return withTestDocAndInitialData(initialData, async docRef => {
const testDocRef: DocumentReference<TestObjectUnion> =
docRef.withConverter(testConverterUnion);

await updateDoc(testDocRef, {
optionalStr: 'foo'
});
await updateDoc(testDocRef, {
'optionalStr': 'foo'
});

await updateDoc(testDocRef, {
nested: {
requiredStr: 'foo'
}
});
await updateDoc(testDocRef, {
'nested.requiredStr': 'foo'
});
await updateDoc(testDocRef, {
// @ts-expect-error
'nested.requiredStr': 1
});
await updateDoc(testDocRef, {
'nested.requiredStrObject': 'foo'
});

await updateDoc(testDocRef, {
// @ts-expect-error
'nested.requiredStringObject': 1
});
});
});

it('checks for nonexistent fields', () => {
return withTestDocAndInitialData(initialData, async docRef => {
const testDocRef: DocumentReference<TestObject> =
Expand Down