Skip to content
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

fix: support Objects created with Object.create({}) #842

Merged
merged 8 commits into from Jan 8, 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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 2 additions & 2 deletions dev/src/document.ts
Expand Up @@ -23,10 +23,10 @@ import {google} from '../protos/firestore_v1_proto_api';
import {FieldTransform} from './field-value';
import {FieldPath, validateFieldPath} from './path';
import {DocumentReference} from './reference';
import {isPlainObject, Serializer} from './serializer';
import {Serializer} from './serializer';
import {Timestamp} from './timestamp';
import {ApiMapValue, DocumentData, UpdateMap} from './types';
import {isEmpty, isObject} from './util';
import {isEmpty, isObject, isPlainObject} from './util';

import api = google.firestore.v1;

Expand Down
18 changes: 1 addition & 17 deletions dev/src/serializer.ts
Expand Up @@ -24,7 +24,7 @@ import {DocumentReference, Firestore} from './index';
import {FieldPath, QualifiedResourcePath} from './path';
import {Timestamp} from './timestamp';
import {ApiMapValue, DocumentData, ValidationOptions} from './types';
import {isEmpty, isObject} from './util';
import {isEmpty, isObject, isPlainObject} from './util';
import {customObjectMessage, invalidArgumentMessage} from './validate';

import api = proto.google.firestore.v1;
Expand Down Expand Up @@ -256,22 +256,6 @@ export class Serializer {
}
}

/**
* Verifies that 'obj' is a plain JavaScript object that can be encoded as a
* 'Map' in Firestore.
*
* @private
* @param input The argument to verify.
* @returns 'true' if the input can be a treated as a plain object.
*/
export function isPlainObject(input: unknown): input is DocumentData {
return (
isObject(input) &&
(Object.getPrototypeOf(input) === Object.prototype ||
Object.getPrototypeOf(input) === null)
);
}

/**
* Validates a JavaScript value for usage as a Firestore value.
*
Expand Down
3 changes: 1 addition & 2 deletions dev/src/transaction.ts
Expand Up @@ -25,15 +25,14 @@ import {
QuerySnapshot,
validateDocumentReference,
} from './reference';
import {isPlainObject} from './serializer';
import {
DocumentData,
Precondition as PublicPrecondition,
ReadOptions,
SetOptions,
UpdateData,
} from './types';
import {isObject, requestTag} from './util';
import {isObject, isPlainObject} from './util';
import {
invalidArgumentMessage,
RequiredArgumentOptions,
Expand Down
19 changes: 19 additions & 0 deletions dev/src/util.ts
Expand Up @@ -14,6 +14,8 @@
* limitations under the License.
*/

import {DocumentData} from './types';

/**
* A Promise implementation that supports deferred resolution.
* @private
Expand Down Expand Up @@ -75,6 +77,23 @@ export function isObject(value: unknown): value is {[k: string]: unknown} {
return Object.prototype.toString.call(value) === '[object Object]';
}

/**
* Verifies that 'obj' is a plain JavaScript object that can be encoded as a
* 'Map' in Firestore.
*
* @private
* @param input The argument to verify.
* @returns 'true' if the input can be a treated as a plain object.
*/
export function isPlainObject(input: unknown): input is DocumentData {
return (
isObject(input) &&
(Object.getPrototypeOf(input) === Object.prototype ||
Object.getPrototypeOf(input) === null ||
input.constructor.name === 'Object')

Choose a reason for hiding this comment

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

According to this stackoverflow post, obj.constructor can be changed by the user, so they recommend using instanceof instead.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Unfortunately, the recommendation here does not quite work for us. We don't have access to the user's type and instanceof Object returns true for custom types as well as plain objects such as {}.

It also looks like the other suggestion Object.prototype.toString.call just returns [object Object] for custom types, so that is likely out of the question too.

);
}

