Skip to content

Commit 2f84f50

Browse files
chore: sort by closest result if using location search (#719)
1 parent 9c907e7 commit 2f84f50

File tree

1 file changed

+17
-2
lines changed

1 file changed

+17
-2
lines changed

backend/src/recreation-resource/service/recreation-resource-search.service.ts

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,20 @@ export class RecreationResourceSearchService {
6161
lon,
6262
});
6363

64+
const hasLocation = typeof lat === "number" && typeof lon === "number";
65+
66+
// Distance is used for sorting and is only calculated if lat/lon are provided
67+
const distanceSql = hasLocation
68+
? Prisma.sql`, public.ST_Distance(
69+
public.ST_Transform(public.ST_SetSRID(recreation_site_point, 3005), 3005),
70+
public.ST_Transform(public.ST_SetSRID(public.ST_MakePoint(${lon}, ${lat}), 4326), 3005)
71+
) as distance`
72+
: Prisma.empty;
73+
74+
const orderBySql = hasLocation
75+
? Prisma.sql`order by distance asc, name asc`
76+
: Prisma.sql`order by name asc`;
77+
6478
const [recreationResources, combinedRecordCounts, combinedStaticCounts] =
6579
await this.prisma.$transaction([
6680
this.prisma.$queryRaw<any[]>`
@@ -81,11 +95,12 @@ export class RecreationResourceSearchService {
8195
recreation_structure,
8296
has_toilets,
8397
has_tables
98+
${distanceSql}
8499
from recreation_resource_search_view
85100
${whereClause}
86-
order by name asc
101+
${orderBySql}
87102
limit ${take}
88-
${skip ? Prisma.sql`OFFSET ${skip}` : Prisma.empty};`,
103+
${skip ? Prisma.sql`offset ${skip}` : Prisma.empty};`,
89104

90105
// Query filter menu content and counts that change based on search results
91106
this.prisma.$queryRaw<CombinedRecordCount[]>`

0 commit comments

Comments
 (0)