Skip to content

Add setDoc, updateDoc, deleteDoc and addDoc #3306

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 10 commits into from
Jun 27, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .changeset/tame-countries-marry.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
---
---

143 changes: 141 additions & 2 deletions packages/firestore/exp/src/api/reference.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,18 +20,30 @@
import * as firestore from '../../index';

import { Firestore } from './database';
import { DocumentKeyReference } from '../../../src/api/user_data_reader';
import {
DocumentKeyReference,
ParsedUpdateData
} from '../../../src/api/user_data_reader';
import { debugAssert } from '../../../src/util/assert';
import { cast } from '../../../lite/src/api/util';
import { DocumentSnapshot, QuerySnapshot } from './snapshot';
import {
applyFirestoreDataConverter,
getDocsViaSnapshotListener,
getDocViaSnapshotListener,
SnapshotMetadata
} from '../../../src/api/database';
import { ViewSnapshot } from '../../../src/core/view_snapshot';
import { DocumentReference, Query } from '../../../lite/src/api/reference';
import {
CollectionReference,
doc,
DocumentReference,
newUserDataReader,
Query
} from '../../../lite/src/api/reference';
import { Document } from '../../../src/model/document';
import { DeleteMutation, Precondition } from '../../../src/model/mutation';
import { FieldPath } from '../../../src/api/field_path';

export function getDoc<T>(
reference: firestore.DocumentReference<T>
Expand Down Expand Up @@ -141,6 +153,133 @@ export function getQueryFromServer<T>(
});
}

export function setDoc<T>(
reference: firestore.DocumentReference<T>,
data: T
): Promise<void>;
export function setDoc<T>(
reference: firestore.DocumentReference<T>,
data: Partial<T>,
options: firestore.SetOptions
): Promise<void>;
export function setDoc<T>(
reference: firestore.DocumentReference<T>,
data: T,
options?: firestore.SetOptions
): Promise<void> {
const ref = cast<DocumentReference<T>>(reference, DocumentReference);
const firestore = cast(ref.firestore, Firestore);

const convertedValue = applyFirestoreDataConverter(
ref._converter,
data,
options
);
const dataReader = newUserDataReader(firestore);
const parsed = dataReader.parseSetData(
'setDoc',
ref._key,
convertedValue,
ref._converter !== null,
options
);

return firestore
._getFirestoreClient()
.then(firestoreClient =>
firestoreClient.write(parsed.toMutations(ref._key, Precondition.none()))
);
}

export function updateDoc(
reference: firestore.DocumentReference<unknown>,
data: firestore.UpdateData
): Promise<void>;
export function updateDoc(
reference: firestore.DocumentReference<unknown>,
field: string | firestore.FieldPath,
value: unknown,
...moreFieldsAndValues: unknown[]
): Promise<void>;
export function updateDoc(
reference: firestore.DocumentReference<unknown>,
fieldOrUpdateData: string | firestore.FieldPath | firestore.UpdateData,
value?: unknown,
...moreFieldsAndValues: unknown[]
): Promise<void> {
const ref = cast<DocumentReference<unknown>>(reference, DocumentReference);
const firestore = cast(ref.firestore, Firestore);
const dataReader = newUserDataReader(firestore);

let parsed: ParsedUpdateData;
if (
typeof fieldOrUpdateData === 'string' ||
fieldOrUpdateData instanceof FieldPath
) {
parsed = dataReader.parseUpdateVarargs(
'updateDoc',
ref._key,
fieldOrUpdateData,
value,
moreFieldsAndValues
);
} else {
parsed = dataReader.parseUpdateData(
'updateDoc',
ref._key,
fieldOrUpdateData
);
}

return firestore
._getFirestoreClient()
.then(firestoreClient =>
Copy link
Contributor

Choose a reason for hiding this comment

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

Same comment from previous PR's. Why is there chaining instead of just using async/await?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Same response: )

"The outermost code needs to be async to ensure synchronous function execution, which impacts error propagation and execution order. The cast calls here, for example, would not throw but cause rejected Promises."

In this case, this also impact user input validation, which we want to throw as it is likely caused by invalid SDK usage.

firestoreClient.write(
parsed.toMutations(ref._key, Precondition.exists(true))
)
);
}

export function deleteDoc(
reference: firestore.DocumentReference
): Promise<void> {
const ref = cast<DocumentReference<unknown>>(reference, DocumentReference);
const firestore = cast(ref.firestore, Firestore);
return firestore
._getFirestoreClient()
.then(firestoreClient =>
firestoreClient.write([new DeleteMutation(ref._key, Precondition.none())])
);
}

export function addDoc<T>(
reference: firestore.CollectionReference<T>,
data: T
): Promise<firestore.DocumentReference<T>> {
const collRef = cast<CollectionReference<T>>(reference, CollectionReference);
const firestore = cast(collRef, Firestore);
const docRef = doc(collRef);

const convertedValue = applyFirestoreDataConverter(collRef._converter, data);

const dataReader = newUserDataReader(collRef.firestore);
const parsed = dataReader.parseSetData(
'addDoc',
docRef._key,
convertedValue,
collRef._converter !== null
);

return firestore
._getFirestoreClient()
.then(firestoreClient =>
firestoreClient.write(
parsed.toMutations(docRef._key, Precondition.exists(false))
)
)
.then(() => docRef);
}

/**
* Converts a ViewSnapshot that contains the single document specified by `ref`
* to a DocumentSnapshot.
Expand Down
12 changes: 12 additions & 0 deletions packages/firestore/exp/test/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import {
DEFAULT_SETTINGS
} from '../../test/integration/util/settings';
import { collection } from '../../lite/src/api/reference';
import { setDoc } from '../src/api/reference';
import { AutoId } from '../../src/util/misc';

let appCount = 0;
Expand Down Expand Up @@ -63,3 +64,14 @@ export function withTestDoc(
): Promise<void> {
return withTestDb(db => fn(doc(collection(db, 'test-collection'))));
}

export function withTestDocAndInitialData(
data: firestore.DocumentData,
fn: (doc: firestore.DocumentReference) => void | Promise<void>
): Promise<void> {
return withTestDb(async db => {
const ref = doc(collection(db, 'test-collection'));
await setDoc(ref, data);
return fn(ref);
});
}
Loading