-
-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathAreaDataSource.ts
More file actions
270 lines (250 loc) · 8.23 KB
/
AreaDataSource.ts
File metadata and controls
270 lines (250 loc) · 8.23 KB
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
import { MongoDataSource } from 'apollo-datasource-mongodb'
import { Filter } from 'mongodb'
import muuid from 'uuid-mongodb'
import bboxPolygon from '@turf/bbox-polygon'
import { getAreaModel, getMediaModel, getMediaObjectModel } from '../db/index.js'
import { AreaType } from '../db/AreaTypes'
import { GQLFilter, AreaFilterParams, PathTokenParams, LeafStatusParams, ComparisonFilterParams, StatisticsType, CragsNear, BBoxType } from '../types'
import { getClimbModel } from '../db/ClimbSchema.js'
import { ClimbGQLQueryType, ClimbType } from '../db/ClimbTypes.js'
import { logger } from '../logger.js'
export default class AreaDataSource extends MongoDataSource<AreaType> {
areaModel = getAreaModel()
climbModel = getClimbModel()
tagModel = getMediaModel()
mediaObjectModal = getMediaObjectModel()
async findAreasByFilter (filters?: GQLFilter): Promise<any> {
let mongoFilter: any = {}
if (filters !== undefined) {
mongoFilter = Object.entries(filters).reduce<Filter<AreaType>>((acc, [key, filter]): Filter<AreaType> => {
switch (key) {
case 'area_name': {
const areaFilter = (filter as AreaFilterParams)
const param = areaFilter.exactMatch !== true ? new RegExp(areaFilter.match, 'ig') : areaFilter.match
acc.area_name = param
break
}
case 'leaf_status': {
const leafFilter = filter as LeafStatusParams
acc['metadata.leaf'] = leafFilter.isLeaf
break
}
// Add score conversion to climbs
case 'path_tokens': {
const pathFilter = filter as PathTokenParams
if (pathFilter.exactMatch === true) {
acc.pathTokens = pathFilter.tokens
} else {
const filter: Record<string, any> = {}
filter.$all = pathFilter.tokens
if (pathFilter.size !== undefined) {
filter.$size = pathFilter.size
}
acc.pathTokens = filter
}
break
}
case 'field_compare': {
const comparisons = {}
for (const f of filter as ComparisonFilterParams[]) {
const { field, num, comparison } = f
const currFiled = comparisons[field]
if (currFiled === undefined) {
comparisons[field] = { [`$${comparison}`]: num }
} else {
comparisons[field] = { ...currFiled, [`$${comparison}`]: num }
}
acc = { ...acc, ...comparisons }
}
break
}
default:
break
}
return acc
}, {})
}
mongoFilter._deleting = { $eq: null } // marked for deletion
// Todo: figure whether we need to populate 'climbs' array
return this.collection.find(mongoFilter)
}
async findManyByPathHash (pathHashes: string[]): Promise<any> {
return await this.collection.aggregate([
{ $match: { pathHash: { $in: pathHashes } } },
{ $addFields: { __order: { $indexOfArray: [pathHashes, '$pathHash'] } } },
{ $sort: { __order: 1 } }
]).toArray()
}
async listAllCountries (): Promise<any> {
try {
return await this.areaModel.find({ pathTokens: { $size: 1 } }).lean()
} catch (e) {
logger.error(e)
return []
}
}
async findOneAreaByUUID (uuid: muuid.MUUID): Promise<AreaType> {
const rs = await this.areaModel
.aggregate([
{ $match: { 'metadata.area_id': uuid, _deleting: { $exists: false } } },
{
$lookup: {
from: 'climbs', // other collection name
localField: 'climbs',
foreignField: '_id',
as: 'climbs' // clobber array of climb IDs with climb objects
}
},
{
$set: {
'climbs.gradeContext': '$gradeContext' // manually set area's grade context to climb
}
}
])
if (rs != null && rs.length === 1) {
return rs[0]
}
throw new Error(`Area ${uuid.toUUID().toString()} not found.`)
}
async findManyClimbsByUuids (uuidList: muuid.MUUID[]): Promise<ClimbType[]> {
const rs = await this.climbModel.find().where('_id').in(uuidList)
return rs
}
/**
* Find a climb by uuid. Also return the parent area object (crag or boulder).
*
* SQL equivalent:
* ```sql
* SELECT
* climbs.*,
* areas.ancestors as ancestors,
* areas.pathTokens as pathTokens,
* (select * from areas) as parent
* FROM climbs, areas
* WHERE
* climbs.metadata.areaRef == areas.metadata.area_id
* ```
* @param uuid climb uuid
*/
async findOneClimbByUUID (uuid: muuid.MUUID): Promise<ClimbGQLQueryType | null> {
const rs = await this.climbModel
.aggregate([
{ $match: { _id: uuid } },
{
$lookup: {
from: 'areas', // other collection name
localField: 'metadata.areaRef',
foreignField: 'metadata.area_id',
as: 'parent' // add a new parent field
}
},
{ $unwind: '$parent' }, // Previous stage returns as an array of 1 element. 'unwind' turn it into an object.
{
$set: {
// create aliases
pathTokens: '$parent.pathTokens',
ancestors: '$parent.ancestors'
}
}
])
if (rs != null && rs?.length === 1) {
return rs[0]
}
return null
}
/**
* Find all descendants (inclusive) starting from path
* @param path comma-separated _id's of area
* @param isLeaf
* @returns array of areas
*/
async findDescendantsByPath (path: string, isLeaf: boolean = false): Promise<AreaType[]> {
const regex = new RegExp(`^${path}`)
const data = this.collection.find({ ancestors: regex, 'metadata.leaf': isLeaf })
return await data.toArray()
}
/**
* Get whole db stats
* @returns
*/
async getStats (): Promise<StatisticsType> {
const stats = {
totalClimbs: 0,
totalCrags: 0
}
const agg1 = await this.climbModel.countDocuments()
const agg2 = await this.areaModel.aggregate([{ $match: { 'metadata.leaf': true } }])
.count('totalCrags')
if (agg2.length === 1) {
const totalClimbs = agg1
const totalCrags = agg2[0].totalCrags
return {
totalClimbs,
totalCrags
}
}
return stats
}
async getCragsNear (
placeId: string,
lnglat: [number, number],
minDistance: number,
maxDistance: number,
includeCrags: boolean = false): Promise<CragsNear[]> {
const rs = await this.areaModel.aggregate([
{
$geoNear: {
near: { type: 'Point', coordinates: lnglat },
key: 'metadata.lnglat',
distanceField: 'distance',
distanceMultiplier: 0.001,
minDistance,
maxDistance,
query: { 'metadata.leaf': true },
spherical: true
}
},
{
// Exclude climbs in this crag to reduce result size.
// This will result in climbs: null
// We'll set them to [] in the end to avoid potential unexpected null problems.
$unset: ['climbs']
},
{
// group result by 'distance' from center
$bucket: {
groupBy: '$distance',
boundaries: [
0, 48, 96, 160, 240
],
default: 'theRest',
output: {
count: {
$sum: 1
},
// Only include crags data (a lot) if needed
crags: {
$push: includeCrags ? '$$ROOT' : ''
}
}
}
},
{ $unset: 'crags.distance' }, // remove 'distance' field
{ $set: { 'crags.climbs': [] } }, // set to empty []
// this is a hack to add an arbitrary token to make the graphql result uniquely identifiable for Apollo client-side cache. Todo: look for a better way as this could be potential injection.
{ $addFields: { placeId } }])
return rs
}
async findCragsWithin (bbox: BBoxType, zoom: number): Promise<any> {
const polygon = bboxPolygon(bbox)
const filter = {
'metadata.lnglat': {
$geoWithin: {
$geometry: polygon.geometry
}
},
'metadata.leaf': zoom >= 11
}
return await this.areaModel.find(filter).lean()
}
}