Created
November 14, 2017 10:30
-
-
Save forki/a50821ae4f47c344e8068492f9868096 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Elmish.WebSocket | |
open Fable.Core | |
open Elmish | |
open Fable.Import.Browser | |
open Fable.Import.JS | |
open Fable.Core.JsInterop | |
open System.Runtime.InteropServices.ComTypes | |
[<RequireQualifiedAccess>] | |
type WebSocketMsg<'Data> = | |
| Connected | |
| Disconnected | |
| Error of string | |
| Data of 'Data | |
let createAuthenticated (url:string,jwt:string) = | |
WebSocket.Create(url + sprintf "/token/%s" (encodeURI jwt)) | |
let send (ws:Fable.Import.Browser.WebSocket) msg = | |
let m = toJson msg | |
ws.send m | |
module Cmd = | |
let [<PassGenerics>] Configure<'Data,'msg> (ws:Fable.Import.Browser.WebSocket) (messageCtor:WebSocketMsg<'Data> -> 'msg) = | |
let configure dispatch = | |
ws.onmessage <- | |
unbox (fun (msg: MessageEvent) -> | |
let msg' = msg.data |> string | |
let decoded = msg' |> ofJson<'Data> | |
dispatch (messageCtor (WebSocketMsg.Data decoded)) | |
unbox None) | |
ws.onopen <- unbox (fun _ -> dispatch (messageCtor WebSocketMsg.Connected)) | |
ws.onclose <- unbox (fun _ -> dispatch (messageCtor WebSocketMsg.Disconnected)) | |
ws.onerror <- unbox (fun evt-> dispatch (messageCtor (WebSocketMsg.Error (unbox evt?data)))) | |
() | |
[configure] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment