git.iko.soy/typeable/servant-swagger-ui
on master help sign in
Extend an example showing how to use AppendSymbol for more info
e45af43Oleg Grenrus
example/Main.hs+50−3
@@ -50,6 +50,13 @@ import Control.Monad.Trans.Either (EitherT)
50#define SUMMARY(d)
50#define SUMMARY(d)
51#endif
51#endif
52
52
53+#if MIN_VERSION_servant(0,13,0)
54+#if __GLASGOW_HASKELL__ >= 802 && MIN_VERSION_base(4,10,0)
55+import GHC.Generics (D1, Meta (..), Rep)
56+import GHC.TypeLits (AppendSymbol, Symbol)
57+#endif
58+#endif
59+
53-- data types
60-- data types
54data Cat = Cat { catName :: CatName, catIsMale :: Bool }
61data Cat = Cat { catName :: CatName, catIsMale :: Bool }
55 deriving (Generic, Show)
62 deriving (Generic, Show)
@@ -77,13 +84,53 @@ instance ToSchema CatName
77
84
78-- api
85-- api
79
86
87+#if MIN_VERSION_servant(0,13,0)
88+#if __GLASGOW_HASKELL__ >= 802 && MIN_VERSION_base(4,10,0)
89+-- | Get a typename as type-level 'Symbol'.
90+--
91+-- Few non-Generic things are hard-coded, for else we fallback to 'Generic'
92+--
93+-- >>> :kind! TypeName Int
94+-- TypeName Int :: Symbol
95+-- = "Int"
96+--
97+-- >>> :kind! TypeName CatName
98+-- TypeName CatName :: Symbol
99+-- = "CatName"
100+--
101+-- Unfortunately we cannot use 'TypeError' for other cases,
102+-- as 'Rep' isn't reduced so 'GenericTypeName' cannot fall past first
103+-- equation. So you will get somewhat obscure errors saying
104+-- "no instance for (KnownSymbol ... (GenericTypeName YourNonGenericType ..."
105+--
106+-- >>> :kind! TypeName Float
107+-- TypeName Float :: Symbol
108+-- = GenericTypeName Float (Rep Float ())
109+--
110+-- It would be nice if there were such type family for 'Typeable', i.e. all
111+-- types :)
112+--
113+type family TypeName (x :: *) :: Symbol where
114+ TypeName Int = "Int"
115+ TypeName Text = "Text"
116+ TypeName x = GenericTypeName x (Rep x ())
117+
118+type family GenericTypeName t (r :: *) :: Symbol where
119+ GenericTypeName t (D1 ('MetaData name mod pkg nt) f x) = name
120+
121+type Desc t n = Description (AppendSymbol (TypeName t) (AppendSymbol " | " n))
122+#else
123+type Desc t n = Description n
124+#endif
125+#endif
126+
80type FirstCatEndpoint =
127type FirstCatEndpoint =
81#if MIN_VERSION_servant(0,13,0)
128#if MIN_VERSION_servant(0,13,0)
82 "cat"
129 "cat"
83 :> Summary "First cat endpoint"
130 :> Summary "First cat endpoint"
84− :> Capture' '[Description "Cat's name"] ":name" CatName
131+ :> Capture' '[Desc CatName "Cat's name"] ":name" CatName
85− :> QueryParam' '[Required, Description "Random number"] "num" Int
132+ :> QueryParam' '[Required, Desc Int "Random number"] "num" Int
86− :> QueryParam' '[Optional, Description "Random text"] "text" Text
133+ :> QueryParam' '[Optional, Desc Text "Random text"] "text" Text
87 :> Get '[JSON] Cat
134 :> Get '[JSON] Cat
88#else
135#else
89 "cat" :> Capture ":name" CatName
136 "cat" :> Capture ":name" CatName