Skip to content

Commit 55373ba

Browse files
committed
Fix self posts on HN
1 parent 217cdd0 commit 55373ba

File tree

2 files changed

+22
-3
lines changed

2 files changed

+22
-3
lines changed

.ghci

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
:set -isrc -itests
1+
:set -isrc -itests -XOverloadedStrings

src/NumberSix/Handlers/HackerNews.hs

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import Control.Monad (mzero)
1212
import Control.Monad.Trans (liftIO)
1313
import Data.Aeson (FromJSON (..), Value (..), (.:))
1414
import Data.ByteString (ByteString)
15+
import qualified Data.ByteString.Char8 as BC
1516

1617

1718
--------------------------------------------------------------------------------
@@ -28,10 +29,28 @@ data HackerNews = HackerNews [Item] deriving (Show)
2829

2930
--------------------------------------------------------------------------------
3031
instance FromJSON HackerNews where
31-
parseJSON (Object o) = HackerNews <$> o .: "items"
32+
parseJSON (Object o) = resolveSelfPosts . HackerNews <$> o .: "items"
3233
parseJSON _ = mzero
3334

3435

36+
--------------------------------------------------------------------------------
37+
-- | Make an URLs in items absolute if needed
38+
--
39+
-- The HN api returns
40+
--
41+
-- > /comments/1234
42+
--
43+
-- as URL for these links, and we need
44+
--
45+
-- > http://news.ycombinator.com/item?id=1234
46+
resolveSelfPosts :: HackerNews -> HackerNews
47+
resolveSelfPosts (HackerNews items) = HackerNews $ map resolve items
48+
where
49+
resolve (Item title url) = Item title $ case (BC.split '/' url) of
50+
["", "comments", nr] -> "http://news.ycombinator.com/item?id=" <> nr
51+
_ -> url
52+
53+
3554
--------------------------------------------------------------------------------
3655
data Item = Item ByteString ByteString deriving (Show)
3756

@@ -50,7 +69,7 @@ hackerNews query = do
5069
Right (HackerNews items) ->
5170
let Item title url = items !! idx
5271
in textAndUrl title url
53-
_ -> return "Something went wrong"
72+
_ -> return "Error: data center on fire"
5473
where
5574
idx = case readByteString query of
5675
Just n -> n - 1

0 commit comments

Comments
 (0)