-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGetServerSideProps.purs
More file actions
81 lines (71 loc) · 2.51 KB
/
GetServerSideProps.purs
File metadata and controls
81 lines (71 loc) · 2.51 KB
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
module Next.GetServerSideProps where
import Prelude hiding (top)
import Control.Promise (Promise)
import Control.Promise as Promise
import Data.Either (Either(..))
import Data.Maybe (Maybe)
import Data.Semigroup.Foldable (intercalateMap)
import Effect.Aff (Aff)
import Effect.Uncurried (EffectFn1, mkEffectFn1)
import Foreign (Foreign, renderForeignError)
import Foreign.Object (Object)
import Next.SerialisedProps (SerialisedProps)
import Partial.Unsafe (unsafeCrashWith)
import Prim.Row (class Union)
import Unsafe.Coerce (unsafeCoerce)
import Yoga.JSON (class ReadForeign, class WriteForeign, read, write, writeJSON)
type ServerSidePropsContext params =
{ params ∷ Maybe { | params }
, req ∷ Foreign -- IncomingMessage
, res ∷ Foreign -- HTTP response object
, query ∷ Object String
, preview ∷ Maybe Boolean
, resolvedUrl ∷ String
, locale ∷ Maybe Locale
, locales ∷ Maybe (Array Locale)
, defaultLocale ∷ Maybe Locale
}
-- [TODO]: Move to a separate file
newtype Locale = Locale String
derive newtype instance ReadForeign Locale
derive newtype instance WriteForeign Locale
type ServerSideProps props =
( props ∷ props
, redirect ∷ { destination ∷ String, permanent ∷ Boolean }
, notFound ∷ Boolean
)
foreign import data GetServerSideProps ∷ Type → Type → Type
toGetServerSideProps
∷ ∀ partialProps componentProps params
. (EffectFn1 Foreign (Promise partialProps))
→ GetServerSideProps params componentProps
toGetServerSideProps = unsafeCoerce
decodeContextOrCrash ∷ ∀ a. ReadForeign a ⇒ Foreign → a
decodeContextOrCrash fgn =
case read fgn of
Right value → value
Left errors →
unsafeCrashWith
$ "Invalid context received in getServerSideProps:\n"
<> intercalateMap "\n" renderForeignError errors
mkGetServerSideProps
∷ ∀ props p p_ params
. Union p p_ (ServerSideProps props)
⇒ ReadForeign { | params }
⇒ ReadForeign { | p }
⇒ WriteForeign props
⇒ WriteForeign { props ∷ { serialisedProps ∷ String } | p }
⇒ (ServerSidePropsContext params → Aff { props ∷ props | p })
→ GetServerSideProps { | params } (SerialisedProps props)
mkGetServerSideProps constructProps =
toGetServerSideProps
$ mkEffectFn1
( Promise.fromAff
<<< (map write)
<<<
( map \x →
(x { props = { serialisedProps: writeJSON x.props } ∷ SerialisedProps props })
)
<<< constructProps
<<< decodeContextOrCrash
)