/**
* Returns whether `value` has no custom properties.
*
Expand Down
18 changes: 1 addition & 17 deletions dev/src/validate.ts
Expand Up @@ -37,22 +37,6 @@ export interface NumericRangeOptions {
maxValue?: number;
}

/**
* Returns the name of the base class (ignoring Object).
*
* @private
* @param value The object whose base class name to extract.
* @returns The name of the base class constructor or "Object" if value does not
* extend a custom class.
*/
function extractBaseClassName(value: object): string {
let constructorName = 'Object';
while (Object.getPrototypeOf(value) !== Object.prototype) {
value = Object.getPrototypeOf(value);
constructorName = value.constructor.name;
}
return constructorName;
}
/**
* Generates an error message to use with custom objects that cannot be
* serialized.
Expand All @@ -73,7 +57,7 @@ export function customObjectMessage(
// We use the base class name as the type name as the sentinel classes
// returned by the public FieldValue API are subclasses of FieldValue. By
// using the base name, we reduce the number of special cases below.
const typeName = extractBaseClassName(value);
const typeName = value.constructor.name;
switch (typeName) {
case 'DocumentReference':
case 'FieldPath':
Expand Down
4 changes: 2 additions & 2 deletions dev/src/write-batch.ts
Expand Up @@ -28,7 +28,7 @@ import {Firestore} from './index';
import {logger} from './logger';
import {FieldPath, validateFieldPath} from './path';
import {DocumentReference, validateDocumentReference} from './reference';
import {isPlainObject, Serializer, validateUserInput} from './serializer';
import {Serializer, validateUserInput} from './serializer';
import {Timestamp} from './timestamp';
import {
Precondition as PublicPrecondition,
Expand All @@ -37,7 +37,7 @@ import {
UpdateMap,
} from './types';
import {DocumentData} from './types';
import {isObject, requestTag} from './util';
import {isObject, isPlainObject, requestTag} from './util';
import {
customObjectMessage,
invalidArgumentMessage,
Expand Down
40 changes: 32 additions & 8 deletions dev/test/document.ts
Expand Up @@ -166,18 +166,42 @@ describe('serialize document', () => {
}).to.throw(
'Value for argument "data" is not a valid Firestore document. Couldn\'t serialize object of type "Foo". Firestore doesn\'t support JavaScript objects with custom prototypes (i.e. objects that were created via the "new" operator).'
);

expect(() => {
class Foo {}
class Bar extends Foo {}
firestore
.doc('collectionId/documentId')
.set(new Bar() as InvalidApiUsage);
}).to.throw(
'Value for argument "data" is not a valid Firestore document. Couldn\'t serialize object of type "Bar". Firestore doesn\'t support JavaScript objects with custom prototypes (i.e. objects that were created via the "new" operator).'
);
});

it('supports objects created with Object.create({})', () => {
const overrides: ApiOverride = {
commit: (request, options, callback) => {
requestEquals(
request,
set({
document: document('documentId'),
})
);
callback(null, writeResult(1));
},
};
return createInstance(overrides).then(firestore => {
const plainObject = Object.create({});
return firestore.doc('collectionId/documentId').set(plainObject);
});
});

it('provides custom error for objects from different Firestore instance', () => {
class FieldPath {}
class CustomFieldPath extends FieldPath {}
class VeryCustomFieldPath extends CustomFieldPath {}
class GeoPoint {}
class Timestamp {}

const customClasses = [
new FieldPath(),
new CustomFieldPath(),
new VeryCustomFieldPath(),
];
const customClasses = [new FieldPath(), new GeoPoint(), new Timestamp()];

for (const customClass of customClasses) {
expect(() => {
Expand All @@ -186,7 +210,7 @@ describe('serialize document', () => {
.set(customClass as InvalidApiUsage);
}).to.throw(
'Value for argument "data" is not a valid Firestore document. ' +
'Detected an object of type "FieldPath" that doesn\'t match the expected instance.'
`Detected an object of type "${customClass.constructor.name}" that doesn't match the expected instance.`
);
}
});
Expand Down
2 changes: 1 addition & 1 deletion dev/test/index.ts
Expand Up @@ -1073,7 +1073,7 @@ describe('getAll() method', () => {
expect(actualErrorAttempts).to.deep.eq(expectedErrorAttempts);
});
});
});
}).timeout(5000);

Choose a reason for hiding this comment

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

Still needed?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

This is in master now, so the diff should eventually disappear: https://github.com/googleapis/nodejs-firestore/blob/master/dev/test/index.ts#L1103


it('requires at least one argument', () => {
return createInstance().then(firestore => {
Expand Down