|
| 1 | +defmodule Collections.SimpleTest do |
| 2 | + |
| 3 | + use MongoTest.Case, async: false |
| 4 | + |
| 5 | + require Logger |
| 6 | + |
| 7 | + alias Mongo |
| 8 | + alias Mongo.Collection |
| 9 | + |
| 10 | + setup_all do |
| 11 | + assert {:ok, pid} = Mongo.TestConnection.connect |
| 12 | + Mongo.drop_database(pid) |
| 13 | + {:ok, [pid: pid]} |
| 14 | + end |
| 15 | + |
| 16 | + defmodule Label do |
| 17 | + |
| 18 | + use Collection |
| 19 | + |
| 20 | + document do |
| 21 | + attribute :name, String.t(), default: "warning" |
| 22 | + attribute :color, String.t(), default: :red |
| 23 | + after_load &Label.after_load/1 |
| 24 | + end |
| 25 | + |
| 26 | + def after_load(%Label{color: color} = label) when is_binary(color) do |
| 27 | + %Label{label | color: String.to_existing_atom(color)} |
| 28 | + end |
| 29 | + def after_load(label) do |
| 30 | + label |
| 31 | + end |
| 32 | + |
| 33 | + end |
| 34 | + |
| 35 | + defmodule Card do |
| 36 | + |
| 37 | + use Collection |
| 38 | + |
| 39 | + @collection nil |
| 40 | + |
| 41 | + collection "cards" do |
| 42 | + attribute :title, String.t(), default: "new title" |
| 43 | + attribute :created, DateString.t(), default: &DateTime.utc_now/0 |
| 44 | + attribute :modified, DateString.t(), default: &DateTime.utc_now/0 |
| 45 | + embeds_one :label, Label, default: &Label.new/0 |
| 46 | + end |
| 47 | + |
| 48 | + def insert_one(%Card{} = card, top) do |
| 49 | + with map <- dump(card), |
| 50 | + {:ok, _} <- Mongo.insert_one(top, @collection, map) do |
| 51 | + :ok |
| 52 | + end |
| 53 | + end |
| 54 | + |
| 55 | + def find_one(id, top) do |
| 56 | + top |
| 57 | + |> Mongo.find_one(@collection, %{@id => id}) |
| 58 | + |> load() |
| 59 | + end |
| 60 | + |
| 61 | + end |
| 62 | + |
| 63 | + test "load and dump", _c do |
| 64 | + |
| 65 | + alias Collections.SimpleTest.Card |
| 66 | + alias Collections.SimpleTest.Label |
| 67 | + |
| 68 | + new_card = Card.new() |
| 69 | + map_card = Card.dump(new_card) |
| 70 | + |
| 71 | + assert %{title: "new title", label: %{color: :red, name: "warning"}} = map_card |
| 72 | + |
| 73 | + struct_card = Card.load(map_card, true) |
| 74 | + |
| 75 | + assert %Card{label: %Label{color: :red, name: "warning"}} = struct_card |
| 76 | + end |
| 77 | + |
| 78 | + test "save and find", c do |
| 79 | + |
| 80 | + alias Collections.SimpleTest.Card |
| 81 | + alias Collections.SimpleTest.Label |
| 82 | + |
| 83 | + new_card = Card.new() |
| 84 | + |
| 85 | + assert :ok = Card.insert_one(new_card, c.pid) |
| 86 | + |
| 87 | + card = Card.find_one(new_card._id, c.pid) |
| 88 | + |
| 89 | + assert %Card{label: %Label{color: :red, name: "warning"}} = card |
| 90 | + end |
| 91 | +end |
0 commit comments