Skip to content

Commit

Permalink
Tweaks to allow for single instance models
Browse files Browse the repository at this point in the history
  • Loading branch information
netikular committed Feb 1, 2024
1 parent 4de5242 commit 8a90878
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 4 deletions.
4 changes: 4 additions & 0 deletions lib/dato_cms_graphql.rb
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,10 @@ def self.query(query, variables: {})
end
end

def self.query_one(query, variables: {})
Client.query(query, variables: variables).data.item.to_h.deep_transform_keys { |k| k.underscore }
end

def self.count(query, variables: {})
Client.query(query, variables: variables).data.meta_data.count
end
Expand Down
39 changes: 36 additions & 3 deletions lib/dato_cms_graphql/graphql_base.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,17 @@ module DatoCmsGraphql
class GraphqlBase
class_attribute :graphql_page_size
class_attribute :fields
class_attribute :graphql_single_instance

class << self
def page_size(value)
self.graphql_page_size = value
end

def single_instance(value)
self.graphql_single_instance = value
end

def query_name
to_s.humanize.pluralize
end
Expand All @@ -20,15 +26,22 @@ def graphql_fields(*args)

def initialize_queries
class_eval do
const_set(:INDEX, query_for)
const_set(:META_DATA, meta_data_query)
const_set(:SINGLE, query_for_single) if single_instance?
const_set(:INDEX, query_for) unless single_instance?
const_set(:META_DATA, meta_data_query) unless single_instance?
end
end

def plural_name
to_s.pluralize
end

def single_name
rv = to_s
rv[0] = rv[0].downcase
rv
end

def parse(query)
DatoCmsGraphql::Client.parse(query)
end
Expand All @@ -43,6 +56,16 @@ def query_for
GRAPHQL
end

def query_for_single
parse <<~GRAPHQL
query {
item: #{single_name} {
#{fields}
}
}
GRAPHQL
end

def meta_data_query
parse <<~GRAPHQL
query {
Expand All @@ -54,18 +77,28 @@ def meta_data_query
end

def all
raise "This is a single instance model" if single_instance?
ModelIterator.new(self)
end

def get
new(DatoCmsGraphql.query_one(self::SINGLE))
end

def single_instance?
graphql_single_instance || false
end
end

attr_reader :attributes
page_size(100) # Set the maximum page size as default.
single_instance(false)

def initialize(attributes)
@attributes = JSON.parse(attributes.to_json, object_class: OpenStruct)
end

def respond_to_missing?(method)
def respond_to_missing?(method, *args)
@attributes.respond_to?(method)
end

Expand Down
2 changes: 1 addition & 1 deletion lib/dato_cms_graphql/version.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# frozen_string_literal: true

module DatoCmsGraphql
VERSION = "0.1.1"
VERSION = "0.1.2"
end

0 comments on commit 8a90878

Please sign in to comment.