我正在同时使用 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
来响应。username
bio
image
我们怎样才能做到这一点?谢谢。
更新:我相信可以通过对特定表使用不同的记录来“转换”持久类型和仆人请求类型。例如,一个由 Persistent 使用,另一个用作与客户端的接口。但是,这可能需要一个函数在两者之间进行转换。随着逻辑的发展,我想事情会变得很麻烦。
此外,我认为定义 ToJSON 和 FromJSON 实例可以解决问题,但我无法理解它。