1+ import { getAuthenticatedUser } from "@/lib/services/authentication-service" ;
2+ import { getSegment } from "@/lib/services/segments-service" ;
3+ import { NextRequest , NextResponse } from "next/server" ;
4+ import { getRepositoriesStorage } from "@/lib/storage/repositories-storage" ;
5+ import { RepositorySort } from "@/lib/services/repositories-service" ;
6+
7+ interface RouteParams {
8+ params : Promise < {
9+ id : string ;
10+ } > ;
11+ }
12+
13+ // Valid sort fields for repositories
14+ const validSortFields = [ "name" , "stars" , "forks" , "updated_at" , "created_at" ] as const ;
15+ type ValidSortField = typeof validSortFields [ number ] ;
16+
17+ export async function GET ( request : NextRequest , { params } : RouteParams ) {
18+ try {
19+ // Get the authenticated user
20+ const user = await getAuthenticatedUser ( ) ;
21+
22+ if ( ! user ) {
23+ return NextResponse . json ( { error : "Unauthorized" } , { status : 401 } ) ;
24+ }
25+
26+ const { id } = await params ;
27+
28+ // Get the segment to verify it exists
29+ const segment = await getSegment ( id ) ;
30+
31+ if ( ! segment ) {
32+ return NextResponse . json ( { error : "Segment not found" } , { status : 404 } ) ;
33+ }
34+
35+ // Extract query parameters for sorting
36+ const searchParams = request . nextUrl . searchParams ;
37+ const sortBy = searchParams . get ( "sortBy" ) ;
38+ const sortDirection = searchParams . get ( "sortDirection" ) ;
39+
40+ // Build sort object if sort parameters are provided
41+ let sort : RepositorySort | undefined ;
42+ if ( sortBy && sortDirection && [ "asc" , "desc" ] . includes ( sortDirection ) ) {
43+ // Validate that sortBy is one of the allowed fields
44+ if ( validSortFields . includes ( sortBy as ValidSortField ) ) {
45+ sort = {
46+ field : sortBy as ValidSortField ,
47+ direction : sortDirection as "asc" | "desc"
48+ } ;
49+ }
50+ }
51+
52+ // Get the repositories from storage using the dedicated method for segment repositories
53+ const storage = getRepositoriesStorage ( ) ;
54+ const repositories = await storage . getRepositoriesBySegmentId ( id , sort ) ;
55+
56+ return NextResponse . json ( repositories ) ;
57+ } catch ( error ) {
58+ const { id } = await params ;
59+ console . error ( `Error fetching repositories for segment ${ id } :` , error ) ;
60+ return NextResponse . json ( { error : "Failed to fetch repositories for segment" } , { status : 500 } ) ;
61+ }
62+ }
0 commit comments