Skip to content

Provide document path context for input validation errors. #3189

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 4 commits into from
Jun 24, 2020
Merged
Show file tree
Hide file tree
Changes from 2 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
16 changes: 13 additions & 3 deletions packages/firestore/lite/src/api/reference.ts
Original file line number Diff line number Diff line change
Expand Up @@ -307,7 +307,12 @@ export function setDoc<T>(
ref.firestore._settings!
);

const parsed = dataReader.parseSetData('setDoc', convertedValue, options);
const parsed = dataReader.parseSetData(
'setDoc',
ref._key,
convertedValue,
options
);

return configureClient.then(datastore =>
invokeCommitRpc(
Expand Down Expand Up @@ -349,12 +354,17 @@ export function updateDoc(
) {
parsed = dataReader.parseUpdateVarargs(
'updateDoc',
ref._key,
fieldOrUpdateData,
value,
moreFieldsAndValues
);
} else {
parsed = dataReader.parseUpdateData('updateDoc', fieldOrUpdateData);
parsed = dataReader.parseUpdateData(
'updateDoc',
ref._key,
fieldOrUpdateData
);
}

return configureClient.then(datastore =>
Expand Down Expand Up @@ -406,7 +416,7 @@ export function addDoc<T>(
collRef.firestore._databaseId,
collRef.firestore._settings!
);
const parsed = dataReader.parseSetData('addDoc', convertedValue);
const parsed = dataReader.parseSetData('addDoc', docRef._key, convertedValue);

return configureClient
.then(datastore =>
Expand Down
3 changes: 3 additions & 0 deletions packages/firestore/lite/src/api/transaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ export class Transaction implements firestore.Transaction {
);
const parsed = this._dataReader.parseSetData(
'Transaction.set',
ref._key,
convertedValue,
options
);
Expand Down Expand Up @@ -140,13 +141,15 @@ export class Transaction implements firestore.Transaction {
) {
parsed = this._dataReader.parseUpdateVarargs(
'Transaction.update',
ref._key,
fieldOrUpdateData,
value,
moreFieldsAndValues
);
} else {
parsed = this._dataReader.parseUpdateData(
'Transaction.update',
ref._key,
fieldOrUpdateData
);
}
Expand Down
3 changes: 3 additions & 0 deletions packages/firestore/lite/src/api/write_batch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ export class WriteBatch implements firestore.WriteBatch {

const parsed = this._dataReader.parseSetData(
'WriteBatch.set',
ref._key,
convertedValue,
options
);
Expand Down Expand Up @@ -109,13 +110,15 @@ export class WriteBatch implements firestore.WriteBatch {
) {
parsed = this._dataReader.parseUpdateVarargs(
'WriteBatch.update',
ref._key,
fieldOrUpdateData,
value,
moreFieldsAndValues
);
} else {
parsed = this._dataReader.parseUpdateData(
'WriteBatch.update',
ref._key,
fieldOrUpdateData
);
}
Expand Down
13 changes: 12 additions & 1 deletion packages/firestore/src/api/database.ts
Original file line number Diff line number Diff line change
Expand Up @@ -738,6 +738,7 @@ export class Transaction implements firestore.Transaction {
);
const parsed = this._firestore._dataReader.parseSetData(
functionName,
ref._key,
convertedValue,
options
);
Expand Down Expand Up @@ -776,6 +777,7 @@ export class Transaction implements firestore.Transaction {
);
parsed = this._firestore._dataReader.parseUpdateVarargs(
'Transaction.update',
ref._key,
fieldOrUpdateData,
value,
moreFieldsAndValues
Expand All @@ -789,6 +791,7 @@ export class Transaction implements firestore.Transaction {
);
parsed = this._firestore._dataReader.parseUpdateData(
'Transaction.update',
ref._key,
fieldOrUpdateData
);
}
Expand Down Expand Up @@ -835,6 +838,7 @@ export class WriteBatch implements firestore.WriteBatch {
);
const parsed = this._firestore._dataReader.parseSetData(
functionName,
ref._key,
convertedValue,
options
);
Expand Down Expand Up @@ -877,6 +881,7 @@ export class WriteBatch implements firestore.WriteBatch {
);
parsed = this._firestore._dataReader.parseUpdateVarargs(
'WriteBatch.update',
ref._key,
fieldOrUpdateData,
value,
moreFieldsAndValues
Expand All @@ -890,6 +895,7 @@ export class WriteBatch implements firestore.WriteBatch {
);
parsed = this._firestore._dataReader.parseUpdateData(
'WriteBatch.update',
ref._key,
fieldOrUpdateData
);
}
Expand Down Expand Up @@ -1029,6 +1035,7 @@ export class DocumentReference<T = firestore.DocumentData>
);
const parsed = this.firestore._dataReader.parseSetData(
functionName,
this._key,
convertedValue,
options
);
Expand Down Expand Up @@ -1057,6 +1064,7 @@ export class DocumentReference<T = firestore.DocumentData>
validateAtLeastNumberOfArgs('DocumentReference.update', arguments, 2);
parsed = this.firestore._dataReader.parseUpdateVarargs(
'DocumentReference.update',
this._key,
fieldOrUpdateData,
value,
moreFieldsAndValues
Expand All @@ -1065,6 +1073,7 @@ export class DocumentReference<T = firestore.DocumentData>
validateExactNumberOfArgs('DocumentReference.update', arguments, 1);
parsed = this.firestore._dataReader.parseUpdateData(
'DocumentReference.update',
this._key,
fieldOrUpdateData
);
}
Expand Down Expand Up @@ -1369,7 +1378,9 @@ export class DocumentSnapshot<T = firestore.DocumentData>
if (this._document) {
const value = this._document
.data()
.field(fieldPathFromArgument('DocumentSnapshot.get', fieldPath));
.field(
fieldPathFromArgument('DocumentSnapshot.get', fieldPath, this._key)
);
if (value !== null) {
const userDataWriter = new UserDataWriter(
this._firestore._databaseId,
Expand Down
5 changes: 4 additions & 1 deletion packages/firestore/src/api/field_value.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,11 +107,12 @@ export class ArrayUnionFieldValueImpl extends SerializableFieldValue {

_toFieldTransform(context: ParseContext): FieldTransform {
// Although array transforms are used with writes, the actual elements
// being uniomed or removed are not considered writes since they cannot
// being unioned or removed are not considered writes since they cannot
// contain any FieldValue sentinels, etc.
const parseContext = new ParseContext(
Copy link
Contributor

Choose a reason for hiding this comment

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

It might be time to add a helper method to ParseContext (or a tree-shakeable function in this file) that simplifies the creation of an argument parser. If arrayElement remains configurable, this code would replace line 112-122, 145-155 and 173-181.

Optional.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I pulled out createSentinelChildContext. LMK if this is what you had in mind.

{
dataSource: UserDataSource.Argument,
targetDoc: context.settings.targetDoc,
methodName: this._methodName,
arrayElement: true
},
Expand Down Expand Up @@ -144,6 +145,7 @@ export class ArrayRemoveFieldValueImpl extends SerializableFieldValue {
const parseContext = new ParseContext(
{
dataSource: UserDataSource.Argument,
targetDoc: context.settings.targetDoc,
methodName: this._methodName,
arrayElement: true
},
Expand Down Expand Up @@ -173,6 +175,7 @@ export class NumericIncrementFieldValueImpl extends SerializableFieldValue {
const parseContext = new ParseContext(
{
dataSource: UserDataSource.Argument,
targetDoc: context.settings.targetDoc,
methodName: this._methodName
},
context.databaseId,
Expand Down
95 changes: 68 additions & 27 deletions packages/firestore/src/api/user_data_reader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,8 @@ interface ContextSettings {
readonly dataSource: UserDataSource;
/** The name of the method the user called to create the ParseContext. */
readonly methodName: string;
/** The document the user is attempting to modify, if that applies. */
readonly targetDoc?: DocumentKey;
/**
* A path within the object being parsed. This could be an empty path (in
* which case the context represents the root of the data being parsed), or a
Expand Down Expand Up @@ -247,15 +249,11 @@ export class ParseContext {
}

createError(reason: string): Error {
const fieldDescription =
!this.path || this.path.isEmpty()
? ''
: ` (found in field ${this.path.toString()})`;
return new FirestoreError(
Code.INVALID_ARGUMENT,
`Function ${this.settings.methodName}() called with invalid data. ` +
reason +
fieldDescription
return createError(
reason,
this.settings.methodName,
this.path,
this.settings.targetDoc
);
}

Expand Down Expand Up @@ -309,14 +307,16 @@ export class UserDataReader {
/** Parse document data from a set() call. */
parseSetData(
methodName: string,
targetDoc: DocumentKey,
input: unknown,
options: firestore.SetOptions = {}
): ParsedSetData {
const context = this.createContext(
options.merge || options.mergeFields
? UserDataSource.MergeSet
: UserDataSource.Set,
methodName
methodName,
targetDoc
);
validatePlainObject('Data must be an object, but it was:', context, input);
const updateData = parseObject(input, context)!;
Expand All @@ -338,7 +338,8 @@ export class UserDataReader {
} else if (typeof stringOrFieldPath === 'string') {
fieldPath = fieldPathFromDotSeparatedString(
methodName,
stringOrFieldPath
stringOrFieldPath,
targetDoc
);
} else {
throw fail(
Expand Down Expand Up @@ -375,14 +376,22 @@ export class UserDataReader {
}

/** Parse update data from an update() call. */
parseUpdateData(methodName: string, input: unknown): ParsedUpdateData {
const context = this.createContext(UserDataSource.Update, methodName);
parseUpdateData(
methodName: string,
targetDoc: DocumentKey,
input: unknown
): ParsedUpdateData {
const context = this.createContext(
UserDataSource.Update,
methodName,
targetDoc
);
validatePlainObject('Data must be an object, but it was:', context, input);

const fieldMaskPaths: FieldPath[] = [];
const updateData = new ObjectValueBuilder();
forEach(input as Dict<unknown>, (key, value) => {
const path = fieldPathFromDotSeparatedString(methodName, key);
const path = fieldPathFromDotSeparatedString(methodName, key, targetDoc);

const childContext = context.childContextForFieldPath(path);
if (
Expand Down Expand Up @@ -411,12 +420,17 @@ export class UserDataReader {
/** Parse update data from a list of field/value arguments. */
parseUpdateVarargs(
methodName: string,
targetDoc: DocumentKey,
field: string | BaseFieldPath,
value: unknown,
moreFieldsAndValues: unknown[]
): ParsedUpdateData {
const context = this.createContext(UserDataSource.Update, methodName);
const keys = [fieldPathFromArgument(methodName, field)];
const context = this.createContext(
UserDataSource.Update,
methodName,
targetDoc
);
const keys = [fieldPathFromArgument(methodName, field, targetDoc)];
const values = [value];

if (moreFieldsAndValues.length % 2 !== 0) {
Expand Down Expand Up @@ -474,12 +488,14 @@ export class UserDataReader {
/** Creates a new top-level parse context. */
private createContext(
dataSource: UserDataSource,
methodName: string
methodName: string,
targetDoc?: DocumentKey
): ParseContext {
return new ParseContext(
{
dataSource,
methodName,
targetDoc,
path: FieldPath.EMPTY_PATH,
arrayElement: false
},
Expand Down Expand Up @@ -740,18 +756,16 @@ function validatePlainObject(
*/
export function fieldPathFromArgument(
methodName: string,
path: string | BaseFieldPath
path: string | BaseFieldPath,
targetDoc?: DocumentKey
): FieldPath {
if (path instanceof BaseFieldPath) {
return path._internalPath;
} else if (typeof path === 'string') {
return fieldPathFromDotSeparatedString(methodName, path);
} else {
const message = 'Field path arguments must be of type string or FieldPath.';
throw new FirestoreError(
Code.INVALID_ARGUMENT,
`Function ${methodName}() called with invalid data. ${message}`
);
throw createError(message, methodName, undefined, targetDoc);
}
}

Expand All @@ -761,22 +775,49 @@ export function fieldPathFromArgument(
* @param methodName The publicly visible method name
* @param path The dot-separated string form of a field path which will be split
* on dots.
* @param targetDoc The document against which the field path will be evaluated.
*/
export function fieldPathFromDotSeparatedString(
methodName: string,
path: string
path: string,
targetDoc?: DocumentKey
): FieldPath {
try {
return fromDotSeparatedString(path)._internalPath;
} catch (e) {
const message = errorMessage(e);
throw new FirestoreError(
Code.INVALID_ARGUMENT,
`Function ${methodName}() called with invalid data. ${message}`
);
throw createError(message, methodName, undefined, targetDoc);
}
}

function createError(
reason: string,
methodName: string,
path?: FieldPath,
targetDoc?: DocumentKey
): Error {
const hasPath = path && !path.isEmpty();
const hasDocument = targetDoc !== undefined;

let description = '';
if (hasPath || hasDocument) {
description += ' (found';

if (hasPath) {
description += ` in field ${path!.toString()}`;
Copy link
Contributor

Choose a reason for hiding this comment

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

Nit: ${path!.toString()} is the same as ${path} (here and below).

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Fixed.

}
if (hasDocument) {
description += ` in document ${targetDoc!.toString()}`;
}
description += ')';
}

return new FirestoreError(
Code.INVALID_ARGUMENT,
`Function ${methodName}() called with invalid data. ` + reason + description
);
}

/**
* Extracts the message from a caught exception, which should be an Error object
* though JS doesn't guarantee that.
Expand Down
Loading