Skip to content

elixir-maru/maru_entity

Repository files navigation

Maru.Entity

Parallelizable serializer inspired by grape-entity.

Module Version Hex Docs Total Download License Last Updated CI

Usage

Installation

  1. Add maru_entity to your list of dependencies in mix.exs:

    def deps do
      [{:maru_entity, "~> 0.2.0"}]
    end
    
  2. Config :default_max_concurrency:

    config :maru_entity, default_max_concurrency: 4
    

Example

check here if you want a full example with models and serializers.

defmodule PostEntity do
  use Maru.Entity

  expose [:id, :title]
  expose :body, source: :content

  expose :disabled, if: fn(post, _options) -> post.is_disabled end
  expose :active, unless: fn(post, _options) -> post.is_disabled end

  expose :comments, [using: List[CommentEntity]], fn(post, _options) ->
    query =
      from c in Comment,
        where: c.post_id == post.id,
        select: c
    Repo.all(query)
  end
end

defmodule CommentEntity do
  use Maru.Entity

  expose [:id, :body]
  expose :author, using: AuthorEntity, batch: CommentAuthor.BatchHelper
end

defmodule AuthorEntity do
  use Maru.Entity

  expose :id
  expose :name, [], fn(author, _options) ->
    "#{author.first_name} #{author.last_name}"
  end
end

defmodule CommentAuthor.BatchHelper do
  def key(comment, _options) do
    comment.author_id
  end

  def resolve(ids) do
    query =
      from a in Author,
        where: a.id in ids,
        select: a
    Repo.all(query) |> Map.new(&{&1.id, &1})
  end
end

PostEntity.serialize(posts)

About

parallelizable serializer inspired by grape-entity

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages