Skip to content

Commit

Permalink
feat: support dot-notation attributes in Filter
Browse files Browse the repository at this point in the history
  • Loading branch information
avaly committed Sep 13, 2021
1 parent 6b3c161 commit 52b858e
Show file tree
Hide file tree
Showing 3 changed files with 83 additions and 12 deletions.
5 changes: 4 additions & 1 deletion src/index.ts
Expand Up @@ -430,6 +430,9 @@ export type {
KeysOfAType,
KeysOfOtherType,
IsAny,
OneOrMore
OneOrMore,
Join,
PropertyType,
NestedPaths
} from './mongo_types';
export type { serialize, deserialize } from './bson';
44 changes: 43 additions & 1 deletion src/mongo_types.ts
Expand Up @@ -54,7 +54,7 @@ export type WithoutId<TSchema> = Omit<TSchema, '_id'>;

/** A MongoDB filter can be some portion of the schema or a set of operators @public */
export type Filter<TSchema> = {
[P in keyof TSchema]?: Condition<TSchema[P]>;
[P in Join<NestedPaths<TSchema>, '.'>]?: Condition<PropertyType<TSchema, P>>;
} &
RootFilterOperators<TSchema>;

Expand Down Expand Up @@ -425,3 +425,45 @@ export class TypedEventEmitter<Events extends EventsDescription> extends EventEm

/** @public */
export class CancellationToken extends TypedEventEmitter<{ cancel(): void }> {}

/**
* Helper types for dot-notation filter attributes
*/

/** @public */
export type Join<T extends unknown[], D extends string> = T extends []
? ''
: T extends [string | number | boolean | bigint]
? `${T[0]}`
: T extends [string | number | boolean | bigint, ...infer R]
? `${T[0]}${D}${Join<R, D>}`
: string;

/** @public */
export type PropertyType<T, P extends string> = string extends P
? unknown
: P extends keyof T
? T[P]
: P extends `${infer K}.${infer R}`
? K extends keyof T
? PropertyType<T[K], R>
: unknown
: unknown;

// We dont't support nested circular references
/** @public */
export type NestedPaths<T> = T extends
| string
| number
| boolean
| Date
| ObjectId
| Array<any>
| ReadonlyArray<any>
? []
: // eslint-disable-next-line @typescript-eslint/ban-types
T extends object
? {
[K in Extract<keyof T, string>]: [K, ...NestedPaths<T[K]>];
}[Extract<keyof T, string>]
: [];
46 changes: 36 additions & 10 deletions test/types/community/collection/filterQuery.test-d.ts
Expand Up @@ -15,6 +15,11 @@ const db = client.db('test');
* Test the generic Filter using collection.find<T>() method
*/

interface HumanModel {
_id: ObjectId;
name: string;
}

// a collection model for all possible MongoDB BSON types and TypeScript types
interface PetModel {
_id: ObjectId; // ObjectId field
Expand All @@ -23,14 +28,28 @@ interface PetModel {
age: number; // number field
type: 'dog' | 'cat' | 'fish'; // union field
isCute: boolean; // boolean field
bestFriend?: PetModel; // object field (Embedded/Nested Documents)
bestFriend?: HumanModel; // object field (Embedded/Nested Documents)
createdAt: Date; // date field
treats: string[]; // array of string
playTimePercent: Decimal128; // bson Decimal128 type
readonly friends?: ReadonlyArray<PetModel>; // readonly array of objects
playmates?: PetModel[]; // writable array of objects
readonly friends?: ReadonlyArray<HumanModel>; // readonly array of objects
playmates?: HumanModel[]; // writable array of objects
// Object with multiple nested levels
meta?: {
updatedAt?: Date;
deep?: {
nested?: {
level?: number;
};
};
};
}

const john = {
_id: new ObjectId('577fa2d90c4cc47e31cf4b6a'),
name: 'John'
};

const spot = {
_id: new ObjectId('577fa2d90c4cc47e31cf4b6f'),
name: 'Spot',
Expand Down Expand Up @@ -78,14 +97,25 @@ expectNotType<Filter<PetModel>>({ age: [23, 43] });

/// it should query __nested document__ fields only by exact match
// TODO: we currently cannot enforce field order but field order is important for mongo
await collectionT.find({ bestFriend: spot }).toArray();
await collectionT.find({ bestFriend: john }).toArray();
/// nested documents query should contain all required fields
expectNotType<Filter<PetModel>>({ bestFriend: { family: 'Andersons' } });
expectNotType<Filter<PetModel>>({ bestFriend: { name: 'Andersons' } });
/// it should not accept wrong types for nested document fields
expectNotType<Filter<PetModel>>({ bestFriend: 21 });
expectNotType<Filter<PetModel>>({ bestFriend: 'Andersons' });
expectNotType<Filter<PetModel>>({ bestFriend: [spot] });
expectNotType<Filter<PetModel>>({ bestFriend: [{ family: 'Andersons' }] });
expectNotType<Filter<PetModel>>({ bestFriend: [{ name: 'Andersons' }] });

/// it should query __nested document__ fields using dot-notation
collectionT.find({ 'meta.updatedAt': new Date() });
collectionT.find({ 'meta.deep.nested.level': 123 });
/// it should not accept wrong types for nested document fields
expectNotType<Filter<PetModel>>({ 'meta.updatedAt': 123 });
expectNotType<Filter<PetModel>>({ 'meta.updatedAt': true });
expectNotType<Filter<PetModel>>({ 'meta.updatedAt': 'now' });
expectNotType<Filter<PetModel>>({ 'meta.deep.nested.level': '123' });
expectNotType<Filter<PetModel>>({ 'meta.deep.nested.level': true });
expectNotType<Filter<PetModel>>({ 'meta.deep.nested.level': new Date() });

/// it should query __array__ fields by exact match
await collectionT.find({ treats: ['kibble', 'bone'] }).toArray();
Expand Down Expand Up @@ -227,7 +257,3 @@ await collectionT.find({ playmates: { $elemMatch: { name: 'MrMeow' } } }).toArra
expectNotType<Filter<PetModel>>({ name: { $all: ['world', 'world'] } });
expectNotType<Filter<PetModel>>({ age: { $elemMatch: [1, 2] } });
expectNotType<Filter<PetModel>>({ type: { $size: 2 } });

// dot key case that shows it is assignable even when the referenced key is the wrong type
expectAssignable<Filter<PetModel>>({ 'bestFriend.name': 23 }); // using dot notation permits any type for the key
expectNotType<Filter<PetModel>>({ bestFriend: { name: 23 } });

0 comments on commit 52b858e

Please sign in to comment.