How to structure a library around a WebSocket API?

I’ve been getting into Elixir recently and now that I’ve finished the “Elixir in Action” book I’m ready to dive into my first project: a library around a specific WebSocket API.

Since I’ve never built a library in any language I’d like to get some pointers how to do this in a meaningful way.

WebSocket library
I think using an existing WebSocket library to handle the connection etc. would be a good start? I’ve been looking around and didn’t find any that’s “actively” developed. Do you have any recommendations? I’ve been looking at WebSockex and Fresh

User friendly structure
How do I go about structuring this? Fresh has various options when starting it up with start_link. Do I hide those except for the URI the user has to provide or just reference them in the documentation so the user can decide? There’s also an authentication needed via access token so I’d need the user to provide this to the state.

The API I’m trying to write the wrapper for has states and events you can listen for. My idea was to have a module handling the WebSocket callbacks and pass the relevant data to the main module where I’d have callbacks that the user implements. Something like this:

defmodule Lib.WebSocket do
    use Fresh/WebSockex/...

    @impl Fresh/WebSockex/...
    def handle_in({:text, frame}, state) do
        case Jason.decode(frame) do
            {:ok, msg} -> handle_msg(msg, state)
            {:error, error} -> {:ok, state}
        end
    end

    def handle_msg(%{"type" => "auth_required"}, state) do
        # get access token from state and send back?
    end

    def handle_msg(%{"type" => "state_changed", ...}, state) do
        # pass to main module
        Lib.handle_state(entity, from, to)
    end
end

I’ve not yet worked with callbacks but I’d have handle_state be the callback so the user can pattern match to whatever combinaion of state change they want. Is that a good way to do it?

Error handling is another part I’m unsure about

So many questions, hope you can help me out here :pray:

1 Like

Ha, you’ll likely be interested in this very recent thread as well as this one.

Also, welcome to Elixir Forum!

5 Likes

Thanks for the feedback, though I can’t quite follow those threads with my limited knowledge. Maybe I’m just blind but I can’t see any answers to my questions :confused:

Ah sorry I didn’t mean to imply that it would answer all of your questions, it was just recent discussion on the same topic I thought you would may be able to get something out of. Sorry that it was no help :frowning:

2 Likes