I need to convert some data after every query.
ex) Change id to negative
I can add converting function for every query, but it’s pretty heavy when loading that model with preload.
defmodule MyApp.Model do
use Ecto.Schema
alias MyApp.Repo
schema "models" do
end
def get(id) do
__MODULE__
|> Repo.get(id)
|> convert_id_to_negative()
end
def list() do
__MODULE__
|> Repo.all()
|> Enum.map(&convert_id_to_negative/1)
end
def convert_id_to_negative(%__MODULE__{id: id} = struct) do
%__MODULE__{struct | id: -id}
end
end
defmodule MyApp.ParentModel do
use Ecto.Schema
alias MyApp.Repo
schema "parent_models" do
has_many :models, MyApp.Model
end
def get(id) do
__MODULE__
|> Repo.get(id)
|> Repo.preload(:models)
# missing converting
end
end
I found old codes that can be useful for this situation, like after_load/2
.
But it’s gone now. Is there any alternatives to this callback functions?