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.

Last Post!

unlogic

unlogic

Thank you for your reply. I ended up going with the reduce as it seemed simpler

attrs
    |> Enum.reduce(%{new: [], updated: []}, fn x, acc ->
      case Repo.get_by(Machine, name: x["name"]) do
        nil ->
          # Insert a new machine
          {:ok, machine} = Repo.insert(Machine.changeset(%Machine{}, x))
          new_list = acc.new ++ [machine]
          %{new: new_list, updated: acc.updated}

        machine ->
          # Update the machine data
          {:ok, machine} = Repo.update(Machine.changeset(machine, x))
          updated_list = acc.updated ++ [machine]
          %{new: acc.new, updated: updated_list}
      end
    end)

Where Next?

Popular in Questions Top

jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod – where is this set? Thanks.
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
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
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
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
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

Other popular topics Top

nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod – where is this set? Thanks.
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
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
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
saif
Hello everyone, Long time lurker first time poster here. I’ve recently begun working on Elixir full-time again! :raised_hands: It’s been...
New

We're in Beta

About us Mission Statement