Module: Dato::ApiClient::ClassMethods

Defined in:
lib/dato/api_client.rb

Instance Method Summary collapse

Instance Method Details

#json_schema(subdomain) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/dato/api_client.rb', line 28

def json_schema(subdomain)
  define_method(:initialize) do |token, options = {}|
    @token = token
    @base_url = options[:base_url] || "https://#{subdomain}.datocms.com"
    @extra_headers = options[:extra_headers] || {}
  end

  response = Faraday.get(
    # FOR DEV
    # "http://#{subdomain}.lvh.me:3001/docs/#{subdomain}-hyperschema.json"
    "https://#{subdomain}.datocms.com/docs/#{subdomain}-hyperschema.json"
  )

  schema = JsonSchema.parse!(JSON.parse(response.body))
  schema.expand_references!

  schema.definitions.each do |type, schema|
    is_collection = schema.links.select { |x| x.rel === 'instances' }.any?
    namespace = is_collection ? type.pluralize : type

    define_method(namespace) do
      instance_variable_set(
        "@#{namespace}",
        instance_variable_get("@#{namespace}") ||
        Dato::Repo.new(self, type, schema)
      )
    end
  end
end