Skip to content

Commit 8fd1cab

Browse files
committed
perf(api): support optional projection in DataLoader batch fns
1 parent e453f3b commit 8fd1cab

1 file changed

Lines changed: 16 additions & 6 deletions

File tree

src/dataLoaders.ts

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -68,27 +68,36 @@ export default class DataLoaders {
6868
* Batching function for resolving entities from their ids
6969
* @param collectionName - collection name to get entities
7070
* @param ids - ids for resolving
71+
* @param projection - optional mongo projection to limit returned fields
7172
*/
7273
private async batchByIds<T extends { _id: ObjectId }>(
7374
collectionName: string,
74-
ids: ReadonlyArray<string>
75+
ids: ReadonlyArray<string>,
76+
projection?: Record<string, 0 | 1>
7577
): Promise<(WithId<T> | null)[]> {
76-
return this.batchByField<T, '_id'>(collectionName, '_id', ids.map(id => new ObjectId(id)));
78+
return this.batchByField<T, '_id'>(
79+
collectionName,
80+
'_id',
81+
ids.map(id => new ObjectId(id)),
82+
projection
83+
);
7784
}
7885

7986
/**
8087
* Batching function for resolving entities by certain field
8188
* @param collectionName - collection name to get entities
8289
* @param fieldName - field name to resolve
8390
* @param values - values for resolving
91+
* @param projection - optional mongo projection to limit returned fields
8492
*/
8593
private async batchByField<
8694
T extends Record<string, any>,
8795
FieldType extends keyof T
8896
>(
8997
collectionName: string,
9098
fieldName: FieldType,
91-
values: ReadonlyArray<T[FieldType]>
99+
values: ReadonlyArray<T[FieldType]>,
100+
projection?: Record<string, 0 | 1>
92101
): Promise<(WithId<T> | null)[]> {
93102
type Doc = WithId<T>;
94103
const valuesMap = new Map<string, FieldType>();
@@ -99,9 +108,10 @@ export default class DataLoaders {
99108

100109
const queryResult = await this.dbConnection
101110
.collection<T>(collectionName)
102-
.find({
103-
[fieldName]: { $in: Array.from(valuesMap.values()) },
104-
} as any)
111+
.find(
112+
{ [fieldName]: { $in: Array.from(valuesMap.values()) } } as any,
113+
projection ? { projection } : {}
114+
)
105115
.toArray();
106116

107117
/**

0 commit comments

Comments
 (0)