Last active
February 9, 2018 08:00
-
-
Save jochasinga/59495ff8330dd7764b34f528b80f8180 to your computer and use it in GitHub Desktop.
Exploring first Bucklescript
This file contains 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
type socket | |
type event | |
type config = { | |
reconnect: bool; | |
debug: bool; | |
timeout: int; | |
interval: int | |
} | |
type callback = (socket -> config -> event -> unit) option | |
type callbacks = { | |
on_open: callback; | |
on_error: callback; | |
on_close: callback; | |
on_message: callback | |
} | |
(* External JS *) | |
external create_ws : string -> socket = "WebSocket" [@@bs.new] | |
external add_listener : socket -> string -> (event -> unit) -> unit = | |
"addEventListener" [@@bs.send] | |
(* Helper functions *) | |
let debug_log msg = | |
match msg with | |
| "" -> () | |
| _ -> Js.log msg | |
let inject_handler f args = | |
match f with | |
| None -> () | |
| Some f -> let (socket, config, ev) = args in f socket config ev | |
let init_socket uri config callbacks = | |
let { reconnect; debug; timeout; interval } = config in | |
let { on_open; on_error; on_close; on_message } = callbacks in | |
let socket = create_ws uri in | |
let events = [ ("open", "Connected", on_open) | |
; ("error", "", on_error) | |
; ("close", "Disconnected", on_close) | |
; ("message", "Incoming", on_message) | |
] in | |
events |> List.iter (fun event -> | |
let (ev_name, ev_message, ev_callback) = event in | |
add_listener socket ev_name ( fun ev -> | |
if debug && ev_message <> "" then debug_log ev_message; | |
inject_handler ev_callback (socket, config, ev) | |
) | |
) | |
let main () = | |
let uri = "wss://endpoint.lol/api/services/foo/bar" in | |
let config = {reconnect = true; debug = true; timeout = 3000; interval = 1} in | |
let cbs = { | |
on_open = None; | |
on_close = None; | |
on_error = None; | |
on_message = Some ( fun socket conf ev -> Js.log ev ) | |
} in init_socket uri config cbs | |
let () = main () |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment