首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将IHP有效载荷解析为记录类型

将IHP有效载荷解析为记录类型
EN

Stack Overflow用户
提问于 2022-11-28 17:26:55
回答 1查看 53关注 0票数 1

我想做什么?

我将在IHP中重新设置一个JSON有效负载,并希望将其转换为记录类型。

我所拥有的

我用IHP生成器生成的记录类型

代码语言:javascript
复制
data Resource' userId providerId bookings = Resource 
  { id :: (Id' "resources")
  , createdAt :: UTCTime
  , updatedAt :: UTCTime
  , userId :: userId
  , providerId :: providerId
  , name :: Text
  , bookings :: bookings
  , meta :: MetaBag
  } deriving (Eq, Show)
type Resource = Resource' (Id' "users") (Id' "providers")(QueryBuilder.QueryBuilder "bookings")

我无法直接将json有效负载转换为Record,因此创建了另一个临时记录来从json获取值。

代码语言:javascript
复制
data ResourceCreateRequest = ResourceCreateRequest { name :: String }

instance FromJSON ResourceCreateRequest where
  parseJSON = withObject "Resource" $ \o -> ResourceCreateRequest <$> o .: "name"

JSON有效载荷

代码语言:javascript
复制
{"name": "X"}

我的想法是使用临时记录来替换IHP生成的newRecord @Resource中的几个特定字段。以显示我在控制器中使用(或尝试)的结果

代码语言:javascript
复制
-- JRCR is a qualified name of the module with my temporary record
"application/json" -> renderJson (newRecord @Resource){ name = (JRCR.name getRequest) }

问题

显然,我在Value -> ResourceValue -> ResourceCreateRequest转换方面存在问题,无法正确完成。你能帮帮我吗?

电流误差

代码语言:javascript
复制
Record update is ambiguous, and requires a type signature
    * In the second argument of `($)', namely
        `(newRecord @Resource) {name = (JRCR.name getRequest)}'
      In the expression:
        renderJson $ (newRecord @Resource) {name = (JRCR.name getRequest)}
      In a case alternative:
          "application/json"
            -> renderJson
                 $ (newRecord @Resource) {name = (JRCR.name getRequest)}
   |
52 |           "application/json" -> renderJson $ (newRecord @Resource){ name = (JRCR.name getRequest) }
   |                                              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-11-28 23:17:06

问题是类型推断和DuplicateRecordFields不能很好地结合在一起。下面是一个很小的程序,它演示了您遇到的相同问题,但不涉及IHP或任何其他第三方代码:

代码语言:javascript
复制
{-# LANGUAGE DuplicateRecordFields, TypeApplications #-}

data Foo = Foo { name :: String } deriving Show
data Bar = Bar { name :: String } deriving Show

class Baz a where
    baz :: a

instance Baz Foo where
    baz = Foo ""

instance Baz Bar where
    baz = Bar ""

main :: IO ()
main = print $ (baz @Foo){ name = "qux" }

这里的解决方案是将baz @Foo更改为baz @Foo :: Foo。在这种情况下,只有baz :: Foo也能工作。

同样,将newRecord @Resource更改为newRecord @Resource :: Resource,或者可能将newRecord :: Resource更改为newRecord :: Resource,应该可以修复代码。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74604340

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档