-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
query.forGoogleMaps.handler.ts
72 lines (65 loc) · 2.1 KB
/
query.forGoogleMaps.handler.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import { TRPCError } from '@trpc/server'
import { getBounds, getCenterOfBounds } from 'geolib'
import { prisma } from '@weareinreach/db'
import { handleError } from '~api/lib'
import { globalWhere } from '~api/selects/global'
import { type TRPCHandlerParams } from '~api/types/handler'
import { type TForGoogleMapsSchema } from './query.forGoogleMaps.schema'
const getBoundary = (coords: { latitude: number; longitude: number }[]): google.maps.LatLngBoundsLiteral => {
const bounds = getBounds(coords)
return {
north: bounds.maxLat,
east: bounds.maxLng,
south: bounds.minLat,
west: bounds.minLng,
}
}
const getCenter = (coords: { latitude: number; longitude: number }[]): google.maps.LatLngLiteral => {
const center = getCenterOfBounds(coords)
return { lat: center.latitude, lng: center.longitude }
}
const forGoogleMaps = async ({ input, ctx }: TRPCHandlerParams<TForGoogleMapsSchema>) => {
try {
const { locationIds, isEditMode } = input
const canSeeAll = isEditMode && !!ctx.session?.user?.permissions
const result = await prisma.orgLocation.findMany({
where: {
...(!canSeeAll && globalWhere.isPublic()),
id: { in: locationIds },
AND: [{ latitude: { not: 0 } }, { longitude: { not: 0 } }],
},
select: {
id: true,
name: true,
latitude: true,
longitude: true,
},
})
if (!result.length) {
throw new TRPCError({ code: 'NOT_FOUND' })
}
const coordsForBounds: { latitude: number; longitude: number }[] = []
for (const { latitude, longitude } of result) {
if (latitude && longitude) {
coordsForBounds.push({ latitude, longitude })
}
}
const bounds = result.length > 1 ? getBoundary(coordsForBounds) : null
const singleLat = result.at(0)?.latitude
const singleLon = result.at(0)?.longitude
const center =
result.length === 1 && singleLat && singleLon
? ({ lat: singleLat, lng: singleLon } satisfies google.maps.LatLngLiteral)
: getCenter(coordsForBounds)
const zoom = result.length === 1 ? 17 : null
return {
locations: result,
bounds,
center,
zoom,
}
} catch (e) {
return handleError(e)
}
}
export default forGoogleMaps