ash-project / ash_json_api

The JSON:API extension for the Ash Framework
https://hexdocs.pm/ash_json_api
MIT License
56 stars 40 forks source link

improvement: Add calculated fields to OpenAPI, JSON schema #90

Closed skanderm closed 1 year ago

skanderm commented 1 year ago

Adds calculated fields to API responses and to OpenAPI and JSON schemas.

This is a draft since this assumes all public calculations are loaded in the actions. We could either return nil for unloaded calculations or remove the keys entirely, but I haven't exactly looked into how to do either. We could also make loaded calculations explicit in the json_api block (or each route block?).

skanderm commented 1 year ago

I think this should be ready to go, though let me know if this should go in a different direction. Calculated fields that aren't loaded just get skipped entirely.

zachdaniel commented 1 year ago

So, calculations should just automatically be loaded if they are requested in fields.

for example:

|> Ash.Query.load(fields(request, request.resource))

Is that not what you're seeing?

skanderm commented 1 year ago

Yep! There's a working test there for selecting a calculated attribute using the fields param.

The PR also adds calculated fields to the OpenAPI + JSON schema attributes for a resource, and includes calculated fields when they're loaded in the action. Otherwise they're skipped if they're not loaded and the request doesn't use the fields param (in case the calculation is expensive). Does that all make sense?

skanderm commented 1 year ago

For a little more context, I originally needed calculated fields to show up in the resources' OpenAPI schema objects for a client generator to pick up the fields + field types (and expect them in the json response).

zachdaniel commented 1 year ago

Does the schema show the keys as optional/maybe not present with this setup? If so then it should be all good 👍

skanderm commented 1 year ago

Yep, I only added calculations to the attributes key and not under required (here: OpenAPI and JSON schema). Attributes are assumed optional as long as they're not part of required.