访问控制器助手中的用户字段不起作用

Accessing user fields in controller helper does not work

上下文

在控制器中,我有一个通过 beforeAction 调用的函数来检查 user 上的某个字段是否为空。如果为空,则应将用户重定向到另一个控制器中的某个操作。

因为我想从我应用程序中的几乎每个控制器调用这个函数,所以把它放在 Application.Helper.Controller 中似乎是正确的选择,但我无法弄清楚类型签名。

函数如下,在普通控制器中是这样的:

ensureIsSubscribed :: _ => IO ()
ensureIsSubscribed = do
    case currentUserOrNothing of
        Just loggedInUser -> do
            case (get #subscriptionId loggedInUser) of
                Nothing -> redirectToPath "/NewCheckoutSession"
                _ -> redirectToPath "/Welcome"
        Nothing -> pure ()

但是将上面的内容放入 Application.Helper.Controller 时出现此错误:

• Could not deduce (HasField
                      "subscriptionId" CurrentUserRecord (Maybe a0))
    arising from a use of ‘get’
  from the context: ?context::ControllerContext
    bound by the inferred type of
               ensureIsSubscribed :: (?context::ControllerContext) => IO ()
    at Application/Helper/Controller.hs:(8,1)-(14,26)
  The type variable ‘a0’ is ambiguous
• In the expression: (get #subscriptionId loggedInUser)
  In a stmt of a 'do' block:
    case (get #subscriptionId loggedInUser) of
      Nothing -> redirectToPath "/NewCheckoutSession"
      _ -> redirectToPath "/Welcome"
  In the expression:
    do case (get #subscriptionId loggedInUser) of
         Nothing -> redirectToPath "/NewCheckoutSession"
         _ -> redirectToPath "/Welcome"
   |
11 |             case (get #subscriptionId loggedInUser) of
   |                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

问题

为什么上面的方法不起作用,正确的类型签名是什么(如果这是问题所在)?

CurrentUserRecordWeb/Types.hs 中定义为 type instance CurrentUserRecord = User。如果未导入 Web.Types 模块,则类型 CurrentUserRecord 无法替换为它的定义 User.

因此,解决方法是将 import Web.Types 添加到您的 Application.Helper.Controller 模块 :)