Is it possible to directly return JSON ecnoded data in resolver

Hi all.

I have a GraphQL field exchange_rates of type [ExchangeRate], where ExchangeRate is a custom object type. The data for this field is cached in ETS and refreshed every minute.

To improve performance, I’d like to avoid redundant JSON serialization for each request by caching the JSON-serialized data in ETS. However, when I return the JSON-encoded string directly from the resolver instead of the list of Elixir data structures, Absinthe crashes the request.

Is there a way to inform Absinthe that the data is already JSON-encoded and should be served as-is in the response?

I’m aware of the workaround using a custom scalar type for this serialized JSON, but I feel it’s not elegant as it requires custom parsing on the client side and loses type safety.

Are there any other approaches or best practices for handling pre-serialized data in Absinthe resolvers while maintaining schema integrity and type safety?

Thank you for any insights or suggestions!

If you’re using Jason you can use Jason.Fragment — jason v1.4.1

1 Like

Thank you. But it looks like returning Jason.Fragment doesn’t make the response working properly. There is no exception but it returns list of one element(with values as null)

@benwilson512 Sorry to tag you but just want wonder if Jason.Fragment being supported as returned type in resolver?

Hey @bruteforcecat the issue is that Absinthe wouldn’t be running the resolvers on all of the child nodes at all. This would require some new execution directive to basically halt the tree walk and have Absinthe return the value as is.

The issue with this is that how are you or Absinthe to know what the user requested as subfields? You’re returning the same JSON blob either way regardless of whether the query document contains those fields or not.

Have you looked into whether you can cache this at the HTTP layer? It makes sense to basically cache whole document request / results but fragments are incredibly tricky to do in a way that doesn’t guarantee non spec compliant behavior.

1 Like

Thank you for the detailed answer. yea it doesn’t like it’s very hard to do given the nature of graphql that client can request sub-fields.