{"id":382125,"date":"2024-06-29T04:05:05","date_gmt":"2024-06-29T04:05:05","guid":{"rendered":"http:\/\/savepearlharbor.com\/?p=382125"},"modified":"-0001-11-30T00:00:00","modified_gmt":"-0001-11-29T21:00:00","slug":"","status":"publish","type":"post","link":"https:\/\/savepearlharbor.com\/?p=382125","title":{"rendered":"<span>GraphQL without N+1 is easy. N1Loader is a must<\/span>"},"content":{"rendered":"<div><!--[--><!--]--><\/div>\n<div id=\"post-content-body\">\n<div>\n<div class=\"article-formatted-body article-formatted-body article-formatted-body_version-2\">\n<div xmlns=\"http:\/\/www.w3.org\/1999\/xhtml\">\n<p><a href=\"https:\/\/github.com\/djezzzl\/n1_loader#killer-feature-for-graphql-api\" rel=\"noopener noreferrer nofollow\">N1Loader<\/a> is designed to provide a simple way for avoiding <a href=\"https:\/\/stackoverflow.com\/questions\/97197\/what-is-the-n1-selects-problem-in-orm-object-relational-mapping\" rel=\"noopener noreferrer nofollow\">N+1 issues<\/a><br \/>of any kind. Gladly, it&#8217;s super easy to integrate with your GraphQL<br \/>API. Without further delay, let&#8217;s look at a simple but yet detailed<br \/>example.<\/p>\n<pre><code class=\"ruby\"># Add N1Loader with ArLazyPreload integration  require \"n1_loader\/ar_lazy_preload\" require 'graphql'  # Setup SQLite tables in memory. That is irrelevant to the example. require_relative 'context\/setup_database' # ArLazyPreload requires Rails application. This is needed to avoid that. require_relative 'context\/setup_ar_lazy'  class User &lt; ActiveRecord::Base   has_many :payments    n1_optimized :payments_total do |users|     # Fetch payments for a group of users we will preload in a single query     total_per_user = Payment.group(:user_id).where(user: users).sum(:amount).tap { |h| h.default = 0 }      users.each do |user|       total = total_per_user[user.id]       # No promises here, simply add a value for to a user.       fulfill(user, total)     end   end end  class Payment &lt; ActiveRecord::Base   belongs_to :user    validates :amount, presence: true end  # Enable ArLazyPreload globally ArLazyPreload.config.auto_preload = true # Or use +preload_associations_lazily+ when loading objects from database  class UserType &lt; GraphQL::Schema::Object   field :payments_total, Integer end  class QueryType &lt; GraphQL::Schema::Object   field  :users, [UserType]    def users     User.all   end end  class Schema &lt; GraphQL::Schema   query QueryType end  query_string = &lt;&lt;~GQL   {     users {       paymentsTotal     }   } GQL  # No N+1. And never will be! p Schema.execute(query_string)['data']<\/code><\/pre>\n<p><a href=\"https:\/\/github.com\/djezzzl\/n1_loader\" rel=\"noopener noreferrer nofollow\">N1Loader<\/a> supports arguments that you can pass through GraphQL API. There will no N+1 still.<\/p>\n<pre><code class=\"ruby\">class User &lt; ActiveRecord::Base   n1_optimized :payments_total do     argument :from     argument :to      def perform(users)       total_per_user =         Payment           .group(:user_id)           .where(created_at: from..to)           .where(user: users)           .sum(:amount)           .tap { |h| h.default = 0 }        users.each do |user|         total = total_per_user[user.id]         fulfill(user, total)       end     end   end end  class UserType &lt; GraphQL::Schema::Object   field :payments_total, Integer do     argument :from, Time     argument :to, Time   end end  query_string = &lt;&lt;~GQL   {     users {       paymentsTotal     }   } GQL  # No N+1. And never will be! p Schema.execute(query_string, variables: {from: 3.days.ago, to: 1.day.ago})['data']<\/code><\/pre>\n<p><em>Define loaders once &#8212; use it everywhere without N+1.<\/em><\/p>\n<p>Check <a href=\"https:\/\/github.com\/djezzzl\/n1_loader\" rel=\"noopener noreferrer nofollow\">N1Loader<\/a> for more features and give it a try in your projects.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<p><!----><!----><\/div>\n<p><!----><!----><br \/> \u0441\u0441\u044b\u043b\u043a\u0430 \u043d\u0430 \u043e\u0440\u0438\u0433\u0438\u043d\u0430\u043b \u0441\u0442\u0430\u0442\u044c\u0438 <a href=\"https:\/\/habr.com\/ru\/articles\/663830\/\"> https:\/\/habr.com\/ru\/articles\/663830\/<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<div><!--[--><!--]--><\/div>\n<div id=\"post-content-body\">\n<div>\n<div class=\"article-formatted-body article-formatted-body article-formatted-body_version-2\">\n<div xmlns=\"http:\/\/www.w3.org\/1999\/xhtml\">\n<p><a href=\"https:\/\/github.com\/djezzzl\/n1_loader#killer-feature-for-graphql-api\" rel=\"noopener noreferrer nofollow\">N1Loader<\/a> is designed to provide a simple way for avoiding <a href=\"https:\/\/stackoverflow.com\/questions\/97197\/what-is-the-n1-selects-problem-in-orm-object-relational-mapping\" rel=\"noopener noreferrer nofollow\">N+1 issues<\/a><br \/>of any kind. Gladly, it&#8217;s super easy to integrate with your GraphQL<br \/>API. Without further delay, let&#8217;s look at a simple but yet detailed<br \/>example.<\/p>\n<pre><code class=\"ruby\"># Add N1Loader with ArLazyPreload integration  require \"n1_loader\/ar_lazy_preload\" require 'graphql'  # Setup SQLite tables in memory. That is irrelevant to the example. require_relative 'context\/setup_database' # ArLazyPreload requires Rails application. This is needed to avoid that. require_relative 'context\/setup_ar_lazy'  class User &lt; ActiveRecord::Base   has_many :payments    n1_optimized :payments_total do |users|     # Fetch payments for a group of users we will preload in a single query     total_per_user = Payment.group(:user_id).where(user: users).sum(:amount).tap { |h| h.default = 0 }      users.each do |user|       total = total_per_user[user.id]       # No promises here, simply add a value for to a user.       fulfill(user, total)     end   end end  class Payment &lt; ActiveRecord::Base   belongs_to :user    validates :amount, presence: true end  # Enable ArLazyPreload globally ArLazyPreload.config.auto_preload = true # Or use +preload_associations_lazily+ when loading objects from database  class UserType &lt; GraphQL::Schema::Object   field :payments_total, Integer end  class QueryType &lt; GraphQL::Schema::Object   field  :users, [UserType]    def users     User.all   end end  class Schema &lt; GraphQL::Schema   query QueryType end  query_string = &lt;&lt;~GQL   {     users {       paymentsTotal     }   } GQL  # No N+1. And never will be! p Schema.execute(query_string)['data']<\/code><\/pre>\n<p><a href=\"https:\/\/github.com\/djezzzl\/n1_loader\" rel=\"noopener noreferrer nofollow\">N1Loader<\/a> supports arguments that you can pass through GraphQL API. There will no N+1 still.<\/p>\n<pre><code class=\"ruby\">class User &lt; ActiveRecord::Base   n1_optimized :payments_total do     argument :from     argument :to      def perform(users)       total_per_user =         Payment           .group(:user_id)           .where(created_at: from..to)           .where(user: users)           .sum(:amount)           .tap { |h| h.default = 0 }        users.each do |user|         total = total_per_user[user.id]         fulfill(user, total)       end     end   end end  class UserType &lt; GraphQL::Schema::Object   field :payments_total, Integer do     argument :from, Time     argument :to, Time   end end  query_string = &lt;&lt;~GQL   {     users {       paymentsTotal     }   } GQL  # No N+1. And never will be! p Schema.execute(query_string, variables: {from: 3.days.ago, to: 1.day.ago})['data']<\/code><\/pre>\n<p><em>Define loaders once &#8212; use it everywhere without N+1.<\/em><\/p>\n<p>Check <a href=\"https:\/\/github.com\/djezzzl\/n1_loader\" rel=\"noopener noreferrer nofollow\">N1Loader<\/a> for more features and give it a try in your projects.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<p><!----><!----><\/div>\n<p><!----><!----><br \/> \u0441\u0441\u044b\u043b\u043a\u0430 \u043d\u0430 \u043e\u0440\u0438\u0433\u0438\u043d\u0430\u043b \u0441\u0442\u0430\u0442\u044c\u0438 <a href=\"https:\/\/habr.com\/ru\/articles\/663830\/\"> https:\/\/habr.com\/ru\/articles\/663830\/<\/a><br \/><\/br><\/br><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[],"tags":[],"class_list":["post-382125","post","type-post","status-publish","format-standard","hentry"],"_links":{"self":[{"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=\/wp\/v2\/posts\/382125","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=382125"}],"version-history":[{"count":0,"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=\/wp\/v2\/posts\/382125\/revisions"}],"wp:attachment":[{"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=382125"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=382125"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=382125"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}