Magik.JsonView (magik v0.1.1)
Link to this section Summary
Functions
Render field with custom render function
View module must defines render_field/2
function to render each custom field
Render a struct to a map with given options
Render relationship field for struct. relationships
is a list of {field, view} for mapping render.
For each field, call function View.render()
to render json for relation object.
Link to this section Functions
render_custom_fields(struct, view, fields)
Render field with custom render function
View module must defines render_field/2
function to render each custom field
use JsonView
def render_field(:is_success, item) do
item.state > 3
end
render_custom_fields(struct, __MODULE__, [:is_success])
render_fields(structs, fields)
render_json(struct, view, opts)
Render a struct to a map with given options
fields
: which fields are extract directly from structcustom_fields
: which fields are render using customrender_field/2
functionrelationships
: a list of {field, view_module} defines which fields are rendered using another viewdefmodule MyApp.PostView do
use JsonView @fields [:title, :content, :excerpt, :cover] @custom_fields [:like_count] @relationships [author: MyApp.AuthorView] def render("post.json", %{post: post}) do # 1st way if `use JsonView` render_json(post, @fields, @custom_fields, @relationships) # 2nd way same as above JsonView.render_json(post, __MODULE__, fields: @fields, custom_fields: @custom_fields, relationships: @relationships ) # 3rd render manual post |> JsonView.render_fields(@fields) |> Map.merge(JsonView.render_custom_fields(post, __MODULE__, @custom_fields)) |> Map.merge(JsonView.render_relationships(post, @relationships)) end def render_field(:like_count, item) do # load like_count from some where end
end
render_relationship(struct, field, view)
render_relationships(struct, relationships)
Render relationship field for struct. relationships
is a list of {field, view} for mapping render.
For each field, call function View.render()
to render json for relation object.
Example relationships:
relationships = [comments: CommentView, author: UserView]
Result of render_relationships(post, relationships)
equal to output of below code
%{
comments: CommentView.render_many(comments, CommentView, "comment.json"),
autho: UserView.render_one(author, UserView, "user.json")
}