EctoJsonapi v0.2.0 EctoJsonapi.Load View Source

Use to convert an Ecto.Schema into Json API

Link to this section Summary

Link to this section Functions

Link to this function

load(ectos) View Source
load([Ecto.Schema]) :: map()
load(Ecto.Schema) :: map()

Convert Ecto.Schemas into a Json API map

This looks at your schema and figures out how to convert it to the Jsonapi V1.0 spec

Options

The following options are accepted:

  • :attributes - the attributes you want to return for each type of Ecto.Schema being loaded. This is a map where the key is a module name and the value is a list of fields.
    E.g. attributes: %{User => [:email, :name, :age]}. Remember, the :id is not an attribute and is always returned.

Example

Let's say you have the following data:

iex(1)>  user_with_credit_cards = %User{
...(1)>    id: 1,
...(1)>    name: "Micah Cooper",
...(1)>    email: "micah@example.com",
...(1)>    credit_cards: [
...(1)>      %CreditCard{
...(1)>        id: 456,
...(1)>        number: "4444 4444 4444 4444",
...(1)>        expiration_date: "2018-02",
...(1)>        cvv: "321",
...(1)>        user_id: 1
...(1)>      },
...(1)>      %CreditCard{
...(1)>        id: 789,
...(1)>        number: "5555 5555 5555 5555",
...(1)>        expiration_date: "2018-02",
...(1)>        cvv: "234",
...(1)>        user_id: 1
...(1)>      }
...(1)>    ]
...(1)>  }
...(1)> #Convert this to Jsonapi. Only show the `User`'s email and name
...(1)> EctoJsonapi.Load.load(user_with_credit_cards,
...(1)>                       attributes: %{User => [:email]} )
%{
 "data" => %{
   "attributes" => %{
     "email" => "micah@example.com"
   },
   "id" => 1,
   "relationships" => %{
     "credit-cards" => %{
       "data" => [
         %{"id" => 456, "type" => "credit_cards"},
         %{"id" => 789, "type" => "credit_cards"}
       ]
     },
     "events" => %{
       "data" => nil
     }
   },
   "type" => "users"
 },
 "included" => [
   %{
     "attributes" => %{
       "cvv" => "321",
       "expiration-date" => "2018-02",
       "number" => "4444 4444 4444 4444",
       "user-id" => 1
     },
     "id" => 456,
     "relationships" => %{"user" => %{"data" => %{"id" => 1, "type" => "users"}}},
     "type" => "credit_cards"
   },
   %{
     "attributes" => %{
       "cvv" => "234",
       "expiration-date" => "2018-02",
       "number" => "5555 5555 5555 5555",
       "user-id" => 1
     },
     "id" => 789,
     "relationships" => %{"user" => %{"data" => %{"id" => 1, "type" => "users"}}},
     "type" => "credit_cards"
   }
 ]
}
Link to this function

load(ectos, options) View Source
load([Ecto.Schema], %{optional(module()) => [atom()]}) :: map()
load(Ecto.Schema, %{optional(module()) => [atom()]}) :: map()