# Structuring projects - this ok?

**URL:** <https://forum.elixirforum.com/t/structuring-projects-this-ok/25040>\
**Category:** Questions\
**Tags:** project-structure\
**Created:** [August 31, 2019, 1:05pm UTC](https://forum.elixirforum.com/t/structuring-projects-this-ok/25040 "2019-08-31T13:05:06Z")\
**Posts on this page:** 6\
**Page:** 1

<div class="post-metadata">

**Author:** ![Nefcairon](https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/nefcairon/32/31921_2.png) [@Nefcairon](https://forum.elixirforum.com/u/Nefcairon)\
**Post date:** [August 31, 2019, 1:05pm UTC](https://forum.elixirforum.com/t/structuring-projects-this-ok/25040/1 "2019-08-31T13:05:06Z")

</div>

Hello,

With your help from [Generate a list of structs from a list](https://forum.elixirforum.com/t/generate-a-list-of-structs-from-a-list/20065/12) and [Improve a function](https://forum.elixirforum.com/t/to-improve-a-function/24745/11) I have now a working first simple version of my program. Before I want to extend that program, I am wondering whether the structure of my project is a good one or not.

My program just gets the data of the first 100.000 leagues (a “league” has an id, name, etc.) from an external url and inserts them into a repo.

It looks like this (I stripped the files as much as possible):

program.ex

```elixir
defmodule Program do
  use Application 

  alias Program.LeagueAPI

  def start(_type, _args) do
    children = [
      Program.Repo
    ]

    Supervisor.start_link(children, strategy: :one_for_one)
  end 

  def start() do
    for x <- 1..100_000 do 
      LeagueAPI.get_data(x) 
    end
  end
end

```

leagueAPI.ex is like that:

```elixir
defmodule Program.LeagueAPI do 

  @api_url "http://--hidden-external-api-url"

  alias ProgramAuth
  alias Program.Repo
  alias League
  import SweetXml

  defp get_url(league_id) do
    @api_url <> "&leagueID=" <> to_string(league_id)
  end 

  def get_data(league_id) do
    url = get_url(league_id)
    response = ProgramAuth.get_response(url)

    league_id =
      response.body
      |> xpath(~x"/ProgramData/LeagueID/text()"l)
      |> List.first()
      |> to_string() 

    league_name =
      response.body
      |> xpath(~x"/ProgramData/LeagueName/text()"l)
      |> List.first()
      |> to_string()

    # same for all the other fields

    %Program.League{}
    |> Ecto.Changeset.change(%{
      league_id: league_id, 
      # ... same for all the other fields
    })
    |> Repo.insert(on_conflict: :nothing)
  end
end

```

and finally league.ex is like that:

```elixir
defmodule Program.League do
  use Ecto.Schema
  import Ecto.Changeset

  schema "leagues" do
    field(:league_id, :string, unique: true)
    # same for all the other fields
    timestamps()
  end

  def changeset(league, attrs) do
    league
    |> cast(attrs, [
      :league_id, 
      # same for all the other fields
    ])
    |> validate_required([:league_id])
    |> unique_constraint(:league_id)
    |> validate_number(:league_id, greater_than_or_equal_to: Decimal.new(0))
    # same for all the other fields
  end
end

```

Is my structure with a file for the main program, one file for the schema and one for the API with the functions I implemented in there a good practise or should I put them differently?

Especially I am not sure where the Repo.insert should be placed. Should a module called leagueAPI know the Repo?  
Now Repo.insert is in the leagueAPI.ex, but maybe it should be in program.ex and leaguesAPI should only return a league (which is a schema) to program which inserts it? But should leaguesAPI know the schema “league”? Maybe it should return a list/struct instead?

It may seem that I overcomplicate things, but I think it’s better to think in correct structure before attempting much heavier implementations.

Thanks for advice 🙂

---

<div class="post-metadata">

**Author:** ![Qqwy](https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/qqwy/32/1349_2.png) [@Qqwy](https://forum.elixirforum.com/u/Qqwy)\
**Post date:** [August 31, 2019, 1:45pm UTC](https://forum.elixirforum.com/t/structuring-projects-this-ok/25040/2 "2019-08-31T13:45:39Z")

</div>

The parts where you say ‘same for all the other fields’ can probably be extracted to a separate function, to make the `get_data` function shorter/more readable. Maybe something like:

```elixir
def get_data(league_id) do
    league_id
  |> build_url()
  |> ProgramAuth.get_response()
  |> parse_response()
end

def parse_response(%{body: response_body}) do
  %Program.League{}
  |> Ecto.Changeset.change(%{
    league_id: extract_xpath(body, ~x"/ProgramData/LeagueID/text()"l),
    league_id: extract_xpath(body, ~x"/ProgramData/LeagueID/text()"l),
    # ... the same for the other fields.
  )
end

def extract_xpath(body, xpath) do
  body
  |> xpath(xpath)
  |> List.first
  |> to_string()
end

```

Also note that:

- I decided in the following example to use `get` for the HTTP request call, and `build` for local data manipulation.
- I split off from the `get_data` function a separate `parse_response` function. Besides being more readable, this also means that you can test the parsing separately from invoking the remote API.
- I did not insert anything into the repository inside the API module, to keep that module free from state-modifications. It’s probably nicer to insert the thing into the repository at the place where you call it. For instance the controller inside a Phoenix application (or, if you are working with domain-driven-design, the context module that is invoked by the controller, which itself calls into your API module as part of its work). In your example application, `Program` is indeed where I would put it.

I do think that it makes sense that the leaguesAPI knows the internals of the League datatype, since it is what it will return. You might like to have a module called `League` for the datatype, and have the API module live at `League.API` to indicate clearly that it is conceptually a part of League.

---

<div class="post-metadata">

**Author:** ![Nefcairon](https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/nefcairon/32/31921_2.png) [@Nefcairon](https://forum.elixirforum.com/u/Nefcairon)\
**Post date:** [August 31, 2019, 4:20pm UTC](https://forum.elixirforum.com/t/structuring-projects-this-ok/25040/3 "2019-08-31T16:20:51Z")

</div>

Thanks, quite a bunch of good hints. I am doing my best to get those changes in.

---

<div class="post-metadata">

**Author:** ![Nefcairon](https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/nefcairon/32/31921_2.png) [@Nefcairon](https://forum.elixirforum.com/u/Nefcairon)\
**Post date:** [August 31, 2019, 4:25pm UTC](https://forum.elixirforum.com/t/structuring-projects-this-ok/25040/4 "2019-08-31T16:25:09Z")

</div>

Is there a better way then this?

```elixir
case LeagueAPI.data(league_id) do
  {:ok, league} -> league |> Repo.insert(on_conflict: :nothing)
end

```

`LeagueAPI.data` is now giving a tuple with :ok as first element if the API fetched a valid `league`.

---

<div class="post-metadata">

**Author:** ![Qqwy](https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/qqwy/32/1349_2.png) [@Qqwy](https://forum.elixirforum.com/u/Qqwy)\
**Post date:** [September 1, 2019, 7:38am UTC](https://forum.elixirforum.com/t/structuring-projects-this-ok/25040/5 "2019-09-01T07:38:28Z")

</div>

You are close. However, what do you want to happen when the answer of `LeageAPI.data(league_id)` is `{:error, some_error}`? And are there other steps, where you only want to continue if they all are OK?

So I’d suggest either adding an `{:error, some_error}`-clause (or multiple clauses for various kinds of errors) to the `case`-statement, or instead use a `with` statement:

```elixir
with {:ok, league} <- LeagueAPI.data(league_id),
       # ... maybe some other steps,
  do
    Repo.insert(league, on_conflict: :nothing)
  else 
    # Handle error somehow
end

```

(And side note: Many developers find a simple function call more readable than a pipeline of only one function. I suggest using [credo](https://github.com/rrrene/credo) to get some tips about common ways to structure code and pitfalls to avoid, especially while still starting out. Of course many of the tips are somewhat subjective, but they are a great baseline for a starting Elixir developer.)

---

<div class="post-metadata">

**Author:** ![Nefcairon](https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/nefcairon/32/31921_2.png) [@Nefcairon](https://forum.elixirforum.com/u/Nefcairon)\
**Post date:** [September 1, 2019, 2:57pm UTC](https://forum.elixirforum.com/t/structuring-projects-this-ok/25040/6 "2019-09-01T14:57:34Z")

</div>

Thanks again 🙂
