module Network.API.Builder.Routes
( Route(..)
, URLPiece
, URLParam
, (=.)
, routeURL ) where
import Control.Arrow ((***))
import Data.Monoid ((<>))
import Data.Text (Text)
import qualified Data.Text as T
import qualified Network.HTTP.Base as HTTP (urlEncodeVars)
import qualified Network.HTTP.Types.Method as HTTP
import Network.API.Builder.Query
type URLPiece = Text
type URLParam = [(Text, Text)]
(=.) :: ToQuery a => Text -> a -> [(Text, Text)]
k =. v = toQuery k v
data Route = Route { urlPieces :: [URLPiece]
, urlParams :: [URLParam]
, httpMethod :: HTTP.Method }
deriving (Show, Read, Eq)
routeURL :: Text
-> Route
-> Text
routeURL baseURL (Route fs ps _) =
baseURL <> firstSep <> path <> querySep <> buildParams ps
where
firstSep = if null fs then T.empty else "/"
path = T.intercalate "/" fs
querySep = if null ps then T.empty else pathParamsSep fs
pathParamsSep :: [URLPiece] -> Text
pathParamsSep [] = "?"
pathParamsSep xs = if T.isInfixOf "." (last xs) then "?" else "/?"
buildParams :: [URLParam] -> Text
buildParams = T.pack . HTTP.urlEncodeVars . concatMap (map (T.unpack *** T.unpack))