tusker_push/lib/tusker_push_web/controllers/registrations_controller.ex

60 lines
1.4 KiB
Elixir

defmodule TuskerPushWeb.RegistrationsController do
alias TuskerPush.Registration
alias Ecto.Changeset
use TuskerPushWeb, :controller
require Logger
def create(conn, %{
"transaction_id" => transaction_id,
"environment" => env,
"device_token" => token
}) do
with {:ok, %Registration{id: id}} <-
TuskerPush.register(%{
storekit_original_transaction_id: transaction_id,
apns_environment: env,
apns_device_token: token
}) do
conn
|> json(%{
id: id,
endpoint: url(~p"/mastodon/push/#{id}")
})
else
{:env, nil} ->
conn
|> put_status(400)
|> json(%{error: "invalid apns environment"})
{:error, %Changeset{valid?: false} = changeset} ->
errors =
changeset.errors
|> Enum.map(fn {k, {reason, _}} -> %{key: k, reason: reason} end)
conn
|> put_status(400)
|> json(%{errors: errors})
{:error, reason} ->
Logger.error("Failed creating registration: #{inspect(reason)}")
conn
|> put_status(500)
|> json(%{error: "unknown error"})
end
end
def create(conn, _) do
conn
|> put_status(400)
|> json(%{error: "missing required parameters"})
end
def delete(conn, %{"id" => id}) do
TuskerPush.unregister(id)
json(conn, %{status: "ok"})
end
end