11import { NextResponse } from "next/server" ;
22import { Redis } from "@upstash/redis" ;
3+ import { fetchActiveListings } from "~~/services/marketplace/graphql" ;
34
45const redis = Redis . fromEnv ( ) ;
56const GEO_KEY = "locations:geo" ;
@@ -13,6 +14,33 @@ function idFor(lat: number, lng: number, miles: number) {
1314 return `loc:${ lat . toFixed ( 5 ) } :${ lng . toFixed ( 5 ) } :${ miles . toFixed ( 2 ) } ` ;
1415}
1516
17+ async function getListingCountsByLocation ( ) : Promise < Record < string , number > > {
18+ try {
19+ const items = await fetchActiveListings ( ) ;
20+
21+ if ( items . length === 0 ) {
22+ return { } ;
23+ }
24+
25+ const counts : Record < string , number > = { } ;
26+
27+ for ( const item of items ) {
28+ const locationId = item ?. locationId ;
29+ if ( locationId && typeof locationId === "string" ) {
30+ const normalizedId = locationId . trim ( ) ;
31+ if ( normalizedId ) {
32+ counts [ normalizedId ] = ( counts [ normalizedId ] || 0 ) + 1 ;
33+ }
34+ }
35+ }
36+
37+ return counts ;
38+ } catch ( error : any ) {
39+ console . error ( "[getListingCountsByLocation] Error:" , error ?. message || String ( error ) ) ;
40+ return { } ;
41+ }
42+ }
43+
1644export async function GET ( req : Request ) {
1745 try {
1846 const { searchParams } = new URL ( req . url ) ;
@@ -83,6 +111,27 @@ export async function GET(req: Request) {
83111 return name . includes ( q ) || id . includes ( q ) || akaMatch ;
84112 } ) ;
85113 }
114+
115+ const listingCounts = await getListingCountsByLocation ( ) ;
116+
117+ locations = locations . map ( ( loc : any ) => {
118+ const locationId = String ( loc ?. id || "" ) . trim ( ) ;
119+ const count = locationId ? listingCounts [ locationId ] || 0 : 0 ;
120+
121+ return { ...loc , activeListingsCount : count } ;
122+ } ) ;
123+
124+ locations . sort ( ( a : any , b : any ) => {
125+ const countA = a . activeListingsCount || 0 ;
126+ const countB = b . activeListingsCount || 0 ;
127+ if ( countB !== countA ) {
128+ return countB - countA ;
129+ }
130+ const nameA = ( a . name || a . id || "" ) . toLowerCase ( ) ;
131+ const nameB = ( b . name || b . id || "" ) . toLowerCase ( ) ;
132+ return nameA . localeCompare ( nameB ) ;
133+ } ) ;
134+
86135 return NextResponse . json ( { locations : locations . slice ( 0 , limit ) } ) ;
87136 } catch ( e : any ) {
88137 if ( String ( e ?. message || "" ) . includes ( "Unexpected non-whitespace character after JSON" ) ) {
0 commit comments