This repository has been archived by the owner on Jan 13, 2019. It is now read-only.
/
Internal.purs
72 lines (52 loc) · 1.83 KB
/
Internal.purs
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
module Conveyor.Internal
( LProxy(..)
, get
, rowToList
, decodeBody
, logError
) where
import Prelude
import Control.Monad.Eff (Eff)
import Control.Monad.Eff.Exception (Error, message, stack)
import Control.Monad.Eff.Unsafe (unsafeCoerceEff)
import Data.Array (head)
import Data.Either (Either(..))
import Data.Foreign (ForeignError(..), MultipleErrors)
import Data.List.NonEmpty (singleton)
import Data.Maybe (Maybe(..), fromMaybe, fromMaybe')
import Data.MediaType (MediaType(..))
import Data.MediaType.Common (applicationJSON)
import Data.StrMap (lookup)
import Data.String (Pattern(..), split)
import Data.Symbol (class IsSymbol, SProxy, reflectSymbol)
import Node.HTTP (Request, requestHeaders)
import Node.Stdout (log)
import Partial.Unsafe (unsafeCrashWith)
import Simple.JSON (class ReadForeign, readJSON)
import Type.Row (class RowToList, kind RowList)
import Unsafe.Coerce (unsafeCoerce)
data LProxy (l :: RowList) = LProxy
get
:: forall l a r1 r2
. IsSymbol l
=> RowCons l a r1 r2
=> SProxy l
-> Record r2
-> a
get l r =
fromMaybe'
(\_ -> unsafeCrashWith ("unsafeGet: missing key " <> show s))
(lookup s (unsafeCoerce r))
where
s = reflectSymbol l
rowToList :: forall proxy r l. RowToList r l => proxy r -> LProxy l
rowToList _ = LProxy
decodeBody :: forall a. ReadForeign a => Request -> String -> Either MultipleErrors a
decodeBody req rawBody =
case lookup "content-type" (requestHeaders req) >>= parseMediaType of
Just mediaType | mediaType == applicationJSON -> readJSON rawBody
_ -> Left $ singleton $ ForeignError "Received unpermitted Content-Type."
parseMediaType :: String -> Maybe MediaType
parseMediaType = split (Pattern ";") >>> head >>> map MediaType
logError :: forall e. Error -> Eff e Unit
logError err = unsafeCoerceEff $ log $ fromMaybe (message err) $ stack err