exAspArk / batch-loader

:zap: Powerful tool for avoiding N+1 DB or HTTP queries
https://engineering.universe.com/batching-a-powerful-way-to-solve-n-1-queries-every-rubyist-should-know-24e20c6e7b94
MIT License
1.04k stars 52 forks source link

How to get nested relation without n+1 on graphql ? #58

Closed im-not-a-robot closed 4 years ago

im-not-a-robot commented 4 years ago

Hi i have a project that use graphql and batch loader But i can't used in nested relation.

I have 3 table on my projects (Countries, Provinces, CityDistrict) When i get all the province on certain country, i can get it without n+1 problem. But the problem is i can't get country without n+1 problem.

i.e graphql query :

query city_districts {
  cityDistricts {
    edges {
      node {
        id
        name
        country{
          name
        }
        province{
          name
        }
      }
    }
  }
}

FYI: 'object' is city district it self

City District Graphql Types:

module Types
  class CityDistrictType < BaseObject
    field :id, ID, null: false
    field :name, String, null: false
    field :province, Types::ProvinceType, null: false
    field :country, Types::CountryType, null: false

    def province
        BatchLoader::GraphQL.for(object.province_id).batch do |province_ids, loader|
        Country.joins(:provinces).where("provinces.id IN (:province_ids)", province_ids:                                  province_ids).group(:id).each { |country| loader.call(country.id, country) }
      end
    end

    def country
      BatchLoader::GraphQL.for(object.province_id).batch do |province_ids, loader|
      Country.joins(:provinces).where("provinces.id IN (:province_ids)", province_ids:  province_ids).group(:id).each { |country| loader.call(country.id, country) }
          end
    end
  end
end

Result : Cannot return null for non-nullable field CityDistrict.country

Any solution ?

exAspArk commented 4 years ago

Hey,

Cannot return null for non-nullable field CityDistrict.country

It could be that your DB request in the BatchLoader::GraphQL block doesn't return any values

im-not-a-robot commented 4 years ago

Hey,

Cannot return null for non-nullable field CityDistrict.country

It could be that your DB request in the BatchLoader::GraphQL block doesn't return any values

Yes i know, But when im debug inside block, it will return the correct value Have solution?

ghost commented 4 years ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs.

im-not-a-robot commented 4 years ago

Hi, Any suggest for this ??