sezaru

sezaru

Handle dynamic calculations and aggregates in AshGraphql

I have in my resources some actions that need to do some specific calculations and aggregates, since they are very specific for the action itself (they will never be used by other actions), I don’t want to add them to my resource global list of calculations and aggregates, because of that, I add them dynamically in a preparations like this:

    defmodule Bla do
      use Ash.Resource.Calculation
      def expression(_opts, _context) do
        expr(count(:property))
      end
    end

    read :blibs do
      prepare fn query, context ->
        query
        |> Ash.Query.calculate(:blibs, :integer, Bla)
        |> Ash.Query.aggregate(:blobs, :count, :property, query: [filter: [status: :draft]])
      end
    end

Now, when I call the action, I do the dynamic calculations in the calculations field and the dynamic aggregates in the aggregates field correctly, but I can’t see them in my GraphQL api for the same action.

Is there some way to make them visible to the graphql API?

Marked As Solved

zachdaniel

zachdaniel

Creator of Ash

There are two main ways to go about this kind of thing without having to define additional resources etc.

Use action-specific metadata

read :blibs do
  prepare fn query, context ->
    query
     |> Ash.Query.calculate(:blibs, :integer, Bla)
     |> Ash.Query.aggregate(:blobs, :count, :property, query: [filter: [status: :draft]])
     |> Ash.Query.after_action(fn query, records -> 
       Enum.map(records, fn record -> 
         update_in(record.__metadata__, &Map.merge(&1, Map.take(record.calculations, [:blibs])
          # add stuff to `__metadata__`
       end)
     end)
   end

   metadata :blibs, :integer
   metadata :blobs, :integer
end

Then in your query, you must set show_metadata [:blibs, :blobs] as well as configure a new type_name (because you can’t reuse the type that is already defined that does not have these keys in it)

generic actions with custom return types

defmodule ThingWithExtra do
  use AshGraphql.Type

  use Ash.Type.NewType, subtype_of: :map, constraints: [
      fields: [
        thing: [type: :struct, constraints: [instance_of: Thing]],
        extra: [type: :string]
      ]
    ]

  def graphql_type(_), do: :thing_with_extra
end

action :thing_with_extra, ThingWithExtra do
  run fn input, _ ->
     # fetch and calculate additional stuff
     %{thing: thing, extra: "extra_stuff"}
  end
end

Also Liked

sezaru

sezaru

Just in case it is useful to someone, here is some preparations I created to abstract away some of this:

defmodule Core.Ash.Preparations.AddCalculationsToMetadata do
  @moduledoc """
  Add dynamic calculations values to metadata

  # Usage:

    prepare {#{inspect(__MODULE__)}, [:some_calculation]}
  """

  use Ash.Resource.Preparation

  def prepare(query, opts, _context) when is_list(opts) do
    Ash.Query.after_action(query, fn _, resources ->
      resources =
        Enum.map(resources, fn resource ->
          calculations = Map.take(resource.calculations, opts)

          update_in(resource.__metadata__, &Map.merge(&1, calculations))
        end)

      {:ok, resources}
    end)
  end
end
defmodule Core.Ash.Preparations.AddAggregatesToMetadata do
  @moduledoc """
  Add dynamic aggregates values to metadata

  # Usage:

    prepare {#{inspect(__MODULE__)}, [:some_aggregate]}
  """

  use Ash.Resource.Preparation

  def prepare(query, opts, _context) when is_list(opts) do
    Ash.Query.after_action(query, fn _, resources ->
      resources =
        Enum.map(resources, fn resource ->
          calculations = Map.take(resource.aggregates, opts)

          update_in(resource.__metadata__, &Map.merge(&1, calculations))
        end)

      {:ok, resources}
    end)
  end
end
ken-kost

ken-kost

From docs

The calculations declared on a resource allow for declaring a set of named calculations that can be used by extensions. … Calculations declared on the resource will be keys in the resource’s struct.

But you’re doing custom calculations.

I think the problem here is that, since the calculation is not declared on a resource, it’s not a present key in that resource type.
So

  graphql do
    type :your_resource
  end

will not have those dynamic calculations and it will not be picked up by the graphQL extension.

since they are very specific for the action itself (they will never be used by other actions)

wdym by this? A calculation is specific to some resource, it’s not global per say. I don’t see why you don’t write your calculations and aggregates normally to be honest. :man_shrugging:

sezaru

sezaru

Because they get noisy in big resources. If I want to do a calculation that only makes sense in the context of an action, then I want to define it in that action only instead of making it available for the full resource.

Where Next?

Popular in Questions Top

_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
New
mgjohns61585
Could someone help me? I’m making my first elixir program, number guessing game. I can’t figure out how to convert the user’s guess from ...
New
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
New
tduccuong
Hi, is there any work on GUI with Elixir, that is similar to Electron/Javascript? My idea is to bundle Phoenix and BEAM into a single se...
New
beno
I will often find my self writing things similar to: case some_value do nil -> something() "" -> something() _ -> somethi...
New
RisingFromAshes
I’ve read in another post that it may be possible with a router helper - but I couldn’t find an appropriate one, and tbh, I’m still just ...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
PeterCarter
There are pre-rolled solutions for other frameworks that do work. However, Phoenix does not seem to have these. Have people had good expe...
New

Other popular topics Top

aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
marius95
Hello everyone, I try to use an Javascript Event Handler in my root.html.leex file. Therefore I created a function in the app.js file: ...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 43622 214
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
komlanvi
Hi everyone, I was playing with phoenix liveView but I run into an issue. I have a form and want to validate each input text when the te...
New
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New
PeterCarter
There are pre-rolled solutions for other frameworks that do work. However, Phoenix does not seem to have these. Have people had good expe...
New

We're in Beta

About us Mission Statement