sezaru

sezaru

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?

Showing Posts 1 to 5

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 OP

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.

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
sezaru

sezaru OP

Amazing as always! Thanks a lot Zack!

sezaru

sezaru OP

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
— All posts loaded —

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
FlyingNoodle
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
New

Other Trending Topics Top

mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
webofbits
With AI doing more of the implementation work, I’ve been wondering how much coding I should deliberately keep doing myself. My main conc...
#ai
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews