@@ -27,6 +27,47 @@ type QaApiResponse = {
2727 locale : string ;
2828} ;
2929
30+ function dedupeItems ( items : QaApiResponse [ 'items' ] ) {
31+ const seenById = new Set < string > ( ) ;
32+ const seenByText = new Set < string > ( ) ;
33+ const unique : QaApiResponse [ 'items' ] = [ ] ;
34+
35+ for ( const item of items ) {
36+ if ( seenById . has ( item . id ) ) {
37+ continue ;
38+ }
39+
40+ const textKey = `${ item . locale } :${ item . question . trim ( ) . toLowerCase ( ) } ` ;
41+ if ( seenByText . has ( textKey ) ) {
42+ continue ;
43+ }
44+
45+ seenById . add ( item . id ) ;
46+ seenByText . add ( textKey ) ;
47+ unique . push ( item ) ;
48+ }
49+
50+ return unique ;
51+ }
52+
53+ function normalizeResponse ( data : QaApiResponse , limit : number ) : QaApiResponse {
54+ const uniqueItems = dedupeItems ( data . items ) ;
55+ if ( uniqueItems . length === data . items . length ) {
56+ return data ;
57+ }
58+
59+ const removed = data . items . length - uniqueItems . length ;
60+ const total = Math . max ( 0 , data . total - removed ) ;
61+ const totalPages = Math . ceil ( total / limit ) ;
62+
63+ return {
64+ ...data ,
65+ items : uniqueItems ,
66+ total,
67+ totalPages,
68+ } ;
69+ }
70+
3071export async function GET (
3172 req : Request ,
3273 ctx : { params : Promise < { category : string } > }
@@ -59,9 +100,15 @@ export async function GET(
59100 const cached = await getQaCache < QaApiResponse > ( cacheKey ) ;
60101
61102 if ( cached ) {
62- const response = NextResponse . json ( cached ) ;
103+ const normalizedCached = normalizeResponse ( cached , limit ) ;
104+ const response = NextResponse . json ( normalizedCached ) ;
63105 response . headers . set ( 'Cache-Control' , 'no-store' ) ;
64106 response . headers . set ( 'x-qa-cache' , 'HIT' ) ;
107+
108+ if ( normalizedCached . items . length !== cached . items . length ) {
109+ await setQaCache ( cacheKey , normalizedCached ) ;
110+ }
111+
65112 return response ;
66113 }
67114
@@ -124,23 +171,21 @@ export async function GET(
124171 . limit ( limit )
125172 . offset ( offset ) ;
126173
127- const response = NextResponse . json ( {
174+ const payload = normalizeResponse (
175+ {
128176 items,
129177 total,
130178 page,
131179 totalPages,
132180 locale,
133- } ) ;
181+ } ,
182+ limit
183+ ) ;
184+ const response = NextResponse . json ( payload ) ;
134185 response . headers . set ( 'Cache-Control' , 'no-store' ) ;
135186 response . headers . set ( 'x-qa-cache' , 'MISS' ) ;
136187
137- await setQaCache ( cacheKey , {
138- items,
139- total,
140- page,
141- totalPages,
142- locale,
143- } ) ;
188+ await setQaCache ( cacheKey , payload ) ;
144189
145190 return response ;
146191 } catch ( error ) {
0 commit comments