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
skander
skander2y ago
They should be available if you pull from main! Either load the calculation in your action or access it via the fields param
ZachDaniel
ZachDaniel2y ago
Yep! 🙂 @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 automatically
skander
skander2y ago
If 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
ZachDaniel
ZachDaniel2y ago
🤔 that could be problematic can you show me the code that does that? IIRC we're just iterating over fields
skander
skander2y ago
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.
skander
skander2y ago
That way expensive calculations aren't run if you didn't intend to load them in a generic /resource call
ZachDaniel
ZachDaniel2y ago
Yeah, 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.
Jan Ulbrich
Jan UlbrichOP2y ago
@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! 🎉

Did you find this page helpful?