Skip to content

Instantly share code, notes, and snippets.

@eriktim eriktim/Main.elm Secret
Created Jan 5, 2019

Embed
What would you like to do?
Example usage of elm-protocol-buffers
module Main exposing (Model(..), Msg(..), init, main, subscriptions, update, view)
import Browser
import Html exposing (Html, pre, text)
import Http
import ProtoBuf.Decode as Decode
import ProtoBuf.Encode as Encode
main =
Browser.element
{ init = init
, update = update
, subscriptions = subscriptions
, view = view
}
-- MODEL
type Model
= Failure
| Loading
| Success Message
init : () -> ( Model, Cmd Msg )
init _ =
( Loading
, Http.get
{ url = "http://localhost:3000/api/messages"
, expect = expectBytes GotMessage messageDecoder
}
)
-- UPDATE
type Msg
= GotMessage (Result Http.Error Message)
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
GotMessage result ->
case result of
Ok message ->
( Success message, Cmd.none )
Err _ ->
( Failure, Cmd.none )
-- SUBSCRIPTIONS
subscriptions : Model -> Sub Msg
subscriptions model =
Sub.none
-- VIEW
view : Model -> Html Msg
view model =
case model of
Failure ->
text "I was unable to load your message."
Loading ->
text "Loading..."
Success message ->
pre [] [ text message.text, text message.lang ]
-- PROTOBUF
-- uses https://github.com/azat-co/proto-buffer-api
expectBytes : (Result Http.Error a -> msg) -> Decode.Decoder a -> Http.Expect msg
expectBytes toMsg decoder =
Http.expectBytesResponse toMsg
(\response ->
case response of
Http.BadUrl_ url ->
Err (Http.BadUrl url)
Http.Timeout_ ->
Err Http.Timeout
Http.NetworkError_ ->
Err Http.NetworkError
Http.BadStatus_ metadata body ->
Err (Http.BadStatus metadata.statusCode)
Http.GoodStatus_ _ body ->
case Decode.decode decoder body of
Just value ->
Ok value
Nothing ->
Err (Http.BadBody "Decoder error")
)
type alias Message =
{ text : String
, lang : String
}
messageDecoder : Decode.Decoder Message
messageDecoder =
Decode.message (Message "" "")
[ Decode.optional 1 Decode.string (\v m -> { m | text = v })
, Decode.optional 2 Decode.string (\v m -> { m | lang = v })
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.