fortune-json-api
fortune-json-api copied to clipboard
Computed properties
I would like to add computed properties to a resource, which don't map directly to the database structure. My use case is that I want to perform a count in SQL so I don't have to fetch all resources in the client application (using Ember) just to perform a count.
Model 1 - company { "id": "foo", "name": "", "stores": ["bar"] }
Model 2 - store { "id": "bar", "name": "The First Store", "products": ["baz"] } Model 3 - product { "id": "baz", "name": "A Computer" }
Now I would like to display the amount of products for a single company. I have a database with ~1.000 companies, ~5.000 stores and ~10.000 products. So instead of fetching all stores and products of a company in order to show the amount, I want to query the database directly when fetching a model (because a single SQL-query is much more performant in this case).
If I add the 'amountOfProducts' property to the record in the 'ouput' hook of the company model, it is added under the meta object.
So my question is, how can I add computed properties to a request response; which do not directly map to the database?
Many thanks in advance!
I have thought about adding this property to the meta output, but how should I do this using Fortune? It looks like only the count property is supported, and even automatically added.
https://github.com/fortunejs/fortune-json-api/blob/master/lib/index.js#L202
Is there a way to add meta-properties per resource in the output hook?
I'm not sure I understand the question. When you add properties on a record that aren't defined on the record, they end up serialized in meta on the individual resource.
You are asking about modifying the top-level meta object? This is very specific to this serializer. I'd suggest subclassing it and overriding the showResponse method.
It seems I was facing the same use case, i.e. what about derived data from the model. I updated the model, created a custom adapter which intercepts the response and updates it with the fields I needed.