I need to shift the time_zone of some (DateTime) attributes from a resource. Ideally, I’d like to do it right after records are loaded from db. Is it possible? How?
There are a couple different ways you could do it, depending on the use case. Have you considered a calculation? This would let you do it on demand when you need it.
calculate :thing_in_time_zone, :datetime, YourCalculation
Then you could load that calculation when making queries using Ash.Query.load
or later using Api.load
. If you must do it on the query you can use a preparation + an after_action
hook to do it on all reads.
preparations do
prepare fn query, _ ->
Ash.Query.after_action(query, fn query, results ->
Enum.map(results, &do_whatever_you_want/1)
end)
end
end
Also, I’m not sure what Ash.Transform
is BTW, I don’t think we have anything by that name.
Thanks Zach.
Trying the second option, right now.
Is there any documentation related to preparations?
There is some frustratingly out of date bits here: Ash.Resource.Preparation — ash v2.15.6
Ultimately a preparation can look one of two ways:
prepare fn query, context ->
...
end
# or
prepare Module
prepare {Module, foo: :bar} # or with opts
defmodule Module do
use Ash.Resource.Preparation
def prepare(query, opts, context) do
query
end
end
The actions guide talks more about the lifefcycle of each action type. Actions — ash v2.15.6
Thanks, Zach. That worked.