自定义ToSchema自动推导生成的字段
Customizing the fields generated by automatic derivation of ToSchema
我有以下类型:
data Device = Device { _deviceId :: DeviceId
, _deviceName :: Text
, _deviceDtype :: DType }
deriving (Show, Eq, Generic)
makeFields ''Device
$(deriveJSON (mkOptions "_device") ''Device)
这里我使用 deriveJSON
而不是 Generic
机制,因为我需要为这种数据类型调整 JSON 表示的字段名称:
-- | Make JSON conversion options.
mkOptions :: String -> Options
mkOptions prefix = defaultOptions { fieldLabelModifier = removePrefix prefix
, unwrapUnaryRecords = True
}
为该类型生成镜头需要前缀,但在 JSON 表示中不需要。
现在我正在尝试使用 Device
的 servant-swagger, which requires a ToSchema
实例生成 Swagger 文档。现在的问题是生成的模式将具有上面访问函数的给定前缀名称(_deviceId
、_deviceName
、_deviceDType
)。相反,我会使用修改后的版本(id
、name
和 dtype
)。
有没有办法自定义泛型推导过程?
不太熟悉 servant-swagger
和 swagger2
,但看起来像这样应该可以完成工作:
import Data.Swagger.Schema
import Data.Swagger.SchemaOptions
instance ToSchema Device where
declareNamedSchema =
genericDeclareNamedSchema
defaultSchemaOptions {fieldLabelModifier = \fieldLabel -> ...}
我有以下类型:
data Device = Device { _deviceId :: DeviceId
, _deviceName :: Text
, _deviceDtype :: DType }
deriving (Show, Eq, Generic)
makeFields ''Device
$(deriveJSON (mkOptions "_device") ''Device)
这里我使用 deriveJSON
而不是 Generic
机制,因为我需要为这种数据类型调整 JSON 表示的字段名称:
-- | Make JSON conversion options.
mkOptions :: String -> Options
mkOptions prefix = defaultOptions { fieldLabelModifier = removePrefix prefix
, unwrapUnaryRecords = True
}
为该类型生成镜头需要前缀,但在 JSON 表示中不需要。
现在我正在尝试使用 Device
的 servant-swagger, which requires a ToSchema
实例生成 Swagger 文档。现在的问题是生成的模式将具有上面访问函数的给定前缀名称(_deviceId
、_deviceName
、_deviceDType
)。相反,我会使用修改后的版本(id
、name
和 dtype
)。
有没有办法自定义泛型推导过程?
不太熟悉 servant-swagger
和 swagger2
,但看起来像这样应该可以完成工作:
import Data.Swagger.Schema
import Data.Swagger.SchemaOptions
instance ToSchema Device where
declareNamedSchema =
genericDeclareNamedSchema
defaultSchemaOptions {fieldLabelModifier = \fieldLabel -> ...}