git.iko.soy/typeable/derive-api-th
on master help sign in
add Arbitrary
commit075cd791701fecf394f65ed2f1c5fa6c2decd224 authorDmitry Olshansky <olshanskydr@gmail.com> dateMon 25 Jul 2022, 10:56 (4 years ago) parent2509c54
2 files changed+29−4
derive-api-th.cabal+3−1 src/Derive/API/TH.hs+26−3
derive-api-th.cabal+3−1
@@ -32,7 +32,9 @@ library
3232 , th-abstraction
3333 if !impl(ghcjs)
3434 build-depends:
35− openapi3
35+ openapi3
36+ , generic-arbitrary
37+ , QuickCheck
3638 default-language: Haskell2010
3739 default-extensions:
3840 DuplicateRecordFields
src/Derive/API/TH.hs+26−3
@@ -13,6 +13,7 @@ module Derive.API.TH
1313 , derivingOptionsToSchemaOptions
1414 , deriveToParamSchema
1515 , deriveToSchema
16+ , deriveArbitrary
1617#endif
1718 , deriveApiFromJSON
1819 , deriveApiToJSON
@@ -27,14 +28,16 @@ import Data.Functor
2728#endif
2829import qualified Data.List as List
2930import Data.Maybe
30−#ifndef ghcjs_HOST_OS
31−import Data.OpenApi hiding (prefix)
32−#endif
3331import Data.Typeable
3432import Language.Haskell.TH
3533import Language.Haskell.TH.Datatype
3634import Language.Haskell.TH.Syntax
3735
36+#ifndef ghcjs_HOST_OS
37+import Data.OpenApi hiding (prefix)
38+import Test.QuickCheck
39+import Test.QuickCheck.Arbitrary.Generic
40+#endif
3841
3942-- | derive JSON and openapi3 (ToSchema) instances
4043deriveApiInstances :: DerivingOptions -> Name -> Q [Dec]
@@ -47,6 +50,17 @@ deriveApiInstances opts tname =
4750 deriveJSON (derivingOptionsToJsonOptions opts) tname
4851#endif
4952
53+-- | derive JSON and openapi3 (ToSchema) instances
54+deriveApiAndArbitraryInstances :: DerivingOptions -> Name -> Q [Dec]
55+#ifndef ghcjs_HOST_OS
56+deriveApiAndArbitraryInstances opts tname = liftM2 (<>)
57+ (deriveApiInstances opts tname)
58+ (deriveArbitrary tname)
59+#else
60+deriveApiAndArbitraryInstances opts tname =
61+ deriveApiInstances opts tname
62+#endif
63+
5064-- We can't directly 'lift' Options into TH, so have to use this
5165data DerivingOptions = DerivingOptions
5266 { prefix :: Maybe String
@@ -121,3 +135,12 @@ generateParseJSON = mkParseJSON . derivingOptionsToJsonOptions
121135
122136stripPrefix :: String -> String -> String
123137stripPrefix pfx = fromMaybe <*> List.stripPrefix pfx
138+
139+#ifndef ghcjs_HOST_OS
140+deriveArbitrary :: Name -> Q [Dec]
141+deriveArbitrary t = [d|
142+ instance Arbitrary $(conT t) where
143+ arbitrary = genericArbitrary
144+ shrink = genericShrink
145+ |]
146+#endif