-
-
Notifications
You must be signed in to change notification settings - Fork 62
/
Copy pathPagination.hs
102 lines (84 loc) · 2.76 KB
/
Pagination.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
module Glot.Pagination
( Pagination(..)
, paginationRequired
, PageData(..)
, fromPageData
, PageLink(..)
, toPageLinks
) where
import Prelude
import Data.Int (Int64)
import Data.Text (Text)
import qualified Data.Maybe as Maybe
import qualified Data.Text as Text
data Pagination = Pagination {
paginationNextPage :: Maybe Text,
paginationPrevPage :: Maybe Text,
paginationFirstPage :: Maybe Text,
paginationLastPage :: Maybe Text
} deriving (Show)
paginationRequired :: Pagination -> Bool
paginationRequired p = hasNext || hasPrev
where hasNext = Maybe.isJust $ paginationNextPage p
hasPrev = Maybe.isJust $ paginationPrevPage p
data PageLink = PageLink
{ pageLinkRel :: Text
, pageLinkPage :: Text
}
toPageLinks :: Pagination -> [PageLink]
toPageLinks Pagination{..} =
Maybe.catMaybes
[ fmap (PageLink "next") paginationNextPage
, fmap (PageLink "prev") paginationPrevPage
, fmap (PageLink "first") paginationFirstPage
, fmap (PageLink "last") paginationLastPage
]
data PageData = PageData
{ currentPage :: Int
, totalEntries :: Int64
, entriesPerPage :: Int
}
fromPageData :: PageData -> Pagination
fromPageData PageData{..} =
let
totalPages =
ceiling (fromIntegral totalEntries / fromIntegral entriesPerPage :: Double)
in
if currentPage > totalPages then
Pagination
{ paginationNextPage = Nothing
, paginationPrevPage = Nothing
, paginationFirstPage = Nothing
, paginationLastPage = Nothing
}
else if currentPage == 1 && totalPages == 1 then
Pagination
{ paginationNextPage = Nothing
, paginationPrevPage = Nothing
, paginationFirstPage = Nothing
, paginationLastPage = Just (intToText totalPages)
}
else if currentPage == 1 && totalPages > 1 then
Pagination
{ paginationNextPage = Just "2"
, paginationPrevPage = Nothing
, paginationFirstPage = Nothing
, paginationLastPage = Just (intToText totalPages)
}
else if currentPage == totalPages then
Pagination
{ paginationNextPage = Nothing
, paginationPrevPage = Just (intToText (currentPage - 1))
, paginationFirstPage = Just "1"
, paginationLastPage = Nothing
}
else
Pagination
{ paginationNextPage = Just (intToText (currentPage + 1))
, paginationPrevPage = Just (intToText (currentPage - 1))
, paginationFirstPage = Just "1"
, paginationLastPage = Just (intToText totalPages)
}
intToText :: Int -> Text
intToText n =
Text.pack (show n)