alecStewart1
Hello friends!
So I’ve been ticking away at a project to showcase the possible use case for using Ash and Phoenix at my place of work.
I feel like I’m missing a few things about Ash (or maybe it’s just Elixir) to fully flesh out this example project.
For starters, here’s a more “”“real world”“” example of an Ash Resource that outlines what I’m trying to do:
defmodule MyProject.Entities.State do
@moduledoc """
"""
use Ash.Resource,
data_layer: AshPostgres.DataLayer,
extensions: AshJsonApi.Resource
attributes do
uuid_primary_key :id
attribute :name, :string do
allow_nil? false
end
attribute :opt_out, :boolean do
allow_nil? false
default false
end
end
actions do
# Exposes default built in actions to manage the resource
defaults [:create, :read, :update, :destroy]
# Defines custom read action which fetches post by id.
read :by_id do
# This action has one argument :id of type :uuid
argument :id, :uuid, allow_nil?: false
# Tells us we expect this action to return a single result
get? true
filter expr(id == ^arg(:id))
end
end
code_interface do
define_for MyProject.Entities
define :create, action: :create
define :read_all, action: :read
define :update, action: :update
define :destroy, action: :destroy
define :get_by_id, args: [:id], action: :by_id
end
relationships do
belongs_to :country, MyProject.Entities.Country
has_many :counties, MyProject.Entities.County
has_many :cities, MyProject.Entities.City
end
aggregates do
count :number_of_counties, :counties do
description "Nubmer of counties in a state."
filter expr(opt_out == false)
end
list :counties_in_state, :counties, :id do
description "List of counties in the given state."
filter expr(opt_out == false)
end
count :number_of_cities, :cities do
description "Number of cities in a state"
filter expr(opt_out == false)
end
list :cities_in_state, :cities, :id do
description "List of cities in the given state."
filter expr(opt_out == false)
end
end
postgres do
table "states"
repo MyProject.Repo
end
json_api do
type "states"
routes do
base "/states"
get :by_id, route: "/:id", action: :by_id
index :read, route: "/all"
post :create
end
end
end
So a couple of questions:
-
How do I call an aggregate or calculation in a read action?
listis very useful in a lot of situations that I’d be facing. -
Is it possible or even recommended to cache the results of read actions via Cachex?
They will be used in the
json_apisection and the result of the some read actions can be quite large, some results might even be from thelisttype of aggregate or even more advanced calculations. Of course abusingMATERIALIZED VIEWis an option, but is that always recommended first before any advanced caching mechanisms?
Trending in Questions
Other Trending Topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #blog-post
- #phoenix_html
- #iex
- #graphql
- #ai
- #genstage
- #elixirconf-us
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #metaprogramming
- #security
- #hex










Showing Posts 1 to 6- Show Best Posts
- Show All Posts (oldest first)
- Show All Posts (newest first)
zachdaniel
You can use
loadto load the aggregates/calculations. You can do it on a query:Ash.Query.load(query, [:cities_in_state])or on records that you already have withApi.load(some_data, [:cities_in_state]).You can cache Ash responses, but all of the normal caveats/issues arise from doing that kind of thing
We actually do something similar for data that essentially never changes in
ash_hq. ash_hq/lib/ash_hq/docs/resources/library/library.ex at main · ash-project/ash_hq · GitHubalecStewart1
Okay. I think I’m getting the flow of things, but let me verify you. I think Java and Hibernate have just poisoned my brain so it’s definitely a lot of new things to try and grasp.
If getting an item/some items based on a single attribute of a defined resource, we can do
If getting an item/some items involves something a bit more complex (i.e. checking API permissions before everything else) we can use
preparewith a defined module that contains just apreparefunction that can take up to 3 arguments.prepareis used for, well, preparing the results of a read action.If wanting to get or rather “load” an aggregate or calculated field, we can use
Ash.Query.load.We can use this in another separately defined module and call it in the read action.
We can then use this in as
MyProject.Resources.State.cities_in_state(:some_state_id), and I believe we use it in aApi.readorApi.get!but I’m still trying to get that all straight in my head by going through the docs.In the
json_apisection, we can do the following:Hopefully I’m not too far gone and I’m mostly following the flow of using Ash.
zachdaniel
Yep, this is all good with one exception of #4, only slight semantics.
You won’t typically need to use
Ash.Query.set_resultunless you’re writing something that “pre-empts” the action (like a cache check plus result setter). But keep in mind if you want to useset_resultyou typically will want to use it in abefore_actionhook:alecStewart1
Oh okay, that actually makes it a lot clearer to understand.
I guess my only question left would be is if there’s a recommended way to organize multiple preparations for a single Ash Resource.
In the real world case at work, we’d probably be using a lot of
Ash.Query.loadandAsh.Query.after_actionfor getting the results of many different aggregates or calculations and changing the shape of the data in order to properly display it in places, so keeping all of those functions group in the same module would be useful.zachdaniel
Why would you need to use
after_actionto display loaded data? Loading it automatically puts it in the results. I’d suggest that, if you want to do lots of transformation of the results, your better bet would be to use generic actions and not after action hooks.alecStewart1
Sorry, I worded that wrong.
after_actionwouldn’t be for displaying data, we would use it for a read action to transform the data. So for certain API endpoints we can just calledAsh.Api.get!or whichever function to call the read action, and that way we can limit the logic in endpoints.Like a service in Spring that specifically gets data an endpoint will send out contains most of the logic to transform the data, as opposed to doing it in the endpoint itself.
EDIT: But I do see your point on generic actions