shopify_api-graphql-tiny 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 642318b955f62a8f303f68ed41165130c2c282b2f37f71f54e4b0beb68978b7f
4
+ data.tar.gz: 69d6fe346564ac10490119225043f3f338df160b7055bb74a3d30f24be4f00ff
5
+ SHA512:
6
+ metadata.gz: b6a3c1c73bc9604f96d4d8bb8ee3a30b34d3b7cfdf772069f2e62bcef7070e4c1098e6d35cf53f7fd5f040082775e80e66506b17718ba09c56deb9654244e764
7
+ data.tar.gz: 350db8c3d0db2e212533a6593119cb3fbc1db7a274a239e35c8e208bed9ddee3bd45a48300ac6fb90478025ec21ea2d2a3cf0dc3a8ec900fb801e5f7f2633030
data/.env.template ADDED
@@ -0,0 +1,9 @@
1
+ # To run tests:
2
+ #
3
+ # 1. Copy this file to .env
4
+ # 2. Fill-in the below variables with valid values.
5
+ # These values will be used by the tests. Data will be written to SHOPIFY_DOMAIN
6
+ #
7
+ SHOPIFY_DOMAIN=
8
+ SHOPIFY_TOKEN=
9
+ SHOPIFY_CUSTOMER_ID=
@@ -0,0 +1,27 @@
1
+ name: CI
2
+
3
+ on:
4
+ - push
5
+ - pull_request
6
+
7
+ jobs:
8
+ test:
9
+ runs-on: ubuntu-latest
10
+ env:
11
+ SHOPIFY_DOMAIN: "${{ secrets.SHOPIFY_DOMAIN }}"
12
+ SHOPIFY_TOKEN: "${{ secrets.SHOPIFY_TOKEN }}"
13
+ SHOPIFY_CUSTOMER_ID: "${{ secrets.SHOPIFY_CUSTOMER_ID }}"
14
+
15
+ strategy:
16
+ matrix:
17
+ ruby: ["3.1", "3.0", "2.7.2", "2.6.6", "2.5.8", "2.4.10"]
18
+
19
+ steps:
20
+ - uses: actions/checkout@v2
21
+ - uses: ruby/setup-ruby@v1
22
+ with:
23
+ bundler-cache: true
24
+ ruby-version: ${{ matrix.ruby }}
25
+
26
+ - run: bundle install
27
+ - run: bundle exec rake
data/.gitignore ADDED
@@ -0,0 +1,12 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+
10
+ # rspec failure tracking
11
+ .rspec_status
12
+ .env
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/Gemfile ADDED
@@ -0,0 +1,8 @@
1
+ source "https://rubygems.org"
2
+
3
+ git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }
4
+
5
+ # Specify your gem's dependencies in shopify_api-graphql-tiny.gemspec
6
+ gemspec
7
+
8
+ gem "dotenv", :group => "test" unless ENV["CI"]
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2021 ScreenStaring
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,70 @@
1
+ # ShopifyAPI::GraphQL::Tiny
2
+
3
+ Lightweight, no-nonsense, Shopify GraphQL Admin API client with built-in retry.
4
+
5
+ ![CI](https://github.com/ScreenStaring/shopify_api-graphql-tiny/actions/workflows/ci.yml/badge.svg)
6
+
7
+ ## Usage
8
+
9
+ ```rb
10
+ require "shopify_api/graphql/tiny"
11
+
12
+ gql = ShopifyAPI::GraphQL::Tiny.new("my-shop", token)
13
+ result = gql.execute(<<-GQL, :id => "gid://shopify/Customer/1283599123")
14
+ query findCustomer($id: ID!) {
15
+ customer(id: $id) {
16
+ id
17
+ tags
18
+ metafields(first: 10 namespace: "foo") {
19
+ edges {
20
+ node {
21
+ id
22
+ key
23
+ value
24
+ }
25
+ }
26
+ }
27
+ }
28
+ }
29
+ GQL
30
+
31
+ customer = result["data"]["customer"]
32
+ p customer["tags"]
33
+ p customer.dig("metafields", "edges", 0, "node")["value"]
34
+
35
+ updates = { :id => customer["id"], :tags => customer["tags"] + %w[foo bar] }
36
+ result = gql.execute(<<-GQL, :input => updates)
37
+ mutation customerUpdate($input: CustomerInput!) {
38
+ customerUpdate(input: $input) {
39
+ customer {
40
+ id
41
+ }
42
+ userErrors {
43
+ field
44
+ message
45
+ }
46
+ }
47
+ }
48
+ GQL
49
+
50
+ p result.dig("data", "customerUpdate", "userErrors")
51
+ ```
52
+
53
+ See [the docs](https://rdoc.info/gems/shopify_api-graphql-tiny) for complete documentation.
54
+
55
+ ## Testing
56
+
57
+ `cp env.template .env` and fill-in `.env` with the missing values. This requires a Shopify store.
58
+
59
+ ## See Also
60
+
61
+ - [Shopify Dev Tools](https://github.com/ScreenStaring/shopify-dev-tools) - Command-line program to assist with the development and/or maintenance of Shopify apps and stores
62
+ - [ShopifyAPIRetry](https://github.com/ScreenStaring/shopify_api_retry) - Retry a ShopifyAPI request if rate-limited or other errors occur (REST and GraphQL APIs)
63
+
64
+ ## License
65
+
66
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
67
+
68
+ ---
69
+
70
+ Made by [ScreenStaring](http://screenstaring.com)
data/Rakefile ADDED
@@ -0,0 +1,6 @@
1
+ require "bundler/gem_tasks"
2
+ require "rspec/core/rake_task"
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task :default => :spec
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "shopify_api/graphql/tiny"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,7 @@
1
+ module ShopifyAPI
2
+ module GraphQL
3
+ class Tiny
4
+ VERSION = "0.0.1"
5
+ end
6
+ end
7
+ end
@@ -0,0 +1,156 @@
1
+ # frozen_string_literal: true
2
+ require "json"
3
+ require "net/http"
4
+
5
+ require "shopify_api_retry"
6
+ require "shopify_api/graphql/tiny/version"
7
+
8
+ module ShopifyAPI
9
+ module GraphQL
10
+ ##
11
+ # Client to make Shopify GraphQL Admin API requests with built-in retries.
12
+ #
13
+ class Tiny
14
+ Error = Class.new(StandardError)
15
+ ConnectionError = Class.new(Error)
16
+ GraphQLError = Class.new(Error)
17
+
18
+ class HTTPError < Error
19
+ attr_reader :code
20
+
21
+ def initialize(message, code)
22
+ super(message)
23
+ @code = code
24
+ end
25
+ end
26
+
27
+ class RateLimitError < Error
28
+ attr_reader :response
29
+
30
+ def initialize(message, response)
31
+ super(message)
32
+ @response = response
33
+ end
34
+ end
35
+
36
+ SHOPIFY_DOMAIN = ".myshopify.com"
37
+
38
+ ACCESS_TOKEN_HEADER = "X-Shopify-Access-Token"
39
+ QUERY_COST_HEADER = "X-GraphQL-Cost-Include-Fields"
40
+ DEFAULT_RETRY_OPTIONS = { ConnectionError => { :wait => 3, :tries => 20 }, HTTPError => { :wait => 3, :tries => 20 } }
41
+ DEFAULT_HEADERS = { "Content-Type" => "application/json" }.freeze
42
+ ENDPOINT = "https://%s/admin/api%s/graphql.json" # Note that we omit the "/" after API for the case where there's no version.
43
+
44
+ ##
45
+ #
46
+ # Create a new GraphQL client.
47
+ #
48
+ # === Arguments
49
+ #
50
+ # [shop (String)] Shopify domain to make requests against
51
+ # [token (String)] Shopify Admin API GraphQL token
52
+ # [options (Hash)] Client options. Optional.
53
+ #
54
+ # === Options
55
+ #
56
+ # [:retry (Boolean|Hash)] +Hash+ can be retry config options. For the format see {ShopifyAPIRetry}[https://github.com/ScreenStaring/shopify_api_retry/#usage]. Defaults to +true+
57
+ # [:version (String)] Shopify API version to use. Defaults to the latest version.
58
+ # [:debug (Boolean)] Output the HTTP request/response to +STDERR+. Defaults to +false+.
59
+ #
60
+ # === Errors
61
+ #
62
+ # ArgumentError if no +shop+ or +token+ is provided.
63
+ #
64
+
65
+ def initialize(shop, token, options = nil)
66
+ raise ArgumentError, "shop required" unless shop
67
+ raise ArgumentError, "token required" unless token
68
+
69
+ @domain = shopify_domain(shop)
70
+ @options = options || {}
71
+
72
+ @headers = DEFAULT_HEADERS.dup
73
+ @headers[ACCESS_TOKEN_HEADER] = token
74
+ @headers[QUERY_COST_HEADER] = "true" if retry?
75
+
76
+ @endpoint = URI(sprintf(ENDPOINT, @domain, !@options[:version].to_s.strip.empty? ? "/#{@options[:version]}" : ""))
77
+ end
78
+
79
+ #
80
+ # Execute a GraphQL query or mutation.
81
+ #
82
+ # === Arguments
83
+ #
84
+ # [q (String)] Query or mutation to execute
85
+ # [variables (Hash)] Optional. Variable to pass to the query or mutation given by +q+
86
+ #
87
+ # === Errors
88
+ #
89
+ # ConnectionError, HTTPError, RateLimitError, GraphQLError
90
+ #
91
+ # * An HTTPError is raised of the response does not have 200 status code
92
+ # * A RateLimitError is raised if rate-limited and retries are disabled or if still rate-limited after the configured number of retry attempts
93
+ # * A GraphQLError is raised if the response contains an +errors+ property that is not a rate-limit error
94
+ #
95
+ # === Returns
96
+ #
97
+ # [Hash] The GraphQL response. Unmodified.
98
+
99
+ def execute(q, variables = nil)
100
+ config = retry? ? @options[:retry] || DEFAULT_RETRY_OPTIONS : {}
101
+ ShopifyAPIRetry::GraphQL.retry(config) { post(q, variables) }
102
+ end
103
+
104
+ private
105
+
106
+ def retry?
107
+ @options[:retry] != false
108
+ end
109
+
110
+ def shopify_domain(host)
111
+ domain = host.sub(%r{\Ahttps?://}i, "")
112
+ domain << SHOPIFY_DOMAIN unless domain.end_with?(SHOPIFY_DOMAIN)
113
+ domain
114
+ end
115
+
116
+ def post(query, variables = nil)
117
+ begin
118
+ # Newer versions of Ruby
119
+ # response = Net::HTTP.post(@endpoint, query, @headers)
120
+ params = { :query => query }
121
+ params[:variables] = variables if variables
122
+
123
+ post = Net::HTTP::Post.new(@endpoint.path)
124
+ post.body = params.to_json
125
+
126
+ @headers.each { |k,v| post[k] = v }
127
+
128
+ request = Net::HTTP.new(@endpoint.host, @endpoint.port)
129
+ request.use_ssl = true
130
+ request.set_debug_output($stderr) if @options[:debug]
131
+
132
+ response = request.start { |http| http.request(post) }
133
+ rescue => e
134
+ raise ConnectionError, "request to #@endpoint failed: #{e}"
135
+ end
136
+
137
+ # TODO: Even if non-200 check if JSON. See: https://shopify.dev/api/admin-graphql
138
+ prefix = "failed to execute query for #@domain: "
139
+ raise HTTPError.new("#{prefix}#{response.body}", response.code) if response.code != "200"
140
+
141
+ json = JSON.parse(response.body)
142
+ return json unless json.include?("errors")
143
+
144
+ errors = json["errors"].map { |e| e["message"] }.join(", ")
145
+ if json.dig("errors", 0, "extensions", "code") == "THROTTLED"
146
+ raise RateLimitError.new(errors, json) unless retry?
147
+ return json
148
+ end
149
+
150
+ raise GraphQLError, prefix + errors
151
+ end
152
+ end
153
+ end
154
+
155
+ GQL = GraphQL
156
+ end
@@ -0,0 +1,30 @@
1
+
2
+ lib = File.expand_path("../lib", __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require "shopify_api/graphql/tiny/version"
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "shopify_api-graphql-tiny"
8
+ spec.version = ShopifyAPI::GraphQL::Tiny::VERSION
9
+ spec.authors = ["Skye Shaw"]
10
+ spec.email = ["skye.shaw@gmail.com"]
11
+
12
+ spec.summary = %q{Lightweight, no-nonsense, Shopify Admin API GraphQL client with built-in retry.}
13
+ spec.homepage = "https://github.com/ScreenStaring/shopify_api-graphql-tiny"
14
+ spec.license = "MIT"
15
+
16
+ # Specify which files should be added to the gem when it is released.
17
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
18
+ spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
19
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
20
+ end
21
+ spec.bindir = "exe"
22
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
23
+ spec.require_paths = ["lib"]
24
+
25
+ spec.add_dependency "shopify_api_retry", "~> 0.2"
26
+ spec.add_development_dependency "webmock", "~> 3.0"
27
+ spec.add_development_dependency "bundler"
28
+ spec.add_development_dependency "rake", ">= 12.3.3"
29
+ spec.add_development_dependency "rspec", "~> 3.0"
30
+ end
metadata ADDED
@@ -0,0 +1,128 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: shopify_api-graphql-tiny
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.1
5
+ platform: ruby
6
+ authors:
7
+ - Skye Shaw
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2022-01-07 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: shopify_api_retry
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '0.2'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '0.2'
27
+ - !ruby/object:Gem::Dependency
28
+ name: webmock
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '3.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '3.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: bundler
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: '0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: rake
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: 12.3.3
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ version: 12.3.3
69
+ - !ruby/object:Gem::Dependency
70
+ name: rspec
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: '3.0'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: '3.0'
83
+ description:
84
+ email:
85
+ - skye.shaw@gmail.com
86
+ executables: []
87
+ extensions: []
88
+ extra_rdoc_files: []
89
+ files:
90
+ - ".env.template"
91
+ - ".github/workflows/ci.yml"
92
+ - ".gitignore"
93
+ - ".rspec"
94
+ - Gemfile
95
+ - LICENSE.txt
96
+ - README.md
97
+ - Rakefile
98
+ - bin/console
99
+ - bin/setup
100
+ - lib/shopify_api/graphql/tiny.rb
101
+ - lib/shopify_api/graphql/tiny/version.rb
102
+ - shopify_api-graphql-tiny.gemspec
103
+ homepage: https://github.com/ScreenStaring/shopify_api-graphql-tiny
104
+ licenses:
105
+ - MIT
106
+ metadata: {}
107
+ post_install_message:
108
+ rdoc_options: []
109
+ require_paths:
110
+ - lib
111
+ required_ruby_version: !ruby/object:Gem::Requirement
112
+ requirements:
113
+ - - ">="
114
+ - !ruby/object:Gem::Version
115
+ version: '0'
116
+ required_rubygems_version: !ruby/object:Gem::Requirement
117
+ requirements:
118
+ - - ">="
119
+ - !ruby/object:Gem::Version
120
+ version: '0'
121
+ requirements: []
122
+ rubyforge_project:
123
+ rubygems_version: 2.7.6
124
+ signing_key:
125
+ specification_version: 4
126
+ summary: Lightweight, no-nonsense, Shopify Admin API GraphQL client with built-in
127
+ retry.
128
+ test_files: []