11import { useEffect , useState } from 'react'
22import { ArrowSquareOut , ChatCircle , ArrowUp , Clock } from '@phosphor-icons/react'
33
4+ interface AlgoliaStory {
5+ objectID : string
6+ title : string
7+ url ?: string
8+ points : number
9+ author : string
10+ created_at_i : number
11+ num_comments ?: number
12+ }
13+
414interface HNStory {
515 id : number
616 title : string
@@ -22,22 +32,33 @@ function App() {
2232 setLoading ( true )
2333 setError ( null )
2434
25- // Fetch top story IDs
26- const idsResponse = await fetch ( 'https://hacker-news.firebaseio.com/v0/topstories.json' )
27- if ( ! idsResponse . ok ) throw new Error ( 'Failed to fetch story IDs' )
28-
29- const allIds : number [ ] = await idsResponse . json ( )
30- const topIds = allIds . slice ( 0 , 30 ) // Get first 30 stories
31-
32- // Fetch individual stories in parallel
33- const storyPromises = topIds . map ( async ( id ) => {
34- const response = await fetch ( `https://hacker-news.firebaseio.com/v0/item/${ id } .json` )
35- if ( ! response . ok ) throw new Error ( `Failed to fetch story ${ id } ` )
36- return response . json ( )
37- } )
38-
39- const fetchedStories = await Promise . all ( storyPromises )
40- setStories ( fetchedStories )
35+ // Calculate timestamp for three months ago
36+ const threeMonthsAgo = Math . floor ( Date . now ( ) / 1000 ) - ( 90 * 24 * 60 * 60 )
37+
38+ // Fetch top stories from last three months using Algolia
39+ const response = await fetch (
40+ `https://hn.algolia.com/api/v1/search?tags=story&numericFilters=created_at_i>${ threeMonthsAgo } &hitsPerPage=30`
41+ )
42+ if ( ! response . ok ) throw new Error ( 'Failed to fetch stories' )
43+
44+ const data = await response . json ( )
45+ const algoliaStories : AlgoliaStory [ ] = data . hits
46+
47+ // Convert Algolia format to our HNStory format
48+ const convertedStories : HNStory [ ] = algoliaStories
49+ . filter ( story => story . title && story . points ) // Filter out stories without title or points
50+ . map ( story => ( {
51+ id : parseInt ( story . objectID ) ,
52+ title : story . title ,
53+ url : story . url ,
54+ score : story . points ,
55+ by : story . author ,
56+ time : story . created_at_i ,
57+ descendants : story . num_comments
58+ } ) )
59+ . sort ( ( a , b ) => b . score - a . score ) // Sort by score descending
60+
61+ setStories ( convertedStories )
4162 } catch ( err ) {
4263 setError ( err instanceof Error ? err . message : 'Something went wrong' )
4364 } finally {
@@ -96,7 +117,7 @@ function App() {
96117 Calm HN
97118 </ h1 >
98119 < p className = "text-slate-500 text-[10px] mt-2 uppercase tracking-wider" >
99- Top stories
120+ Top stories from the last three months
100121 </ p >
101122 </ header >
102123
0 commit comments