Skip to content

[Question] Eager-loading on specific operations only? #618

Open
@osteel

Description

@osteel

Hi there,

I'm working on a project where users can view their timesheets, which are collections of time entries. They can query them as JSON which is then parsed and displayed in a UI, or they can export the results as a CSV file.

The way I implemented it, the former is done through a regular JSON:API relationship request, e.g.:

[GET] /users/{id}/time-entries

And the latter is done via a custom export action:

[GET] /users/{id}/time-entries/export

For this I've got a exportTimeEntries method in the UsersController controller, and the route is declared like this (shortened for readability):

$api->resource('users')->controller(UsersController::class)->routes(function ($registrar) {
    $registrar->field('time-entries')->get('{record}/time-entries/export', 'exportTimeEntries');
});

In exportTimeEntries, I inject StoreInterface and FetchRelated objects so I can basically reuse the same parameters and logic as the regular GET endpoint to fetch the user's time entries, but instead of returning the collection as is I then export it as a CSV file.

I hope this gives you enough context. Now, the difference between the regular GET endpoint and the export one, is that for the former the API consumer chooses what resources they want to include with the time entries (such as the related task, so they can display the task name corresponding to the time entry, for instance).

For the export action, however, I know I need these related resources to add the corresponding info to the CSV file, so I want to eager-load them.

Hence my question: is there a way to specify resources to be eager-loaded for a specific action only? Or can I hook into something to add these resource inclusions before the query is executed? I tried to fiddle around the EncodingParameters objects but got nowhere.

My solution at the moment is to eager-load these resources for all the time entry operations (with $defaultWith set on the adapter), which is obviously not ideal.

Any ideas?

Cheers,

Yannick

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions