diff --git a/lib/vonbraun/application.ex b/lib/vonbraun/application.ex index 05d72c9..46b0499 100644 --- a/lib/vonbraun/application.ex +++ b/lib/vonbraun/application.ex @@ -8,6 +8,7 @@ defmodule Vonbraun.Application do @impl true def start(_type, _args) do children = [ + Vonbraun.Repo, {Bandit, scheme: :http, plug: Vonbraun.MyRouter, port: 4012} ] diff --git a/lib/vonbraun/ecto/schema/pair.ex b/lib/vonbraun/ecto/schema/pair.ex index 8561931..aeffae5 100644 --- a/lib/vonbraun/ecto/schema/pair.ex +++ b/lib/vonbraun/ecto/schema/pair.ex @@ -1,10 +1,33 @@ defmodule Vonbraun.Ecto.Schema.Pair do use Ecto.Schema + alias Ecto.Changeset + alias Vonbraun.Repo - @primary_key {:key, :binary_id, autogenerate: false} + @primary_key {:key, :string, autogenerate: false} schema "pairs" do field(:value, :string) timestamps() end + + def changeset(struct, params \\ %{}) do + struct + |> Changeset.cast(params, [:value]) + end + + def set(key, value) do + case Repo.get(__MODULE__, key) do + nil -> + changeset(%__MODULE__{key: key}, %{value: value}) + |> Repo.insert() + + pair -> + changeset(pair, %{value: value}) + |> Repo.update() + end + end + + def get(key) do + Repo.get(__MODULE__, key) + end end diff --git a/lib/vonbraun/inbox_router.ex b/lib/vonbraun/inbox_router.ex index 50cda23..3bdea85 100644 --- a/lib/vonbraun/inbox_router.ex +++ b/lib/vonbraun/inbox_router.ex @@ -14,4 +14,14 @@ defmodule Vonbraun.InboxRouter do send_resp(conn, 404, "fuck off") end end + + post "/" do + nickname = Application.fetch_env!(:vonbraun, :nickname) + + if conn.params["user"] == nickname do + send_resp(conn, 200, "ok") + else + send_resp(conn, 404, "fuck off") + end + end end diff --git a/lib/vonbraun/router.ex b/lib/vonbraun/router.ex index 8b07176..424b69e 100644 --- a/lib/vonbraun/router.ex +++ b/lib/vonbraun/router.ex @@ -2,6 +2,7 @@ defmodule Vonbraun.MyRouter do use Plug.Router require Logger + alias Vonbraun.Ecto.Schema.Pair alias Vonbraun.InboxRouter plug(:match) @@ -224,6 +225,27 @@ defmodule Vonbraun.MyRouter do forward("/inbox", to: InboxRouter) forward("/users/:user/inbox", to: InboxRouter) + post "/pairs/:key/:value" do + key = conn.params["key"] + value = conn.params["value"] + Pair.set(key, value) + + send_resp(conn, 200, "ok") + end + + get "/pairs/:key" do + key = conn.params["key"] + pair = Pair.get(key) + + case pair do + nil -> + send_resp(conn, 404, "fuck off") + + %{:value => value} -> + send_resp(conn, 200, value) + end + end + match _ do send_resp(conn, 404, "fuck off") end