gilbertosj

gilbertosj

Code improvement and how to apply a transaction?

Good Morning,
Could help me improve the code and apply a “transaction”, if one goes wrong …
I have never worked with “transaction”, so I don’t know how to apply it in this scenario.

Below is my controller

  def create(conn, %{"client" => client_params}) do
    url = "https://test.test.com.br/v2/customers/"
    headers = %{"Content-Type" => "application/json", "Authorization" => "Basic sadad=="}
    hackney = [basic_auth: {"AUTHAPI", "AUTHAPI"}]

    client_params_strong = for {key, val} <- client_params, into: %{}, do: {String.to_atom(key), val}

    body = Poison.encode!(
      %{
        ownId: Coherence.current_user(conn).id |> to_string(),
        fullname: client_params_strong.fullname,
        email: Coherence.current_user(conn).email |> to_string(),
        birthDate: client_params_strong.birthdate,
        taxDocument: %{
          type: client_params_strong.type_taxdocument,
          number: client_params_strong.number_taxdocument
        },
        phone: %{
           countryCode: client_params_strong.countrycode_phone,
           areaCode: client_params_strong.areacode_phone,
           number: client_params_strong.number_phone
        },
        shippingAddress: %{
           city: client_params_strong.city_shippingaddress,
           district: client_params_strong.district_shippingaddress,
           street: client_params_strong.street_shippingaddress,
           streetNumber: client_params_strong.streetnumber_shippingaddress,
           zipCode: client_params_strong.zipcode_shippingaddress,
           state: client_params_strong.state_shippingaddress,
           country: client_params_strong.country_shippingaddress
        }
     }

  )

    changeset = Coherence.current_user(conn)
    |> Ecto.build_assoc(:client)
    |> Client.changeset(client_params)


    #case Structure.create_client(client_params) do
    case Repo.insert(changeset) do
      {:ok, client} ->
        conn
        |> put_flash(:info, "Cliente criado com successo!")
        |> redirect(to: Routes.client_path(conn, :show, client))

      {:error, %Ecto.Changeset{} = changeset} ->
        render(conn, "new.html", changeset: changeset)
    end

    case HTTPoison.post(url, body, headers, [hackney: hackney]) do
      {:ok, %HTTPoison.Response{status_code: 400}} ->
        conn
        |> put_flash(:info, "Error 400 Bad Request")
        |> redirect(to: Routes.client_path(conn, :new))

      {:error, %HTTPoison.Error{reason: reason}} ->
        IO.inspect reason
    end

  end

Most Liked

AstonJ

AstonJ

What about Multi.run?

Multi.run

Multi allows you to run arbitrary functions as part of your transaction via run/3 and run/5 . This is especially useful when an operation depends on the value of a previous operation. For this reason, the function given as a callback to run/3 and run/5 will receive the repo as the first argument, and all changes performed by the multi so far as a map for the second argument.

The function given to run must return {:ok, value} or {:error, value} as its result. Returning an error will abort any further operations and make the whole multi fail.

In the Ecto book they use it to run a search engine update function after some db-related commands (all part of the transaction).

AstonJ

AstonJ

Not sure which parts of your code you want as part of the transaction but have a look at this thread:

There’s also a really good section on Transactions in the Programming Ecto (Pragprog) book :smiley:

The main thing to note is that you will want your non-DB part of the transaction to take place after the database part/s of the transaction.

dimitarvp

dimitarvp

I’ve used Multi.run in the past for almost the same scenario as @AstonJ mentioned, with great success.

Where Next?

Popular in Questions Top

chokchit
** (DBConnection.ConnectionError) connection not available and request was dropped from queue after 2733ms. You can configure how long re...
New
marius95
Hello everyone, I try to use an Javascript Event Handler in my root.html.leex file. Therefore I created a function in the app.js file: ...
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
nobody
How to bind a phoenix app to a specific ip address? could not find anything about that, nowhere, unfortunately, but for me this is quite...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
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
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
New

Other popular topics Top

marius95
Hello everyone, I try to use an Javascript Event Handler in my root.html.leex file. Therefore I created a function in the app.js file: ...
New
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
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
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
aesmail
Hello guys, I have finally made it. I created an admin interface for a framework. It’s been on my todo list for years and with the curre...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 52341 488
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
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
sergio
Kind of like when jquery came out, it was super necessary. Existing drag and drop libraries have a bunch of baggage to support old browse...
New

We're in Beta

About us Mission Statement