purescript-httpurple/src/HTTPure/Headers.purs

70 lines
2.2 KiB
Haskell
Raw Normal View History

module HTTPure.Headers
( Headers
, empty
2017-09-26 06:08:07 +00:00
, headers
, header
2017-09-26 06:08:07 +00:00
, read
, write
) where
import Prelude
import Effect as Effect
import Foreign.Object as Object
import Data.String as String
2017-09-26 06:08:07 +00:00
import Data.TraversableWithIndex as TraversableWithIndex
import Data.Tuple as Tuple
import Node.HTTP as HTTP
2017-09-26 06:08:07 +00:00
import HTTPure.Lookup as Lookup
import HTTPure.Lookup ((!!))
2017-09-26 06:08:07 +00:00
-- | The `Headers` type is just sugar for a `Object` of `Strings`
-- | that represents the set of headers in an HTTP request or response.
newtype Headers = Headers (Object.Object String)
2017-09-26 06:08:07 +00:00
-- | Given a string, return a `Maybe` containing the value of the matching
-- | header, if there is any.
instance lookup :: Lookup.Lookup Headers String String where
lookup (Headers headers') key = headers' !! String.toLower key
2017-09-26 06:08:07 +00:00
2017-09-26 14:47:05 +00:00
-- | Allow a `Headers` to be represented as a string. This string is formatted
-- | in HTTP headers format.
instance show :: Show Headers where
2017-09-26 06:08:07 +00:00
show (Headers headers') =
Object.foldMap showField headers' <> "\n"
2017-09-26 06:08:07 +00:00
where
showField key value = key <> ": " <> value <> "\n"
-- | Compare two `Headers` objects by comparing the underlying `Objects`.
instance eq :: Eq Headers where
2017-09-26 06:08:07 +00:00
eq (Headers a) (Headers b) = eq a b
2017-07-18 01:51:43 +00:00
2017-09-27 19:34:00 +00:00
-- | Allow one `Headers` objects to be appended to another.
instance semigroup :: Semigroup Headers where
append (Headers a) (Headers b) = Headers $ Object.union b a
2017-09-27 19:34:00 +00:00
2017-09-26 14:47:05 +00:00
-- | Get the headers out of a HTTP `Request` object.
2017-09-26 06:08:07 +00:00
read :: HTTP.Request -> Headers
read = HTTP.requestHeaders >>> Headers
2017-09-26 14:47:05 +00:00
-- | Given an HTTP `Response` and a `Headers` object, return an effect that will
-- | write the `Headers` to the `Response`.
write :: HTTP.Response ->
2017-07-18 05:25:14 +00:00
Headers ->
Effect.Effect Unit
2017-09-26 06:08:07 +00:00
write response (Headers headers') = void $
TraversableWithIndex.traverseWithIndex (HTTP.setHeader response) headers'
-- | Return a `Headers` containing nothing.
empty :: Headers
empty = Headers Object.empty
2017-09-26 14:47:05 +00:00
-- | Convert an `Array` of `Tuples` of 2 `Strings` to a `Headers` object.
2017-09-26 06:08:07 +00:00
headers :: Array (Tuple.Tuple String String) -> Headers
headers = Object.fromFoldable >>> Headers
-- | Create a singleton header from a key-value pair.
header :: String -> String -> Headers
header key = Object.singleton key >>> Headers