on master help sign in
Merge pull request #1390 from Profpatsch/document-servant-foreign
d06b65cCaroline GAUDREAU
servant-foreign/src/Servant/Foreign.hs+22−19
@@ -1,20 +1,32 @@
1-- | Generalizes all the data needed to make code generation work with
1-- | Generalizes all the data needed to make code generation work with
2-- arbitrary programming languages.
2-- arbitrary programming languages.
3+--
4+-- See documentation of 'HasForeignType' for a simple example. 'listFromAPI' returns a list of all your endpoints and their foreign types, given a mapping from Haskell types to foreign types (conventionally called `ftypes` below).
3module Servant.Foreign
5module Servant.Foreign
4− ( ArgType(..)
6+ (
5− , HeaderArg(..)
7+ -- * Main API
6− , QueryArg(..)
8+ listFromAPI
7 , Req(..)
9 , Req(..)
8− , ReqBodyContentType(..)
10+ , defReq
9− , Segment(..)
11+ , HasForeignType(..)
10− , SegmentType(..)
12+ , GenerateList(..)
13+ , HasForeign(..)
14+ , NoTypes
15+ -- * Subtypes of 'Req'
11 , Url(..)
16 , Url(..)
12− -- aliases
13 , Path
17 , Path
18+ , Segment(..)
19+ , SegmentType(..)
20+ , isCapture
21+ , captureArg
22+ , QueryArg(..)
23+ , ArgType(..)
24+ , HeaderArg(..)
14 , Arg(..)
25 , Arg(..)
15 , FunctionName(..)
26 , FunctionName(..)
27+ , ReqBodyContentType(..)
16 , PathSegment(..)
28 , PathSegment(..)
17− -- lenses
29+ -- * Lenses
18 , argName
30 , argName
19 , argType
31 , argType
20 , argPath
32 , argPath
@@ -30,7 +42,7 @@ module Servant.Foreign
30 , queryArgName
42 , queryArgName
31 , queryArgType
43 , queryArgType
32 , headerArg
44 , headerArg
33− -- prisms
45+ -- * Prisms
34 , _PathSegment
46 , _PathSegment
35 , _HeaderArg
47 , _HeaderArg
36 , _ReplaceHeaderArg
48 , _ReplaceHeaderArg
@@ -39,16 +51,7 @@ module Servant.Foreign
39 , _Normal
51 , _Normal
40 , _Flag
52 , _Flag
41 , _List
53 , _List
42− -- rest of it
43− , HasForeign(..)
44− , HasForeignType(..)
45− , GenerateList(..)
46− , NoTypes
47− , captureArg
48− , isCapture
49− , defReq
50− , listFromAPI
51− -- re-exports
54+ -- * Re-exports
52 , module Servant.API
55 , module Servant.API
53 , module Servant.Foreign.Inflections
56 , module Servant.Foreign.Inflections
54 ) where
57 ) where
servant-foreign/src/Servant/Foreign/Inflections.hs+18−12
@@ -20,20 +20,31 @@ import Prelude hiding
20 (head, tail)
20 (head, tail)
21import Servant.Foreign.Internal
21import Servant.Foreign.Internal
22
22
23+-- | Simply concat each part of the FunctionName together.
24+--
25+-- @[ "get", "documents", "by", "id" ] → "getdocumentsbyid"@
26+concatCase :: FunctionName -> Text
27+concatCase = view concatCaseL
28+
23concatCaseL :: Getter FunctionName Text
29concatCaseL :: Getter FunctionName Text
24concatCaseL = _FunctionName . to mconcat
30concatCaseL = _FunctionName . to mconcat
25
31
26−-- | Function name builder that simply concat each part together
32+-- | Use the snake_case convention.
33+-- Each part is separated by a single underscore character.
34+--
35+-- @[ "get", "documents", "by", "id" ] → "get_documents_by_id"@
27−concatCase :: FunctionName -> Text
36+snakeCase :: FunctionName -> Text
28−concatCase = view concatCaseL
37+snakeCase = view snakeCaseL
29
38
30snakeCaseL :: Getter FunctionName Text
39snakeCaseL :: Getter FunctionName Text
31snakeCaseL = _FunctionName . to (intercalate "_")
40snakeCaseL = _FunctionName . to (intercalate "_")
32
41
33−-- | Function name builder using the snake_case convention.
42+-- | Use the camelCase convention.
34−-- each part is separated by a single underscore character.
43+-- The first part is lower case, every other part starts with an upper case character.
44+--
45+-- @[ "get", "documents", "by", "id" ] → "getDocumentsById"@
35−snakeCase :: FunctionName -> Text
46+camelCase :: FunctionName -> Text
36−snakeCase = view snakeCaseL
47+camelCase = view camelCaseL
37
48
38camelCaseL :: Getter FunctionName Text
49camelCaseL :: Getter FunctionName Text
39camelCaseL = _FunctionName . to convert
50camelCaseL = _FunctionName . to convert
@@ -42,8 +53,3 @@ camelCaseL = _FunctionName . to convert
42 convert (p:ps) = mconcat $ p : map capitalize ps
53 convert (p:ps) = mconcat $ p : map capitalize ps
43 capitalize "" = ""
54 capitalize "" = ""
44 capitalize name = C.toUpper (head name) `cons` tail name
55 capitalize name = C.toUpper (head name) `cons` tail name
45−
46−-- | Function name builder using the CamelCase convention.
47−-- each part begins with an upper case character.
48−camelCase :: FunctionName -> Text
49−camelCase = view camelCaseL
servant-foreign/src/Servant/Foreign/Internal.hs+122−34
@@ -13,8 +13,6 @@
13{-# LANGUAGE TypeOperators #-}
13{-# LANGUAGE TypeOperators #-}
14{-# LANGUAGE UndecidableInstances #-}
14{-# LANGUAGE UndecidableInstances #-}
15
15
16−-- | Generalizes all the data needed to make code generation work with
17−-- arbitrary programming languages.
18module Servant.Foreign.Internal where
16module Servant.Foreign.Internal where
19
17
20import Prelude ()
18import Prelude ()
@@ -40,55 +38,75 @@ import Servant.API.Modifiers
40 (RequiredArgument)
38 (RequiredArgument)
41import Servant.API.TypeLevel
39import Servant.API.TypeLevel
42
40
41+-- | Canonical name of the endpoint, can be used to generate a function name.
42+--
43+-- You can use the functions in "Servant.Foreign.Inflections", like 'Servant.Foreign.Inflections.camelCase' to transform to `Text`.
43newtype FunctionName = FunctionName { unFunctionName :: [Text] }
44newtype FunctionName = FunctionName { unFunctionName :: [Text] }
44 deriving (Data, Show, Eq, Semigroup, Monoid, Typeable)
45 deriving (Data, Show, Eq, Semigroup, Monoid, Typeable)
45
46
46makePrisms ''FunctionName
47makePrisms ''FunctionName
47
48
49+-- | See documentation of 'Arg'
48newtype PathSegment = PathSegment { unPathSegment :: Text }
50newtype PathSegment = PathSegment { unPathSegment :: Text }
49 deriving (Data, Show, Eq, IsString, Semigroup, Monoid, Typeable)
51 deriving (Data, Show, Eq, IsString, Semigroup, Monoid, Typeable)
50
52
51makePrisms ''PathSegment
53makePrisms ''PathSegment
52
54
55+-- | Maps a name to the foreign type that belongs to the annotated value.
56+--
57+-- Used for header args, query args, and capture args.
53−data Arg f = Arg
58+data Arg ftype = Arg
54 { _argName :: PathSegment
59 { _argName :: PathSegment
60+ -- ^ The name to be captured.
61+ --
62+ -- Only for capture args it really denotes a path segment.
55− , _argType :: f }
63+ , _argType :: ftype
64+ -- ^ Foreign type the associated value will have
65+ }
56 deriving (Data, Eq, Show, Typeable)
66 deriving (Data, Eq, Show, Typeable)
57
67
58makeLenses ''Arg
68makeLenses ''Arg
59
69
60−argPath :: Getter (Arg f) Text
70+argPath :: Getter (Arg ftype) Text
61argPath = argName . _PathSegment
71argPath = argName . _PathSegment
62
72
63−data SegmentType f
73+data SegmentType ftype
64 = Static PathSegment
74 = Static PathSegment
65− -- ^ a static path segment. like "/foo"
75+ -- ^ Static path segment.
76+ --
77+ -- @"foo\/bar\/baz"@
78+ --
79+ -- contains the static segments @"foo"@, @"bar"@ and @"baz"@.
66− | Cap (Arg f)
80+ | Cap (Arg ftype)
67− -- ^ a capture. like "/:userid"
81+ -- ^ A capture.
82+ --
83+ -- @"user\/{userid}\/name"@
84+ --
85+ -- would capture the arg @userid@ with type @ftype@.
68 deriving (Data, Eq, Show, Typeable)
86 deriving (Data, Eq, Show, Typeable)
69
87
70makePrisms ''SegmentType
88makePrisms ''SegmentType
71
89
90+-- | A part of the Url’s path.
72−newtype Segment f = Segment { unSegment :: SegmentType f }
91+newtype Segment ftype = Segment { unSegment :: SegmentType ftype }
73 deriving (Data, Eq, Show, Typeable)
92 deriving (Data, Eq, Show, Typeable)
74
93
75makePrisms ''Segment
94makePrisms ''Segment
76
95
96+-- | Whether a segment is a 'Cap'.
77−isCapture :: Segment f -> Bool
97+isCapture :: Segment ftype -> Bool
78isCapture (Segment (Cap _)) = True
98isCapture (Segment (Cap _)) = True
79isCapture _ = False
99isCapture _ = False
80
100
101+-- | Crashing Arg extraction from segment, TODO: remove
81−captureArg :: Segment f -> Arg f
102+captureArg :: Segment ftype -> Arg ftype
82captureArg (Segment (Cap s)) = s
103captureArg (Segment (Cap s)) = s
83captureArg _ = error "captureArg called on non capture"
104captureArg _ = error "captureArg called on non capture"
84
105
106+-- TODO: remove, unnecessary indirection
85−type Path f = [Segment f]
107+type Path ftype = [Segment ftype]
86−
87−newtype Frag f = Frag { unFragment :: Arg f }
88− deriving (Data, Eq, Show, Typeable)
89−
90−makePrisms ''Frag
91
108
109+-- | Type of a 'QueryArg'.
92data ArgType
110data ArgType
93 = Normal
111 = Normal
94 | Flag
112 | Flag
@@ -97,18 +115,41 @@ data ArgType
97
115
98makePrisms ''ArgType
116makePrisms ''ArgType
99
117
118+-- | Url Query argument.
119+--
120+-- Urls can contain query arguments, which is a list of key-value pairs.
121+-- In a typical url, query arguments look like this:
122+--
123+-- @?foo=bar&alist[]=el1&alist[]=el2&aflag@
124+--
125+-- Each pair can be
126+--
127+-- * @?foo=bar@: a plain key-val pair, either optional or required ('QueryParam')
128+-- * @?aflag@: a flag (no value, implicitly Bool with default `false` if it’s missing) ('QueryFlag')
129+-- * @?alist[]=el1&alist[]=el2@: list of values ('QueryParams')
130+--
131+-- @_queryArgType@ will be set accordingly.
132+--
133+-- For the plain key-val pairs ('QueryParam'), @_queryArgName@’s @ftype@ will be wrapped in a @Maybe@ if the argument is optional.
100−data QueryArg f = QueryArg
134+data QueryArg ftype = QueryArg
101− { _queryArgName :: Arg f
135+ { _queryArgName :: Arg ftype
136+ -- ^ Name and foreign type of the argument. Will be wrapped in `Maybe` if the query is optional and in a `[]` if the query is a list
102 , _queryArgType :: ArgType
137 , _queryArgType :: ArgType
138+ -- ^ one of normal/plain, list or flag
103 }
139 }
104 deriving (Data, Eq, Show, Typeable)
140 deriving (Data, Eq, Show, Typeable)
105
141
106makeLenses ''QueryArg
142makeLenses ''QueryArg
107
143
108−data HeaderArg f = HeaderArg
144+data HeaderArg ftype =
145+ -- | The name of the header and the foreign type of its value.
146+ HeaderArg
109− { _headerArg :: Arg f }
147+ { _headerArg :: Arg ftype }
148+ -- | Unused, will never be set.
149+ --
150+ -- TODO: remove
110 | ReplaceHeaderArg
151 | ReplaceHeaderArg
111− { _headerArg :: Arg f
152+ { _headerArg :: Arg ftype
112 , _headerPattern :: Text
153 , _headerPattern :: Text
113 }
154 }
114 deriving (Data, Eq, Show, Typeable)
155 deriving (Data, Eq, Show, Typeable)
@@ -117,29 +158,71 @@ makeLenses ''HeaderArg
117
158
118makePrisms ''HeaderArg
159makePrisms ''HeaderArg
119
160
161+-- | Full endpoint url, with all captures and parameters
120−data Url f = Url
162+data Url ftype = Url
121− { _path :: Path f
163+ { _path :: Path ftype
164+ -- ^ Url path, list of either static segments or captures
165+ --
166+ -- @"foo\/{id}\/bar"@
122− , _queryStr :: [QueryArg f]
167+ , _queryStr :: [QueryArg ftype]
168+ -- ^ List of query args
169+ --
170+ -- @"?foo=bar&a=b"@
123− , _frag :: Maybe f
171+ , _frag :: Maybe ftype
172+ -- ^ Url fragment.
173+ --
174+ -- Not sent to the HTTP server, so only useful for frontend matters (e.g. inter-page linking).
175+ --
176+ -- @#fragmentText@
124 }
177 }
125 deriving (Data, Eq, Show, Typeable)
178 deriving (Data, Eq, Show, Typeable)
126
179
127−defUrl :: Url f
180+defUrl :: Url ftype
128defUrl = Url [] [] Nothing
181defUrl = Url [] [] Nothing
129
182
130makeLenses ''Url
183makeLenses ''Url
131
184
185+-- | See documentation of '_reqBodyContentType'
132data ReqBodyContentType = ReqBodyJSON | ReqBodyMultipart
186data ReqBodyContentType = ReqBodyJSON | ReqBodyMultipart
133 deriving (Data, Eq, Show, Read)
187 deriving (Data, Eq, Show, Read)
134
188
189+-- | Full description of an endpoint in your API, generated by 'listFromAPI'. It should give you all the information needed to generate foreign language bindings.
190+--
191+-- Every field containing @ftype@ will use the foreign type mapping specified via 'HasForeignType' (see its docstring on how to set that up).
192+--
193+-- See https://docs.servant.dev/en/stable/tutorial/ApiType.html for accessible documentation of the possible content of an endpoint.
135−data Req f = Req
194+data Req ftype = Req
136− { _reqUrl :: Url f
195+ { _reqUrl :: Url ftype
196+ -- ^ Full list of URL segments, including captures
137 , _reqMethod :: HTTP.Method
197 , _reqMethod :: HTTP.Method
198+ -- ^ @\"GET\"@\/@\"POST\"@\/@\"PUT\"@\/…
138− , _reqHeaders :: [HeaderArg f]
199+ , _reqHeaders :: [HeaderArg ftype]
200+ -- ^ Headers required by this endpoint, with their type
139− , _reqBody :: Maybe f
201+ , _reqBody :: Maybe ftype
202+ -- ^ Foreign type of the expected request body ('ReqBody'), if any
140− , _reqReturnType :: Maybe f
203+ , _reqReturnType :: Maybe ftype
204+ -- ^ The foreign type of the response, if any
141 , _reqFuncName :: FunctionName
205 , _reqFuncName :: FunctionName
206+ -- ^ The URL segments rendered in a way that they can be easily concatenated into a canonical function name
142 , _reqBodyContentType :: ReqBodyContentType
207 , _reqBodyContentType :: ReqBodyContentType
208+ -- ^ The content type the request body is transferred as.
209+ --
210+ -- This is a severe limitation of @servant-foreign@ currently,
211+ -- as we only allow the content type to be `JSON`
212+ -- no user-defined content types. ('ReqBodyMultipart' is not
213+ -- actually implemented.)
214+ --
215+ -- Thus, any routes looking like this will work:
216+ --
217+ -- @"foo" :> Get '[JSON] Foo@
218+ --
219+ -- while routes like
220+ --
221+ -- @"foo" :> Get '[MyFancyContentType] Foo@
222+ --
223+ -- will fail with an error like
224+ --
225+ -- @• JSON expected in list '[MyFancyContentType]@
143 }
226 }
144 deriving (Data, Eq, Show, Typeable)
227 deriving (Data, Eq, Show, Typeable)
145
228
@@ -183,11 +266,16 @@ defReq = Req defUrl "GET" [] Nothing Nothing (FunctionName []) ReqBodyJSON
183class HasForeignType lang ftype a where
266class HasForeignType lang ftype a where
184 typeFor :: Proxy lang -> Proxy ftype -> Proxy a -> ftype
267 typeFor :: Proxy lang -> Proxy ftype -> Proxy a -> ftype
185
268
269+-- | The language definition without any foreign types. It can be used for dynamic languages which do not /do/ type annotations.
186data NoTypes
270data NoTypes
187
271
272+-- | Use if the foreign language does not have any types.
188−instance HasForeignType NoTypes NoContent ftype where
273+instance HasForeignType NoTypes NoContent a where
189 typeFor _ _ _ = NoContent
274 typeFor _ _ _ = NoContent
190
275
276+-- | Implementation of the Servant framework types.
277+--
278+-- Relevant instances: Everything containing 'HasForeignType'.
191class HasForeign lang ftype (api :: *) where
279class HasForeign lang ftype (api :: *) where
192 type Foreign ftype api :: *
280 type Foreign ftype api :: *
193 foreignFor :: Proxy lang -> Proxy ftype -> Proxy api -> Req ftype -> Foreign ftype api
281 foreignFor :: Proxy lang -> Proxy ftype -> Proxy api -> Req ftype -> Foreign ftype api