JSONAPI-Resources / JSONAPI-Resources/jsonapi-resources

Reducing N+1 queries by eager loading

Offen
#485 10 Kommentare 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

Type: Maintenance
Vorherrschende Sprache
Ruby
Sterne
2.3k
Forks
546
PR-Merge-Kennzahlen
Keine gemergten PRs in 30 T.

Beschreibung

I read through the documentation and couldn't find a built-in solution to this problem. When certain models are serialized we need to make sure that the query to retrieve that entity always adds an includes to avoid all the lazy loaded N+1 queries. We can do this via records as long as the request is on the resources controller. If it's not then I couldn't see a place to extend it.

Let me give an example

class ProjectResource
  has_one :company
end
class CompanyResource
  attribute :plan_start_at

  def plan_start_at
    @model.subscription.created_at
  end
end

As you'll notice each time a company is rendered it is going to retrieve a value out of it's subscription. However, the problem comes in when we request a URL like this

/api/projects?include=company

It's using the records method off of the projects resource and even when it goes to process the include on company it's not calling records on the company resource so we end up with a separate query for every companies subscription.

Now, from what I can tell maybe this is supposed to be taken care of by also requesting the subscription like this

/api/projects?include=company,company.subscription

However this doesn't completely work since I don't need the subscription object and requesting the subscription isn't a concern of the client (since we simply need the subscription in order to calculate a property on the company.)

Beitragsleitfaden

Für dieses Repository ist kein Beitragsleitfaden indexiert

Erste Schritte

  1. Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
  3. Forke das Repository und arbeite in einem Branch.
  4. Öffne einen Pull Request, der die Issue-Nummer nennt.

Rechercherichtung

Beginne damit, den Ressourcen-Controller, die records-Methode und die für ProjectResource und CompanyResource beschriebene include-Verarbeitung nachzuverfolgen. Reproduziere den Fall /api/projects?include=company und vergleiche ihn mit company.subscription; erledigt ist die Aufgabe, wenn abhängige Daten, die von berechneten Attributen verwendet werden, eager geladen werden, ohne dass Clients diese Beziehung anfordern müssen.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
rails, ruby
Bereich
api, backend, performance
Issue-Typ
Feature
Schwierigkeit
5/5
Geschätzter Aufwand
Über eine Woche
Aktivitätsstatus
Veraltet
Klarheit
Muss geklärt werden
Anfängerfreundlichkeit
25/100

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.