lgp

lgp

How do I clean up this code from an example in the PragProg elixir course?

It was a much simpler exercise, but I wanted to add a few things, and well, aside from the duplication, it’s ugly.

defmodule JsonAPI do

  def query(cat,id,keys) do

    categories = %{
      "posts"    => 100,
      "comments" => 500,
      "albums"   => 100,
      "photos"   => 5000,
      "todos"    => 200,
      "users"    => 10
    }

    if cat not in Map.keys(categories) do
       {:error, ~s('#{cat}' is not a valid category.) }
     else
       if id > categories[cat] do
         {:error, ~s(The maximum id for '#{cat}' is #{categories[cat]}.) }
       else
         base = "https://jsonplaceholder.typicode.com/"
         [base, cat, "/", to_string(id)]
               |> :erlang.iolist_to_binary
               |> HTTPoison.get
               |> handle_response(keys)
       end
     end
   end

   def query(cat,id) do

     categories = %{
       "posts"    => 100,
       "comments" => 500,
       "albums"   => 100,
       "photos"   => 5000,
       "todos"     => 200,
       "users"    => 10
     }

     if cat not in Map.keys(categories) do
       {:error, ~s('#{cat}' is not a valid category.) }
     else
       if id > categories[cat] do
         {:error, ~s(The maximum id for '#{cat}' is #{categories[cat]}.) }
       else
         base = "https://jsonplaceholder.typicode.com/"
         [base, cat, "/", to_string(id)]
               |> :erlang.iolist_to_binary
               |> HTTPoison.get
               |> handle_response
       end
     end
   end

   def query(cat) do

     categories = %{
       "posts"    => 100,
       "comments" => 500,
       "albums"   => 100,
       "photos"   => 5000,
       "todos"     => 200,
       "users"    => 10
     }

     if cat not in Map.keys(categories) do
       {:error, ~s('#{cat}' is not a valid category.) }
     else
         base = "https://jsonplaceholder.typicode.com/"
         [base, cat]
               |> :erlang.iolist_to_binary
               |> HTTPoison.get
               |> handle_response
     end
   end

   def handle_response( {:ok, %{status_code: 200, body: body} = _response}, keys ) do
     target = body
            |> Poison.Parser.parse!(%{})
            |> get_in(keys)

     {:ok, target}
   end

   def handle_response( {:ok, %{status_code: status, body: body} = _response}, _keys) do
     message = body
               |> Poison.Parser.parse!(%{})
               |> get_in(["message"])
     {:error, status, message }
   end

   def handle_response( {:error, reason }, _ ) do
     {:error, reason}
   end

   def handle_response( {:ok, %{status_code: 200, body: body} = _response}) do
     target = body
            |> Poison.Parser.parse!(%{})

     {:ok, target}
   end

   def handle_response( {:ok, %{status_code: status, body: body} = _response}) do
     message = body
               |> Poison.Parser.parse!(%{})
               |> get_in(["message"])
     {:error, status, message }
   end

   def handle_response( {:error, reason }) do
     {:error, reason}
   end
 end

Marked As Solved

kartheek

kartheek

@lgp :+1:

  • keys and id logic is being spread all over utility functions like get_url and handle_response.

Check if this works:

defmodule JsonApi do
  def query(cat, id \\ 0, keys \\ []) do
    categories = %{
      "posts"    => 100,
      "comments" => 500,
      "albums"   => 100,
      "photos"   => 5000,
      "todos"    => 200,
      "users"    => 10
    }
    base = "https://jsonplaceholder.typicode.com/"
    
    cond do
      cat not in Map.keys(categories) ->
        {:error, ~s('#{cat}' is not a valid category.)}

      id > categories[cat] ->
        {:error, ~s(The maximum id for '#{cat}' is #{categories[cat]}.)}

      is_list(keys) and length(keys) > 0 ->
        url = [base, cat, "/", to_string(id)]
        response = get_data(url)
        case response do
          {:ok, target} ->
            get_in(target, keys)

          _ ->
            response 
        end

      id > 0 ->
        url = [base, cat, "/", to_string(id)]
        get_data(url)

      true ->
        url = [base, cat]
        get_data(url)
    end
  end

  defp handle_response({:ok, %{status_code: 200, body: body}}) do
    target = Poison.Parser.parse!(body, %{})
    {:ok, target}
  end

  defp handle_response({:ok, %{status_code: status, body: body}}) do
    message =
      body
      |> Poison.Parser.parse!(%{})
      |> get_in(["message"])

    {:error, status, message}
  end

  defp handle_response({:error, reason}), do: {:error, reason}

  defp get_data(url) do
    url
    |> :erlang.iolist_to_binary()
    |> HTTPoison.get()
    |> handle_response()
  end
end

Also Liked

kartheek

kartheek

Hi @lgp can you add new line with ``` at the beginning of the code block and end of code blocks. You can edit post and add them:

```
Your Code
```

Also your question is not clear as to what you want to cleanup ? Can you provide more details.

kodepett

kodepett

You can convert the nested if/else to functions.

drolll

drolll

Personally, I like to paraphrase Thomas Jefferson with “One codes best who codes least”.
While I highly admire and recommend the excellent courses from Pragmatic Studios, I often wince when coming across code that is unhelpfully verbose or not refactored before put into production. With a functional language, there is seldom any advantage to the use of if-else or cond clauses IMHO.
Here’s my take:

defmodule JsonAPI do
    @cats %{"posts" => 100,"comments" => 500,"albums" => 100,"photos" => 5000,"todos" => 200,"users" => 10}
    @base "https://jsonplaceholder.typicode.com/"
    
    def query(cat, id, keys). do: check_key(cat) |> chk_range(cat, id) |> re_query(cat, id, keys) 
    def query(cat, id),       do: check_key(cat) |> chk_range(cat, id) |> re_query(cat, id)
    def query(cat),           do: check_key(cat)                       |> re_query(cat)
    
    def check_key(cat),                                      do: check_key(cat, Map.keys(@cats))
    def check_key(cat, cat_keys) when cat in cat_keys,       do: :ok
    def check_key(cat, _ ),                                  do: {:error, "'#{cat}' is not a valid category." }  
    
    def chk_range(:ok, cat, id)  when id <= @cats(cat),      do: :ok
    def chk_range(:ok, cat, _ ),                             do: {:error, "The maximum id for '#{cat}' is #{@cats[cat]}." }
    def chk_range(error, _, _ ),                             do: error
      
    def re_query(:ok, {cat, id, keys}),                      do: lookup(cat, id) |> respond(keys)
    def re_query(:ok, {cat, id      }),                      do: lookup(cat, id) |> respond
    def re_query(:ok, {cat          }),                      do: lookup(cat)     |> respond
    def re_query({:error, msg},  _   ),                      do: msg 
  
    def lookup(cat, id),                                     do: HTTPoison("#{@base}#{cat}/#{to_string(id)}")
    def lookup(cat)    ,                                     do: HTTPoison("#{@base}#{cat}")
    
    def respond( {:ok, %{status_code:  200,   body: b}}, k), do: {:ok,            get_in(Poison.Parser(b, %{}),  k      )}
    def respond( {:ok, %{status_code: status, body: b}}, _), do: {:error, status, get_in(Poison.Parser(b, %{}), ["message"])}
    def respond( {:error, reason }, _ ),                     do: {:error, reason}

    end
...

Where Next?

Popular in Questions Top

_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
Kurisu
For example for a current url like http://localhost:4000/cosmetic/products?_utf8=✓&amp;query=perfume&amp;page=2, I would like to get: ...
New
greenz1
I have a phoenix application from which a user can download multiple(5-6) files of size 1MB. I couldn’t find anything related to sending ...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? Ecto.Repo — Ecto v3.14.0 has exampl...
New
vegabook
I’m brand new to Phoenix and I have stripped one of the demo applications to the bone. I just want to get an svg up on the screen. Here i...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
yawaramin
In the Dialyzer docs ( dialyzer — OTP 29.0.2 (dialyzer 6.0.1) ), there is a way to turn off a specific warning for a function: -dialyzer...
New

Other popular topics Top

malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
AstonJ
We’ve put together this wiki for Phoenix LiveView - please feel free to add any info you feel is worth including. What is Phoenix LiveV...
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New

We're in Beta

About us Mission Statement