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.

Last Post!

gilbertosj

gilbertosj

Thank you very much @AstonJ ,
really it will suit me …
I am studying ways to apply in my code.
Thank you

Where Next?

Popular in Questions Top

vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New
Emily
I have VueJS GUIs with the project generated using Webpack. I have Elixir modules that will need to be used by the VueJS GUIs. I forese...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
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
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
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
svb
Hi! Currently I want to submit a form by pressing the Enter key. However, since my input field is of type “textarea” this is just adds a...
New

Other popular topics Top

joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
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
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
chrismccord
Phoenix 1.4.0 released Phoenix 1.4 is out! This release ships with exciting new features, most notably with HTTP2 support, improved deve...
688 31586 112
New
axelson
This post is a wiki (feel free to hit the edit button near the bottom right of this post to add your own changes!) This post collects co...
239 49266 226
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New

We're in Beta

About us Mission Statement