1

我正在同时使用 Servant 和 Persistent。我有一个User实体,我想知道是否可以仅使用其字段的一个子集进行响应,具体取决于上下文。

让我们考虑以下两个端点:

type UserAPI = "user"
            :> Capture "username" Username
            :> Get '[JSON] (Entity User)

type ProfileAPI = "profiles"
                :> Capture "username" Username
                :> Get '[JSON] (Entity User)

type AppAPI = UserAPI :<|> ProfileAPI

这是我们的User模型:

share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase|
User json sql=users
    username  Text
    email     Text
    password  Text
    token     Text
    bio       Text Maybe default=NULL
    image     Text Maybe default=NULL
    createdAt UTCTime default=now()
    updatedAt UTCTime Maybe default=NULL

    UniqueUser username email
    deriving Show
|]

GET /user请求到达时,假设我们只想响应email身份token验证。另一方面,当请求到达时,我们希望只用,和GET /profile/:username来响应。usernamebioimage

我们怎样才能做到这一点?谢谢。


更新:我相信可以通过对特定表使用不同的记录来“转换”持久类型和仆人请求类型。例如,一个由 Persistent 使用,另一个用作与客户端的接口。但是,这可能需要一个函数在两者之间进行转换。随着逻辑的发展,我想事情会变得很麻烦。

此外,我认为定义 ToJSON 和 FromJSON 实例可以解决问题,但我无法理解它。

4

1 回答 1

1

为什么你想要相同数据类型的多个实例?为什么不为您希望每个处理程序返回的数据创建单独的数据类型,并ToJSON为每个处理程序创建实例?

type UserAPI = "user"
            :> Capture "username" Username
            :> Get '[JSON] UserEmailAndToken

type ProfileAPI = "profiles"
                :> Capture "username" Username
                :> Get '[JSON] UserNameBioAndImage

type AppAPI = UserAPI :<|> ProfileAPI

然后你会定义UserEmailAndTokenUserNameBioAndImage(这应该很容易),为每个类型编写实例,以及这些类型ToJSON之间的微不足道的函数映射。User

于 2017-05-26T23:54:11.723 回答