Skip to content

Commit

Permalink
feat: add json data type for shields
Browse files Browse the repository at this point in the history
  • Loading branch information
tynn committed Apr 25, 2023
1 parent debc184 commit 869bc91
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 6 deletions.
16 changes: 10 additions & 6 deletions lib/asapi.ex
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,20 @@ defmodule Asapi do
@loading "…"
@unknown "unknown"

def shield(status) when status in [@loading, @unknown] do
shield(status, "inactive")
def shield(status, json \\ false) when status in [@loading, @unknown] do
shield(status, "inactive", json)
end

def shield(status) do
shield(status, "informational")
def shield(status, json) do
shield(status, "informational", json)
end

defp shield(status, color) do
"https://img.shields.io/badge/API-#{encode(status)}-#{color}"
defp shield(status, color, json) do
unless json do
"https://img.shields.io/badge/API-#{encode(status)}-#{color}"
else
"{\"schemaVersion\":1,\"label\":\"API\",\"message\":\"#{status}\",\"color\":\"#{color}\"}"
end
end

defp encode(part) do
Expand Down
7 changes: 7 additions & 0 deletions lib/asapi/lv.ex
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,13 @@ defmodule Asapi.Lv do
|> redirect_to
end

defp asapi_lv(%Conn{assigns: %{asapi_aar: aar, asapi_ext: :json}}) do
aar
|> api_lv
|> shield(json: true)
|> send_json
end

defp asapi_lv(%Conn{assigns: %{asapi_aar: aar, asapi_ext: :txt}}) do
aar
|> api_lv
Expand Down
2 changes: 2 additions & 0 deletions lib/asapi/util.ex
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,7 @@ defmodule Asapi.Util do

def redirect_to(url), do: {:redirect, url}

def send_json(json), do: {:ok, json, ["content-type": "application/json"]}

def send_text(text), do: {:ok, text, ["content-type": "text/plain"]}
end
21 changes: 21 additions & 0 deletions test/asapi/lv_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,27 @@ defmodule Asapi.LvTest do
assert {"location", "#{shield("12+")}.svg"} in conn.resp_headers
end

test "call returns json to with unknown api level" do
conn =
conn(:get, "/foo")
|> assign(:asapi_aar, %{@aar | group: nil})
|> assign(:asapi_ext, :json)
|> Lv.call(nil)

assert conn.resp_body == shield(@unknown, json: true)
end

test_with_mock "call returns json to with api level", Data, get!: fn _ -> "13+" end do
conn =
conn(:get, "/foo")
|> assign(:asapi_aar, @aar)
|> assign(:asapi_ext, :json)
|> Lv.call(nil)

assert called(Data.get!(@aar))
assert conn.resp_body == shield("13+", json: true)
end

test "call returns txt to with unknown api level" do
conn =
conn(:get, "/foo")
Expand Down

0 comments on commit 869bc91

Please sign in to comment.