unlogic

unlogic

Insert or update with separated results

I have an API that allows users to update and insert items with a single request. It works by supplying a list of JSON objects to an endpoint that will update items where the primary key exists, and insert new items where the primary key doesn’t exist. I have this working with:

def create_machines(attrs) do
    x =
      attrs
      |> Enum.map(fn x -> get_changeset(x) end)
      |> Enum.map(fn x -> Repo.insert_or_update(x) end)
  end

  defp get_changeset(params) do
    case Repo.get_by(Machine, name: params["name"]) do
      nil ->
        # Insert a new machine
        Machine.changeset(%Machine{}, params)

      machine ->
        # Update the machine data
        Machine.changeset(machine, params)
    end
  end

I get back a list of {ok: Machine} items. What I would like to have though is a list of updated machines and a list of new machines so that the returned JSON is something like

{
  "new": 
    [
      {"name": "machine1", ...}, {...}
    ], 
  "updated": 
    [
      {"name": "machine2", ....}, .{...} 
    ] 
}

I’m just not sure how best to approach generating this result properly. I’ve tried inserting or updating the changeset in the get_changeset function so that I can return something like {:update, machine} and {:create, machine} but then I got stuck with trying to convert

[{:update, machine1}, {:update, machine2}, {:created, machine3}] 

Into the format above for display.
Any advice on what the best approach is for this? thanks

Marked As Solved

al2o3cr

al2o3cr

Enum.group_by will get you close to what you want:

iex(4)> [{:updated, "foo"}, {:updated, "bar"}, {:created, "baz"}, {:updated, "wat"}] |> Enum.group_by(fn {x, _} -> x end)
%{
  created: [created: "baz"],
  updated: [updated: "foo", updated: "bar", updated: "wat"]
}

This would still require some postprocessing of the individual lists to remove the {:created, _} wrappers around the internal elements.

Alternatively, you could use Enum.reduce with an initial state of %{new: [], updated: []} and compute what you want directly.

Where Next?

Popular in Questions 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
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
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
Kurisu
For example for a current url like http://localhost:4000/cosmetic/products?_utf8=✓&query=perfume&page=2, I would like to get: ...
New
JeremM34
Hello, how can I check the Phoenix version ? Thanks !
New
jaysoifer
Is there a way to rollback a specific migration and only that one (“skipping” all the other ones)? Would mix ecto.rollback -v 200809061...
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
beno
I will often find my self writing things similar to: case some_value do nil -> something() "" -> something() _ -> somethi...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
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

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
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
Nvim
Anybody knows a comprehensive comparison of Django and Phoenix, thanks for the help. Where are they similar? Where do they differ the m...
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
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
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
gausby
I asked this very same question on twitter and got some interesting feedback, but I thought it would be a good question to ask here as we...
1207 39297 209
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
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 47930 226
New
Qqwy
Update: How to use the Blogs & Podcasts section You can post links to your blog posts or podcasts either in one of the Official Blog...
3271 126479 1222
New

We're in Beta

About us Mission Statement