EctoJsonapi v0.4.0 EctoJsonapi.Load View Source
Use to convert an Ecto.Schema
into JSON:API
Link to this section Summary
Functions
Convert Ecto.Schema
s into a Json API map
Link to this section Functions
Link to this function
detail(message) View Source
Link to this function
link(attr, arg, options) View Source
Link to this function
load(ectos) View Source
Convert Ecto.Schema
s into a Json API map
This looks at your schema and figures out how to convert it to the JSON:API V1.0 spec
Options
The following options are accepted:
:attributes
- the attributes you want to return for each type ofEcto.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 JSON:API. 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"}
]
}
},
"type" => "users",
"links" => %{
"credit-cards" => "/users/1/credit_cards",
"events" => "/users/1/events"
}
},
"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"}}},
"links" => %{"user" => "/users/1"},
"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"}}},
"links" => %{"user" => "/users/1"},
"type" => "credit_cards"
}
]
}
Link to this function