|
| 1 | +defmodule Mongo.Ecto.ConversionsTest do |
| 2 | + use ExUnit.Case, async: true |
| 3 | + |
| 4 | + alias Mongo.Ecto.Conversions |
| 5 | + |
| 6 | + describe "from_ecto_pk/2" do |
| 7 | + test "renames the primary key to :_id at the top level" do |
| 8 | + assert {:ok, encoded} = Conversions.from_ecto_pk(%{id: "abc", title: "t"}, :id) |
| 9 | + |
| 10 | + assert Map.new(encoded) == %{_id: "abc", title: "t"} |
| 11 | + end |
| 12 | + |
| 13 | + test "does not rename :id inside a nested map when the parent pk is :id" do |
| 14 | + input = %{ |
| 15 | + id: "abc", |
| 16 | + title: "outer", |
| 17 | + jurisdiction: %{id: "MD", title: "Maryland"} |
| 18 | + } |
| 19 | + |
| 20 | + assert {:ok, encoded} = Conversions.from_ecto_pk(input, :id) |
| 21 | + |
| 22 | + encoded_map = Map.new(encoded) |
| 23 | + assert encoded_map[:_id] == "abc" |
| 24 | + refute Map.has_key?(encoded_map, :id) |
| 25 | + |
| 26 | + # The nested :id field must be passed through unchanged — it belongs to |
| 27 | + # the embedded sub-document, not the parent schema. |
| 28 | + assert Map.new(encoded_map[:jurisdiction]) == %{id: "MD", title: "Maryland"} |
| 29 | + end |
| 30 | + |
| 31 | + test "does not rename :id inside a list of nested maps" do |
| 32 | + input = %{id: "abc", items: [%{id: "one"}, %{id: "two"}]} |
| 33 | + |
| 34 | + assert {:ok, encoded} = Conversions.from_ecto_pk(input, :id) |
| 35 | + |
| 36 | + encoded_map = Map.new(encoded) |
| 37 | + assert encoded_map[:_id] == "abc" |
| 38 | + |
| 39 | + assert Enum.map(encoded_map[:items], &Map.new/1) == [ |
| 40 | + %{id: "one"}, |
| 41 | + %{id: "two"} |
| 42 | + ] |
| 43 | + end |
| 44 | + |
| 45 | + test "leaves nested maps alone when the pk is nil" do |
| 46 | + input = %{id: "abc", jurisdiction: %{id: "MD"}} |
| 47 | + |
| 48 | + assert {:ok, encoded} = Conversions.from_ecto_pk(input, nil) |
| 49 | + |
| 50 | + encoded_map = Map.new(encoded) |
| 51 | + assert encoded_map[:id] == "abc" |
| 52 | + assert Map.new(encoded_map[:jurisdiction]) == %{id: "MD"} |
| 53 | + end |
| 54 | + end |
| 55 | + |
| 56 | + describe "inject_params/3" do |
| 57 | + test "renames the primary key to :_id only at the top level" do |
| 58 | + input = %{ |
| 59 | + id: "abc", |
| 60 | + jurisdiction: %{id: "MD", title: "Maryland"} |
| 61 | + } |
| 62 | + |
| 63 | + assert {:ok, encoded} = Conversions.inject_params(input, {}, :id) |
| 64 | + |
| 65 | + encoded_map = Map.new(encoded) |
| 66 | + assert encoded_map[:_id] == "abc" |
| 67 | + refute Map.has_key?(encoded_map, :id) |
| 68 | + |
| 69 | + assert Map.new(encoded_map[:jurisdiction]) == %{id: "MD", title: "Maryland"} |
| 70 | + end |
| 71 | + end |
| 72 | +end |
0 commit comments