fix api
This commit is contained in:
parent
221c3ae76c
commit
01f8016cfd
2 changed files with 35 additions and 3 deletions
|
|
@ -8,11 +8,14 @@ defmodule ZoeyscomputerWeb.GistController do
|
|||
|
||||
def index(conn, _params) do
|
||||
gists = Gists.list_gists()
|
||||
IO.inspect(gists)
|
||||
render(conn, :index, gists: gists)
|
||||
end
|
||||
|
||||
def create(conn, %{"gist" => gist_params}) do
|
||||
with {:ok, %Gist{} = gist} <- Gists.create_gist(gist_params) do
|
||||
def create(conn, params) do
|
||||
gist_params = decode_params(params)
|
||||
|
||||
with {:ok, %Gist{} = gist} <- Gists.create_gist(conn.assigns.current_user, gist_params) do
|
||||
conn
|
||||
|> put_status(:created)
|
||||
|> put_resp_header("location", ~p"/api/gists/#{gist}")
|
||||
|
|
@ -20,6 +23,32 @@ defmodule ZoeyscomputerWeb.GistController do
|
|||
end
|
||||
end
|
||||
|
||||
# Private function to handle param decoding
|
||||
defp decode_params(params) when is_map(params) do
|
||||
cond do
|
||||
# Handle regular JSON params
|
||||
Map.has_key?(params, "title") and
|
||||
Map.has_key?(params, "desc") and
|
||||
Map.has_key?(params, "code") and
|
||||
Map.has_key?(params, "language") ->
|
||||
params
|
||||
|
||||
# Handle params wrapped in "gist" key
|
||||
Map.has_key?(params, "gist") ->
|
||||
params["gist"]
|
||||
|
||||
# Handle string JSON that needs parsing
|
||||
Enum.any?(params, fn {k, _v} -> String.starts_with?(k, "{") end) ->
|
||||
params
|
||||
|> Map.keys()
|
||||
|> List.first()
|
||||
|> Jason.decode!()
|
||||
|
||||
true ->
|
||||
params
|
||||
end
|
||||
end
|
||||
|
||||
def show(conn, %{"id" => id}) do
|
||||
gist = Gists.get_gist!(id)
|
||||
render(conn, :show, gist: gist)
|
||||
|
|
|
|||
|
|
@ -19,7 +19,10 @@ defmodule ZoeyscomputerWeb.GistJSON do
|
|||
%{
|
||||
id: gist.id,
|
||||
code: gist.code,
|
||||
lang: gist.lang
|
||||
lang: gist.lang,
|
||||
author_id: gist.author_id,
|
||||
desc: gist.desc,
|
||||
title: gist.title
|
||||
}
|
||||
end
|
||||
end
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue