- Add jump_credo_checks ~> 0.4 with all 20 checks enabled - Fix all standard Credo issues: 139 @spec (113 done, 26 remain), 4 refactoring, 3 alias usage, 9 System.cmd env, 5 unsafe_to_atom, 2 max line length, 9 assert_receive timeout - Fix 170+ jump_credo_checks warnings: - 117 TopLevelAliasImportRequire: move nested alias/import to module top - 32 UseObanProWorker: switch to Oban.Pro.Worker - 4 DoctestIExExamples: add doctests / create test file - ~20 WeakAssertion: strengthen type-check assertions - Various ConditionalAssertion, AssertReceiveTimeout fixes - Exclude vendor/ from Credo analysis - Remaining: 175 warnings (mostly opinionated WeakAssertion, AvoidSocketAssignsInTest), 26 @spec annotations
57 lines
1.7 KiB
Elixir
57 lines
1.7 KiB
Elixir
defmodule MicrowavepropWeb.ContactMapController do
|
|
@moduledoc """
|
|
Serves the contact map JSON payload as a standalone HTTP endpoint. Keeps
|
|
the ~5 MB blob out of the `/contacts/map` LiveView's initial HTML response
|
|
and lets the browser's native `Content-Encoding: gzip` handling do the
|
|
compression. The payload itself is served from `Microwaveprop.Cache` via
|
|
`Radio.contact_map_payload/0`.
|
|
"""
|
|
use MicrowavepropWeb, :controller
|
|
|
|
alias Microwaveprop.Cache
|
|
alias Microwaveprop.Radio
|
|
|
|
@cache_key {__MODULE__, :gzipped_payload}
|
|
@cache_ttl_ms 10 * 60 * 1_000
|
|
|
|
@doc false
|
|
@spec cache_key() :: {module(), :gzipped_payload}
|
|
def cache_key, do: @cache_key
|
|
|
|
@spec show(Plug.Conn.t(), map()) :: Plug.Conn.t()
|
|
def show(conn, _params) do
|
|
{body, encoding} = gzipped_or_plain_body(conn)
|
|
|
|
conn
|
|
|> put_resp_content_type("application/json")
|
|
|> maybe_put_encoding(encoding)
|
|
|> put_resp_header("cache-control", "public, max-age=60")
|
|
|> send_resp(200, body)
|
|
end
|
|
|
|
defp gzipped_or_plain_body(conn) do
|
|
if accepts_gzip?(conn) do
|
|
{gzipped_payload(), :gzip}
|
|
else
|
|
%{json: iodata} = Radio.contact_map_payload()
|
|
{IO.iodata_to_binary(iodata), :identity}
|
|
end
|
|
end
|
|
|
|
defp gzipped_payload do
|
|
Cache.fetch_or_store(@cache_key, @cache_ttl_ms, fn ->
|
|
%{json: iodata} = Radio.contact_map_payload()
|
|
:zlib.gzip(IO.iodata_to_binary(iodata))
|
|
end)
|
|
end
|
|
|
|
defp accepts_gzip?(conn) do
|
|
case get_req_header(conn, "accept-encoding") do
|
|
[value | _] -> String.contains?(value, "gzip")
|
|
_ -> false
|
|
end
|
|
end
|
|
|
|
defp maybe_put_encoding(conn, :gzip), do: put_resp_header(conn, "content-encoding", "gzip")
|
|
defp maybe_put_encoding(conn, :identity), do: conn
|
|
end
|