JSON-API And Calculations
Hi, I have a couple of calculations on my models and they seamlessly work in GraphQL. Now I need to make them accessible from the JSON-API and find no automatic way to address them. Do I need to write an extra-route or how should I approach this?
8 Replies
They should be available if you pull from
main
! Either load the calculation in your action or access it via the fields
paramYep! 🙂 @skander just did the work to properly hook up calculations.
I think they will need to be in
fields
no matter what, right?
It's not just any calculation that's loaded, its any calculation that is in the fields
key and is loaded
Check out the spec for more @Jan Ulbrich https://jsonapi.org
well, it loads anything in fields
automaticallyIf you don't provide a
fields
key in your request and you load the calculation via e.g. build(load: [:calculation])
it should show up too🤔 that could be problematic
can you show me the code that does that?
IIRC we're just iterating over fields
https://github.com/ash-project/ash_json_api/blob/c26e263919d52fc11b87e9aa234f5c895eccdf75/lib/ash_json_api/serializer.ex#L644 combined with https://github.com/ash-project/ash_json_api/blob/c26e263919d52fc11b87e9aa234f5c895eccdf75/lib/ash_json_api/serializer.ex#L630 - calculations are part of the default fields but if they're not loaded, they're excluded
GitHub
ash_json_api/lib/ash_json_api/serializer.ex at c26e263919d52fc11b87...
A JSON:API extension for the Ash Framework. Contribute to ash-project/ash_json_api development by creating an account on GitHub.
That way expensive calculations aren't run if you didn't intend to load them in a generic
/resource
callYeah, the primary issue with that is that it is now possible to load a calculation “by accident” if you loaded it for an action.
It has to be a public calculation of course, so not really a security risk
But peoples existing payloads will all of a sudden sometimes include additional fields.
We should make the fallback there only include attributes I think. And then if you want to include calculations you can set the
default_fields
on the route.@Zach Daniel, @skander: Hey guys, sorry that I didn’t get back earlier — too much work in my main job… 😇 I now tested with the HEAD and it works nicely this way: I don’t get the calculation by default and I get the calculation with the
fields[resource]
parameter. Thank you so much! 🎉