/
GeoJoinerGet.ts
52 lines (46 loc) · 1.97 KB
/
GeoJoinerGet.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import { GeoFirestoreTypes } from './GeoFirestoreTypes';
import { GeoQuerySnapshot } from './GeoQuerySnapshot';
import { validateQueryCriteria, calculateDistance } from './utils';
/**
* A `GeoJoinerGet` aggregates multiple `get` results.
*/
export class GeoJoinerGet {
private _docs: Map<string, GeoFirestoreTypes.web.QueryDocumentSnapshot> = new Map();
/**
* @param snapshots An array of snpashots from a Firestore Query `get` call.
* @param _queryCriteria The query criteria of geo based queries, includes field such as center, radius, and limit.
*/
constructor(snapshots: GeoFirestoreTypes.web.QuerySnapshot[], private _queryCriteria: GeoFirestoreTypes.QueryCriteria) {
validateQueryCriteria(_queryCriteria);
snapshots.forEach((snapshot: GeoFirestoreTypes.web.QuerySnapshot) => {
snapshot.docs.forEach((doc) => {
const distance = calculateDistance(this._queryCriteria.center, doc.data().l);
if (this._queryCriteria.radius >= distance) {
this._docs.set(doc.id, doc);
}
});
});
if (this._queryCriteria.limit && this._docs.size > this._queryCriteria.limit) {
const arrayToLimit = Array.from(this._docs.values()).map((doc) => {
return { distance: calculateDistance(this._queryCriteria.center, doc.data().l), id: doc.id };
}).sort((a, b) => a.distance - b.distance);
for (let i = this._queryCriteria.limit; i < arrayToLimit.length; i++) {
this._docs.delete(arrayToLimit[i].id);
}
}
}
/**
* Returns parsed docs as a GeoQuerySnapshot.
*
* @return A new `GeoQuerySnapshot` of the filtered documents from the `get`.
*/
public getGeoQuerySnapshot(): GeoQuerySnapshot {
const docs = Array.from(this._docs.values());
return new GeoQuerySnapshot(
{ docs, docChanges: () => docs.map((doc, index) => {
return { doc, newIndex: index, oldIndex: -1, type: 'added' };
}) } as GeoFirestoreTypes.web.QuerySnapshot,
this._queryCriteria.center
);
}
}