"Strongly-typed" Phoenix channel messages

Some background information first: I am currently in the process of converting our frontend codebase to typescript. Most of the interactions with our backend go through GraphQL, which I used Absinthe for. As GraphQL has schema introspection, tying it to Typescript works pretty well, by generating code from the introspected schema.

What is nice about this solution is that as soon as the backend GraphQL definitions change, after re-running the generator you will exactly know which parts of the frontend code are affected by the backend change; there is one source of truth for the type definitions.

Some of our interactions go through “regular” Phoenix channels. In a Phoenix Channel, a message is defined by a name (a string) and an arbitrary JSON payload.

As of such, for channels there is no strong tie between backend and frontend; the frontend has no way of knowing what messages there are, and what the payload will look like.

As I was Googling and searching through this forum, I was wondering if I was the only one with this need; I have not found any previous discussions around this. So I’m considering doing some coding experiments on this topic. Would anyone be interested to use this if there were a library that provided type-safe channels messages?

3 Likes

This is very cool! I have seen approaches similar to this in a presentation about Rust recently
(c.f. Contract as code as contract: Using Rust to Unify Specification and Implementation), which convinced me that this might be a very good idea to strengthen the guarantees of our software.

AFAIK there indeed is very little work in Elixir on this front right now. Of course there’s TypeCheck (and to some extent Norm) to enable type-safe calling-contracts for ‘general’ functions inside of Elixir, but neither will work (at least not by themselves) for code that communicates with systems outside of Elixir.

I would be very interested in libraries providing type-safe APIs, especially type-safe Phoenix channels! :smiley: