gilbertosj
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
Trending in Questions
Hey guys,
I’ve got a huge CSV ( around 10 GB ) that needs to be processed hourly
Do you guys have any suggestions what is the best prac...
New
Hello!
Could someone please give me a help/sample code, how to delete a file from s3 using waffle/waffle_ecto from Phoenix app.
I creat...
New
I have what I’ve heard referred to as a “lookup table” in my database. This is a way of assigning codes to common values. One common lo...
New
What approach to take when sending live updates to “random” users Hi! I have a question, I have a little chat app, and when I create a DM...
New
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
Anyone here using Honeybadger?
My Honeybadger account is being overwhelmed with noise from some bots. Seeing a lot of
Bandit.HTTPError...
New
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
Other Trending Topics
I am happy to introduce the very α version of the new programming language compiled to BEAM.
Welcome Cure.
It has literally three kille...
New
Hobbes is a low-level distributed database for the Elixir programming language.
Hobbes provides a simple, safe, and scalable storage lay...
New
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge & Solve.
They are GUI (Emerge) and State management (S...
New
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
There are three potential reasons for members of this forum to have a look at https://vutuv.de
You are tired or annoyed of LinkedIn.
Yo...
New
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #elixirconf
- #channels
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #blog-post
- #elixir-ls
- #ai
- #elixirconf-us
- #phoenix_html
- #iex
- #graphql
- #genstage
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #hex
- #security
- #metaprogramming










Showing Posts 1 to 7- Show Best Posts
- Show All (oldest first)
- Show All (newest first)
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
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.
gilbertosj
I forgot to talk about where I want to apply this transaction, sorry.
So there is 2 insert.
1 = local database
case Repo.insert(changeset) do2 = Api (via post)
case HTTPoison.post(url, body, headers, [hackney: hackney]) doI want to put a transaction (rollback) in case of any error in either.
Thanks @AstonJ , I will look for more on how to do this.
kokolegorille
There is no transaction in API call, at least not something as a DB transaction. You could probably send a delete command if this is enough to rollback.
Maybe do API call first?
Then DB if Api call has succeed?
axelson
As @kokolegorille said, a database transcation only covers a single database. If you want to wrap up an DB insert with a remote API call then you need to reach for a heavier weight tool. The most common one is Sage: GitHub - Nebo15/sage: A dependency-free tool to run distributed transactions in Elixir, inspired by Sagas pattern. · GitHub
It can help you write the code to handle if either step fails (sometimes you will need to write code that “undoes” an action).
AstonJ
What about
Multi.run?In the Ecto book they use it to run a search engine update function after some db-related commands (all part of the transaction).
dimitarvp
I’ve used
Multi.runin the past for almost the same scenario as @AstonJ mentioned, with great success.gilbertosj
Thank you very much @AstonJ ,
really it will suit me …
I am studying ways to apply in my code.
Thank you