无法从elm端口解码会话

时间:2017-11-15 05:40:28

标签: elm json-deserialization elm-port

尝试让elm端口正常工作以维护会话。

在index.html中,脚本包含以下侦听器:

  window.addEventListener("load", function(event) {
    app.ports.onSessionChange.send(localStorage.session);
  }, false);

localStorage.session看起来像这样(它会一直存在,直到我退出):

{"email":"user@fake.com","token":"eyJhbG...","user_id":1,"handle":"me"}

Ports.elm中的定义是:

port onSessionChange : (Value -> msg) -> Sub msg

此端口已连接到Main.elm(如果我忘记在下面添加一些定义,请告诉我们):

subscriptions : Model -> Sub Msg
subscriptions model =
    Ports.onSessionChange sessionChange


sessionChange : Json.Decode.Value -> Msg
sessionChange value =
    let
        result =
            Json.Decode.decodeValue sessionDecoder value
    in
        case result of
            Ok sess ->
                SetSession (Just sess)

            Err err ->
                SetSession Nothing

    ...


type alias Session =
    { email : String
    , token : String
    , user_id : Int
    , handle : String
    }

    ...

import Json.Decode as Decode exposing (..)
import Json.Decode.Pipeline as Pipeline exposing (decode, required)

sessionDecoder : Decode.Decoder Session
sessionDecoder =
    Pipeline.decode Session
        |> Pipeline.required "email" Decode.string
        |> Pipeline.required "token" Decode.string
        |> Pipeline.required "user_id" Decode.int
        |> Pipeline.required "handle" Decode.string

    ...

type Msg
    = NoOp
    | SetSession (Maybe Session)

    ...


update msg model =
    case msg of
        SetSession session ->
            case Debug.log "session = " session of
                Just sess ->
                    ({ model | session = sess } , Cmd.none)

                Nothing ->
                    (model, Cmd.none)
当页面加载时,

Debug.log "session"在控制台中显示Nothing,因此JS正在与elm交谈,但解码器似乎失败了。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

我已将您的代码插入minimal working example,一切正常。您可能希望从javascript部分内部记录localStorage.session的值,以确保它是有效的JSON值。