Respond with json string without render from :view or :controller

Im receiving json from postgres. I dont want to deserialize as a map then serialize to json.

Im using using rustler to query the database in rust. Which returns a string. I would like to then just pass that string back to phx then on to the user.

Any ideas how I might do this?

In your controller function you can set headers and write responses directly to the connection.

This example is for a CSV, but JSON should be pretty much identical (you may need to inspect some web response headers from something that works to get the exact recipe right)

defmodule MyWeb.ExportCSVController do
  use MyWeb, :controller

  def export(conn, %{"id" => id}) do
    csv_data = generate_csv(id)

    conn
    |> put_resp_content_type("text/csv")
    |> put_resp_header(
      "content-disposition", 
      ~s[attachment; filename="export_file.csv"]
    )
    |> put_root_layout(false)
    |> send_resp(200, csv_data) # This is where you dump the content
  end
  
  defp generate_csv(id), do: ...
end

and in your router you will have something like:

get "/export/:id", MyWeb.ExportCSVController, :export
1 Like