这就是我试图让我的处理程序看起来像 -
getUserStudentsR :: UserId -> Handler TypedContent
getUserStudentsR userId =
getStudentEntitiesForCoach userId
>>= returnTypedContent . map toUserStudentResponse
其中学生是一个持久实体(细节大多不重要)和
getStudentEntitiesForCoach :: UserId -> HandlerT App IO [Entity Student]
getStudentEntitiesForCoach coachId =
runDB $ selectList [StudentPrimaryCoachId ==. Just(coachId)] []
data UserStudentResponse = StudentResponse (Key Student) Student
instance ToJSON UserStudentResponse where
toJSON (StudentResponse studentId student) =
object
[
"login" .= studentLogin student
, "studentId" .= studentId
, "firstName" .= studentFirstname student
, "lastName" .= studentLastname student
]
toUserStudentResponse :: (Entity Student) -> UserStudentResponse
toUserStudentResponse (Entity studentId student)
= StudentResponse studentId student
和
returnTypedContent x = selectRep $ do
provideJson x
现在很明显,除非 UserStudentResponse 实例化 ToJSON 并提供 toJSON 的实现,否则这不会编译。但是,我想让 returnTypedContent 函数通用 - 比如 -
returnTypedContent x = selectRep $ do
-- if ToJSON x --
provideJSON x
-- if ToHTML x -- -- note this is not an either or
provideRep $ return $ toHtml $ a
我想这样做,以便可以扩展 returnTypedContent 以提供各种内容类型的返回,然后根据处理程序中使用的数据类型是否实例化某些类型类(例如 ToJSON),我们提供了不同的东西。
如果不进入 Template Haskell,这样的事情可能吗?