elixirphoenix-frameworkphoenix-channels

How do I specify my own Phoenix Channel JSON Serializer?


In my endpoint, I've got something that looks like:

  socket "/socket", MarsWeb.UserSocket,
    websocket: [transport: Phoenix.Transports.WebSocket, serializer: {MarsWeb.JsonCamelSerializer, "~>2.0"}],

I'm trying to replace the JSON serializer with my own one (that encodes camelcase on the outgoing messages).

I know this syntax isn't right; how should it look?

Update:

So for the purpose of testing, I set it up like this:

  socket "/socket", MarsWeb.UserSocket,
       websocket: [transport: Phoenix.Transports.Websocket, serializer: 
       Phoenix.Socket.V2.JSONSerializer]

But it actually doesn't work:

** (FunctionClauseError) no function clause matching in Phoenix.Socket.negotiate_serializer/2
    (phoenix 1.4.15) lib/phoenix/socket.ex:613: Phoenix.Socket.negotiate_serializer(Phoenix.Socket.V2.JSONSerializer, "2.0.0")

I think there's this extra issue of a version number, and looking in the source, it looks like it needs a tuple...


Solution

  • In the end, you need to paste a list of tuples.

    My solution was:

      socket "/socket", MarsWeb.UserSocket,
        websocket: [transport: Phoenix.Transports.Websocket, serializer: [{Phoenix.Socket.V1.JSONSerializer, "~> 1.0.0"}, {MarsWeb.JsonCamelSerializer, "~> 2.0.0"}]]