├── .github └── workflows │ ├── ci.yml │ └── publish.yml ├── .gitignore ├── .rspec ├── .rubocop.yml ├── .ruby-version ├── Gemfile ├── LICENSE ├── README.md ├── Rakefile ├── bin ├── console └── setup ├── examples └── examples.rb ├── lib ├── microcms.rb └── microcms │ └── version.rb ├── microcms.gemspec └── spec ├── microcms_spec.rb └── spec_helper.rb /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: Test 2 | 3 | on: 4 | push: 5 | branches: [ main ] 6 | pull_request: 7 | branches: [ main ] 8 | jobs: 9 | lint: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - name: Checkout code 13 | uses: actions/checkout@v2 14 | 15 | - name: Setup Ruby and install gems 16 | uses: ruby/setup-ruby@v1 17 | with: 18 | ruby-version: 2.7 19 | bundler-cache: true 20 | 21 | - name: Run linters 22 | run: | 23 | bundle install && bundle exec rubocop 24 | 25 | test: 26 | runs-on: ubuntu-latest 27 | strategy: 28 | matrix: 29 | ruby-version: [2.6, 2.7, 3.0] 30 | steps: 31 | - name: Checkout code 32 | uses: actions/checkout@v2 33 | 34 | - name: Set up Ruby 35 | uses: ruby/setup-ruby@v1 36 | with: 37 | ruby-version: ${{ matrix.ruby-version }} 38 | bundler-cache: true 39 | 40 | - name: test 41 | run: | 42 | bundle install && bundle exec rspec 43 | -------------------------------------------------------------------------------- /.github/workflows/publish.yml: -------------------------------------------------------------------------------- 1 | name: Ruby Gem 2 | 3 | on: 4 | push: 5 | tags: 6 | - v* 7 | 8 | jobs: 9 | build: 10 | name: Build + Publish 11 | runs-on: ubuntu-latest 12 | permissions: 13 | contents: read 14 | packages: write 15 | 16 | steps: 17 | - uses: actions/checkout@v2 18 | - name: Set up Ruby 2.6 19 | uses: actions/setup-ruby@v1 20 | with: 21 | ruby-version: 2.6.x 22 | 23 | - name: Publish to RubyGems 24 | run: | 25 | mkdir -p $HOME/.gem 26 | touch $HOME/.gem/credentials 27 | chmod 0600 $HOME/.gem/credentials 28 | printf -- "---\n:rubygems_api_key: ${GEM_HOST_API_KEY}\n" > $HOME/.gem/credentials 29 | gem build *.gemspec 30 | gem push *.gem 31 | env: 32 | GEM_HOST_API_KEY: "${{secrets.RUBYGEMS_AUTH_TOKEN}}" 33 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /.bundle/ 2 | /.yardoc 3 | /_yardoc/ 4 | /coverage/ 5 | /doc/ 6 | /pkg/ 7 | /spec/reports/ 8 | /tmp/ 9 | Gemfile.lock 10 | -------------------------------------------------------------------------------- /.rspec: -------------------------------------------------------------------------------- 1 | --require spec_helper 2 | -------------------------------------------------------------------------------- /.rubocop.yml: -------------------------------------------------------------------------------- 1 | AllCops: 2 | TargetRubyVersion: 2.6 3 | NewCops: enable 4 | 5 | Metrics/BlockLength: 6 | Exclude: 7 | - 'spec/**/*' 8 | 9 | Style/OpenStructUse: 10 | Exclude: 11 | - 'spec/**/*' 12 | -------------------------------------------------------------------------------- /.ruby-version: -------------------------------------------------------------------------------- 1 | 2.7.2 2 | -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | source 'https://rubygems.org' 4 | 5 | # Specify your gem's dependencies in microcms.gemspec 6 | gemspec 7 | 8 | gem 'rake', '~> 12.0' 9 | 10 | gem 'rubocop', require: false 11 | 12 | gem 'rspec', require: false 13 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # microCMS Ruby SDK 2 | 3 | [microCMS](https://document.microcms.io/manual/api-request) Ruby SDK. 4 | 5 | ## Tutorial 6 | 7 | See [official tutorial](https://document.microcms.io/tutorial/ruby/ruby-top). 8 | 9 | ## Installation 10 | 11 | Add this line to your application's Gemfile: 12 | 13 | ```ruby 14 | gem 'microcms-ruby-sdk' 15 | ``` 16 | 17 | And then execute: 18 | 19 | $ bundle install 20 | 21 | Or install it yourself as: 22 | 23 | $ gem install microcms-ruby-sdk 24 | 25 | ## Usage 26 | 27 | ### Import 28 | 29 | ```rb 30 | require 'microcms' 31 | ``` 32 | 33 | ### Create client object 34 | 35 | ```rb 36 | MicroCMS.service_domain = 'YOUR_DOMAIN' 37 | MicroCMS.api_key = 'YOUR_API_KEY' 38 | ``` 39 | 40 | Note that the `YOUR_DOMAIN` is the subdomain name of your service (not the FQDN). 41 | 42 | ### Get content list 43 | 44 | ```rb 45 | puts MicroCMS.list('endpoint') 46 | ``` 47 | 48 | ### Get content list with parameters 49 | 50 | ```rb 51 | puts MicroCMS.list( 52 | 'endpoint', 53 | { 54 | draft_key: "abcd", 55 | limit: 100, 56 | offset: 1, 57 | orders: ['updatedAt'], 58 | q: 'Hello', 59 | fields: %w[id title], 60 | ids: ['foo'], 61 | filters: 'publishedAt[greater_than]2021-01-01', 62 | depth: 1, 63 | }, 64 | ) 65 | ``` 66 | 67 | ### Get single content 68 | 69 | ```rb 70 | puts MicroCMS.get('endpoint', 'ruby') 71 | ``` 72 | 73 | ### Get single content with parameters 74 | 75 | ```rb 76 | puts MicroCMS.get( 77 | 'endpoint', 78 | 'ruby', 79 | { 80 | draft_key: 'abcdef1234', 81 | fields: %w[title publishedAt], 82 | depth: 1, 83 | }, 84 | ) 85 | ``` 86 | 87 | ### Get object form content 88 | 89 | ```rb 90 | puts MicroCMS.get('endpoint') 91 | ``` 92 | 93 | ### Create content 94 | 95 | ```rb 96 | puts MicroCMS.create('endpoint', { text: 'Hello, microcms-ruby-sdk!' }) 97 | ``` 98 | 99 | ### Create content with specified ID 100 | 101 | ```rb 102 | puts MicroCMS.create( 103 | 'endpoint', 104 | { 105 | id: 'my-content-id', 106 | text: 'Hello, microcms-ruby-sdk!', 107 | }, 108 | ) 109 | ``` 110 | 111 | ### Create draft content 112 | 113 | ```rb 114 | puts MicroCMS.create( 115 | 'endpoint', 116 | { 117 | id: 'my-content-id', 118 | text: 'Hello, microcms-ruby-sdk!', 119 | }, 120 | { status: 'draft' }, 121 | ) 122 | ``` 123 | 124 | ### Update content 125 | 126 | ```rb 127 | 128 | puts MicroCMS.update( 129 | 'endpoint', 130 | { 131 | id: 'microcms-ruby-sdk', 132 | text: 'Hello, microcms-ruby-sdk update method!', 133 | }, 134 | ) 135 | ``` 136 | 137 | ### Update object form content 138 | 139 | ```rb 140 | puts MicroCMS.update('endpoint', { text: 'Hello, microcms-ruby-sdk update method!' }) 141 | ``` 142 | 143 | ### Delete content 144 | 145 | ```rb 146 | MicroCMS.delete('endpoint', 'microcms-ruby-sdk') 147 | ``` 148 | 149 | ## Development 150 | 151 | After checking out the repo, run `bin/setup` to install dependencies. You can also run `bin/console` for an interactive prompt that will allow you to experiment. 152 | 153 | To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org). 154 | 155 | ## Contributing 156 | 157 | Bug reports and pull requests are welcome on GitHub at . 158 | -------------------------------------------------------------------------------- /Rakefile: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require 'bundler/gem_tasks' 4 | task default: :spec 5 | -------------------------------------------------------------------------------- /bin/console: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # frozen_string_literal: true 3 | 4 | require 'bundler/setup' 5 | require 'microcms' 6 | 7 | # You can add fixtures and/or initialization code here to make experimenting 8 | # with your gem easier. You can also use a different console, if you like. 9 | 10 | # (If you use this, don't forget to add pry to your Gemfile!) 11 | # require "pry" 12 | # Pry.start 13 | 14 | require 'irb' 15 | IRB.start(__FILE__) 16 | -------------------------------------------------------------------------------- /bin/setup: -------------------------------------------------------------------------------- 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 9 | -------------------------------------------------------------------------------- /examples/examples.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | MicroCMS.service_domain = ENV.fetch('YOUR_DOMAIN', nil) 4 | MicroCMS.api_key = ENV.fetch('YOUR_API_KEY', nil) 5 | 6 | endpoint = ENV.fetch('YOUR_ENDPOINT', nil) 7 | 8 | puts MicroCMS.list(endpoint) 9 | 10 | puts MicroCMS.list(endpoint, { 11 | limit: 100, 12 | offset: 1, 13 | orders: ['updatedAt'], 14 | q: 'Hello', 15 | fields: %w[id title], 16 | filters: 'publishedAt[greater_than]2021-01-01' 17 | }) 18 | 19 | puts MicroCMS.get(endpoint, 'ruby') 20 | 21 | puts MicroCMS.get(endpoint, 'ruby', { draft_key: 'abcdef1234' }) 22 | 23 | puts MicroCMS.create(endpoint, { text: 'Hello, microcms-ruby-sdk!' }) 24 | 25 | puts MicroCMS.create(endpoint, { id: 'microcms-ruby-sdk', text: 'Hello, microcms-ruby-sdk!' }) 26 | 27 | puts MicroCMS.create(endpoint, { text: 'Hello, microcms-ruby-sdk!' }, { status: 'draft' }) 28 | 29 | puts MicroCMS.update(endpoint, { id: 'microcms-ruby-sdk', text: 'Hello, microcms-ruby-sdk update method!' }) 30 | 31 | MicroCMS.delete(endpoint, 'microcms-ruby-sdk') 32 | -------------------------------------------------------------------------------- /lib/microcms.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require 'microcms/version' 4 | require 'net/http' 5 | require 'uri' 6 | require 'json' 7 | require 'forwardable' 8 | 9 | # MicroCMS 10 | module MicroCMS 11 | class << self 12 | extend Forwardable 13 | 14 | attr_accessor :api_key, :service_domain 15 | 16 | delegate %i[list get create update delete] => :client 17 | 18 | def client 19 | Client.new(@service_domain, @api_key) 20 | end 21 | end 22 | 23 | # HttpUtil 24 | module HttpUtil 25 | def send_http_request(method, endpoint, path, query = nil, body = nil) 26 | uri = build_uri(endpoint, path, query) 27 | http = build_http(uri) 28 | req = build_request(method, uri, body) 29 | res = http.request(req) 30 | 31 | raise APIError.new(status_code: res.code.to_i, body: res.body) if res.code.to_i >= 400 32 | 33 | JSON.parse(res.body, object_class: OpenStruct) if res.header['Content-Type'].include?('application/json') # rubocop:disable Style/OpenStructUse 34 | end 35 | 36 | private 37 | 38 | def get_request_class(method) 39 | { 40 | GET: Net::HTTP::Get, 41 | POST: Net::HTTP::Post, 42 | PUT: Net::HTTP::Put, 43 | PATCH: Net::HTTP::Patch, 44 | DELETE: Net::HTTP::Delete 45 | }[method] 46 | end 47 | 48 | def build_request(method, uri, body) 49 | req = get_request_class(method.to_sym).new(uri.request_uri) 50 | req['X-MICROCMS-API-KEY'] = @api_key 51 | if body 52 | req['Content-Type'] = 'application/json' 53 | req.body = JSON.dump(body) 54 | end 55 | 56 | req 57 | end 58 | 59 | def build_uri(endpoint, path, query) 60 | origin = "https://#{@service_domain}.microcms.io" 61 | path_with_id = path ? "/api/v1/#{endpoint}/#{path}" : "/api/v1/#{endpoint}" 62 | encoded_query = 63 | if !query || query.size.zero? 64 | '' 65 | else 66 | "?#{URI.encode_www_form(query)}" 67 | end 68 | 69 | URI.parse("#{origin}#{path_with_id}#{encoded_query}") 70 | end 71 | 72 | def build_http(uri) 73 | http = Net::HTTP.new(uri.host, uri.port) 74 | http.use_ssl = true 75 | 76 | http 77 | end 78 | end 79 | 80 | # Client 81 | class Client 82 | include HttpUtil 83 | 84 | def initialize(service_domain, api_key) 85 | @service_domain = service_domain 86 | @api_key = api_key 87 | end 88 | 89 | def list(endpoint, option = {}) 90 | list = send_http_request('GET', endpoint, nil, build_query(option)) 91 | if list[:totalCount] 92 | list[:total_count] = list[:totalCount] 93 | list.delete_field(:totalCount) 94 | end 95 | list 96 | end 97 | 98 | def get(endpoint, id = '', option = {}) 99 | send_http_request( 100 | 'GET', 101 | endpoint, 102 | id, 103 | { 104 | draftKey: option[:draft_key], 105 | fields: option[:fields] ? option[:fields].join(',') : nil, 106 | depth: option[:depth] 107 | }.select { |_key, value| value } 108 | ) 109 | end 110 | 111 | def create(endpoint, content, option = {}) 112 | if content[:id] 113 | put(endpoint, content, option) 114 | else 115 | post(endpoint, content, option) 116 | end 117 | end 118 | 119 | def update(endpoint, content) 120 | body = content.reject { |key, _value| key == :id } 121 | send_http_request('PATCH', endpoint, content[:id], nil, body) 122 | end 123 | 124 | def delete(endpoint, id) 125 | send_http_request('DELETE', endpoint, id) 126 | end 127 | 128 | private 129 | 130 | # rubocop:disable Style/MethodLength 131 | def build_query(option) 132 | { 133 | draftKey: option[:draftKey], 134 | limit: option[:limit], 135 | offset: option[:offset], 136 | orders: option[:orders] ? option[:orders].join(',') : nil, 137 | q: option[:q], 138 | fields: option[:fields] ? option[:fields].join(',') : nil, 139 | filters: option[:filters], 140 | depth: option[:depth], 141 | ids: option[:ids] ? option[:ids].join(',') : nil 142 | }.select { |_key, value| value } 143 | end 144 | # rubocop:enable Style/MethodLength 145 | 146 | def put(endpoint, content, option = {}) 147 | body = content.reject { |key, _value| key == :id } 148 | send_http_request('PUT', endpoint, content[:id], option, body) 149 | end 150 | 151 | def post(endpoint, content, option = {}) 152 | send_http_request('POST', endpoint, nil, option, content) 153 | end 154 | end 155 | 156 | # APIError 157 | class APIError < StandardError 158 | attr_accessor :status_code, :body 159 | 160 | def initialize(status_code:, body:) 161 | @status_code = status_code 162 | @body = parse_body(body) 163 | 164 | message = @body['message'] || 'Unknown error occured.' 165 | super(message) 166 | end 167 | 168 | def inspect 169 | "#<#{self.class.name} @status_code=#{status_code}, @body=#{body.inspect} @message=#{message.inspect}>" 170 | end 171 | 172 | private 173 | 174 | def parse_body(body) 175 | JSON.parse(body) 176 | rescue JSON::ParserError 177 | {} 178 | end 179 | end 180 | end 181 | -------------------------------------------------------------------------------- /lib/microcms/version.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module MicroCMS 4 | VERSION = '1.2.0' 5 | end 6 | -------------------------------------------------------------------------------- /microcms.gemspec: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require_relative 'lib/microcms/version' 4 | 5 | Gem::Specification.new do |spec| 6 | spec.name = 'microcms-ruby-sdk' 7 | spec.version = MicroCMS::VERSION 8 | spec.authors = ['microCMS'] 9 | 10 | spec.summary = 'microCMS Ruby SDK' 11 | spec.description = 'microCMS Ruby SDK' 12 | spec.homepage = 'https://github.com/microcmsio/microcms-ruby-sdk' 13 | spec.required_ruby_version = Gem::Requirement.new('>= 2.6.0') 14 | 15 | spec.metadata['homepage_uri'] = spec.homepage 16 | spec.metadata['source_code_uri'] = spec.homepage 17 | spec.metadata['changelog_uri'] = spec.homepage 18 | 19 | spec.metadata['rubygems_mfa_required'] = 'true' 20 | 21 | # Specify which files should be added to the gem when it is released. 22 | # The `git ls-files -z` loads the files in the RubyGem that have been added into git. 23 | spec.files = Dir.chdir(File.expand_path(__dir__)) do 24 | `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } 25 | end 26 | spec.bindir = 'exe' 27 | spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } 28 | spec.require_paths = ['lib'] 29 | end 30 | -------------------------------------------------------------------------------- /spec/microcms_spec.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require 'microcms' 4 | 5 | RSpec::Matchers.define :request do |method, path, headers, body| 6 | match do |actual| 7 | hash = { 8 | method: [method, actual.method], 9 | path: [path, actual.path], 10 | headers: [headers, headers.to_h { |k, _v| [k, actual[k]] }], 11 | body: [body, actual.body] 12 | } 13 | hash.all? { |_k, v| v[0] == v[1] } 14 | end 15 | end 16 | 17 | describe MicroCMS do 18 | let(:client) { MicroCMS::Client.new('service-domain', 'api-key') } 19 | 20 | let(:content) do 21 | { 22 | id: 'foo', 23 | text: 'Hello, microCMS!', 24 | createdAt: '2021-10-28T07:51:30.668Z', 25 | updatedAt: '2021-10-28T08:06:05.385Z', 26 | publishedAt: '2021-10-28T07:51:30.668Z', 27 | revisedAt: '2021-10-28T08:06:05.385Z' 28 | } 29 | end 30 | 31 | let(:content_list) do 32 | { 33 | contents: [content], 34 | totalCount: 1, 35 | limit: 10, 36 | offset: 0 37 | } 38 | end 39 | 40 | let(:expected_req_method) { 'GET' } 41 | 42 | let(:expected_req_path) { '/api/v1/endpoint' } 43 | 44 | let(:expected_req_headers) { { 'x-microcms-api-key' => 'api-key' } } 45 | 46 | let(:expected_req_body) { nil } 47 | 48 | let(:req_matcher) { request(expected_req_method, expected_req_path, expected_req_headers, expected_req_body) } 49 | 50 | let(:mock_res_headers) { { 'Content-Type' => 'application/json' } } 51 | 52 | let(:mock_res_body) { JSON.dump(content_list) } 53 | 54 | let(:mock_response) do 55 | response = Net::HTTPSuccess.new(1.0, '200', 'OK') 56 | mock_res_headers.each { |k, v| response[k] = v } 57 | response 58 | end 59 | 60 | let(:mock_client_error_response) do 61 | instance_double(Net::HTTPClientError, code: 400, body: '{"message":"client error"}') 62 | end 63 | 64 | let(:mock_server_error_response) do 65 | instance_double(Net::HTTPClientError, code: 500, body: '{"message":"server error"}') 66 | end 67 | 68 | context 'When send GET request without content id' do 69 | it 'should return contents' do 70 | expect_any_instance_of(Net::HTTP).to receive(:request).with(req_matcher) { mock_response } 71 | expect(mock_response).to receive(:body) { mock_res_body } 72 | 73 | res = client.list('endpoint') 74 | 75 | expect(res.contents).to eq [OpenStruct.new(content)] 76 | end 77 | end 78 | 79 | context 'When send GET request with content id' do 80 | let(:expected_req_path) { '/api/v1/endpoint/foo' } 81 | 82 | let(:mock_res_body) { JSON.dump(content) } 83 | 84 | it 'should return content' do 85 | expect_any_instance_of(Net::HTTP).to receive(:request).with(req_matcher) { mock_response } 86 | expect(mock_response).to receive(:body) { mock_res_body } 87 | 88 | res = client.get('endpoint', 'foo') 89 | 90 | expect(res).to eq OpenStruct.new(content) 91 | end 92 | end 93 | 94 | context 'When send POST request' do 95 | let(:expected_req_method) { 'POST' } 96 | let(:expected_req_body) { JSON.dump({ text: 'Hello, new content!' }) } 97 | 98 | let(:mock_res_body) { JSON.dump(content) } 99 | let(:mock_res_body) { '{"id": "bar"}' } 100 | 101 | it 'should return id' do 102 | expect_any_instance_of(Net::HTTP).to receive(:request).with(req_matcher) { mock_response } 103 | expect(mock_response).to receive(:body) { mock_res_body } 104 | 105 | res = client.create('endpoint', { text: 'Hello, new content!' }) 106 | 107 | expect(res).to eq OpenStruct.new({ id: 'bar' }) 108 | end 109 | end 110 | 111 | context 'When send PUT request' do 112 | let(:expected_req_method) { 'PUT' } 113 | let(:expected_req_path) { '/api/v1/endpoint/bar' } 114 | let(:expected_req_body) { JSON.dump({ text: 'Hello, new content!' }) } 115 | 116 | let(:mock_res_body) { JSON.dump(content) } 117 | let(:mock_res_body) { '{"id": "bar"}' } 118 | 119 | it 'should return id' do 120 | expect_any_instance_of(Net::HTTP).to receive(:request).with(req_matcher) { mock_response } 121 | expect(mock_response).to receive(:body) { mock_res_body } 122 | 123 | res = client.create('endpoint', { id: 'bar', text: 'Hello, new content!' }) 124 | 125 | expect(res).to eq OpenStruct.new({ id: 'bar' }) 126 | end 127 | end 128 | 129 | context 'When send POST request with draft status' do 130 | let(:expected_req_method) { 'POST' } 131 | let(:expected_req_path) { '/api/v1/endpoint?status=draft' } 132 | let(:expected_req_body) { JSON.dump({ text: 'Hello, new content!' }) } 133 | 134 | let(:mock_res_body) { JSON.dump(content) } 135 | let(:mock_res_body) { '{"id": "bar"}' } 136 | 137 | it 'should return id' do 138 | expect_any_instance_of(Net::HTTP).to receive(:request).with(req_matcher) { mock_response } 139 | expect(mock_response).to receive(:body) { mock_res_body } 140 | 141 | res = client.create('endpoint', { text: 'Hello, new content!' }, { status: 'draft' }) 142 | 143 | expect(res).to eq OpenStruct.new({ id: 'bar' }) 144 | end 145 | end 146 | 147 | context 'When send PATCH request' do 148 | let(:expected_req_method) { 'PATCH' } 149 | let(:expected_req_path) { '/api/v1/endpoint/bar' } 150 | let(:expected_req_body) { JSON.dump({ text: 'Hello, new content!' }) } 151 | 152 | let(:mock_res_body) { JSON.dump(content) } 153 | let(:mock_res_body) { '{"id": "bar"}' } 154 | 155 | it 'should return id' do 156 | expect_any_instance_of(Net::HTTP).to receive(:request).with(req_matcher) { mock_response } 157 | expect(mock_response).to receive(:body) { mock_res_body } 158 | 159 | res = client.update('endpoint', { id: 'bar', text: 'Hello, new content!' }) 160 | 161 | expect(res).to eq OpenStruct.new({ id: 'bar' }) 162 | end 163 | end 164 | 165 | context 'When send PATCH request' do 166 | let(:expected_req_method) { 'DELETE' } 167 | let(:expected_req_path) { '/api/v1/endpoint/bar' } 168 | 169 | let(:mock_res_body) { nil } 170 | let(:mock_res_headers) { { 'Content-Type': 'text/plain' } } 171 | 172 | it 'should return id' do 173 | expect_any_instance_of(Net::HTTP).to receive(:request).with(req_matcher) { mock_response } 174 | 175 | client.delete('endpoint', 'bar') 176 | end 177 | end 178 | 179 | context 'When api returns a client error' do 180 | it 'raises MicroCMS::APIError' do 181 | expect_any_instance_of(Net::HTTP).to receive(:request).and_return(mock_client_error_response) 182 | expect { client.create('endpoint', { id: 'bar', baz: 'quux' }) }.to( 183 | raise_error(an_instance_of(::MicroCMS::APIError) 184 | .and(have_attributes({ 185 | status_code: 400, 186 | message: 'client error', 187 | body: { 'message' => 'client error' } 188 | }))) 189 | ) 190 | end 191 | end 192 | 193 | context 'When api returns a server error' do 194 | it 'raises MicroCMS::APIError' do 195 | expect_any_instance_of(Net::HTTP).to receive(:request).and_return(mock_server_error_response) 196 | 197 | expect { client.create('endpoint', { id: 'bar', baz: 'quux' }) }.to( 198 | raise_error(an_instance_of(::MicroCMS::APIError) 199 | .and(have_attributes({ 200 | status_code: 500, 201 | message: 'server error', 202 | body: { 'message' => 'server error' } 203 | }))) 204 | ) 205 | end 206 | end 207 | end 208 | -------------------------------------------------------------------------------- /spec/spec_helper.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # This file was generated by the `rspec --init` command. Conventionally, all 4 | # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. 5 | # The generated `.rspec` file contains `--require spec_helper` which will cause 6 | # this file to always be loaded, without a need to explicitly require it in any 7 | # files. 8 | # 9 | # Given that it is always loaded, you are encouraged to keep this file as 10 | # light-weight as possible. Requiring heavyweight dependencies from this file 11 | # will add to the boot time of your test suite on EVERY test run, even for an 12 | # individual file that may not need all of that loaded. Instead, consider making 13 | # a separate helper file that requires the additional dependencies and performs 14 | # the additional setup, and require it from the spec files that actually need 15 | # it. 16 | # 17 | # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration 18 | RSpec.configure do |config| 19 | # rspec-expectations config goes here. You can use an alternate 20 | # assertion/expectation library such as wrong or the stdlib/minitest 21 | # assertions if you prefer. 22 | config.expect_with :rspec do |expectations| 23 | # This option will default to `true` in RSpec 4. It makes the `description` 24 | # and `failure_message` of custom matchers include text for helper methods 25 | # defined using `chain`, e.g.: 26 | # be_bigger_than(2).and_smaller_than(4).description 27 | # # => "be bigger than 2 and smaller than 4" 28 | # ...rather than: 29 | # # => "be bigger than 2" 30 | expectations.include_chain_clauses_in_custom_matcher_descriptions = true 31 | end 32 | 33 | # rspec-mocks config goes here. You can use an alternate test double 34 | # library (such as bogus or mocha) by changing the `mock_with` option here. 35 | config.mock_with :rspec do |mocks| 36 | # Prevents you from mocking or stubbing a method that does not exist on 37 | # a real object. This is generally recommended, and will default to 38 | # `true` in RSpec 4. 39 | mocks.verify_partial_doubles = true 40 | end 41 | 42 | # This option will default to `:apply_to_host_groups` in RSpec 4 (and will 43 | # have no way to turn it off -- the option exists only for backwards 44 | # compatibility in RSpec 3). It causes shared context metadata to be 45 | # inherited by the metadata hash of host groups and examples, rather than 46 | # triggering implicit auto-inclusion in groups with matching metadata. 47 | config.shared_context_metadata_behavior = :apply_to_host_groups 48 | 49 | # The settings below are suggested to provide a good initial experience 50 | # with RSpec, but feel free to customize to your heart's content. 51 | # # This allows you to limit a spec run to individual examples or groups 52 | # # you care about by tagging them with `:focus` metadata. When nothing 53 | # # is tagged with `:focus`, all examples get run. RSpec also provides 54 | # # aliases for `it`, `describe`, and `context` that include `:focus` 55 | # # metadata: `fit`, `fdescribe` and `fcontext`, respectively. 56 | # config.filter_run_when_matching :focus 57 | # 58 | # # Allows RSpec to persist some state between runs in order to support 59 | # # the `--only-failures` and `--next-failure` CLI options. We recommend 60 | # # you configure your source control system to ignore this file. 61 | # config.example_status_persistence_file_path = "spec/examples.txt" 62 | # 63 | # # Limits the available syntax to the non-monkey patched syntax that is 64 | # # recommended. For more details, see: 65 | # # - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/ 66 | # # - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/ 67 | # # - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode 68 | # config.disable_monkey_patching! 69 | # 70 | # # This setting enables warnings. It's recommended, but in some cases may 71 | # # be too noisy due to issues in dependencies. 72 | # config.warnings = true 73 | # 74 | # # Many RSpec users commonly either run the entire suite or an individual 75 | # # file, and it's useful to allow more verbose output when running an 76 | # # individual spec file. 77 | # if config.files_to_run.one? 78 | # # Use the documentation formatter for detailed output, 79 | # # unless a formatter has already been configured 80 | # # (e.g. via a command-line flag). 81 | # config.default_formatter = "doc" 82 | # end 83 | # 84 | # # Print the 10 slowest examples and example groups at the 85 | # # end of the spec run, to help surface which specs are running 86 | # # particularly slow. 87 | # config.profile_examples = 10 88 | # 89 | # # Run specs in random order to surface order dependencies. If you find an 90 | # # order dependency and want to debug it, you can fix the order by providing 91 | # # the seed, which is printed after each run. 92 | # # --seed 1234 93 | # config.order = :random 94 | # 95 | # # Seed global randomization in this process using the `--seed` CLI option. 96 | # # Setting this allows you to use `--seed` to deterministically reproduce 97 | # # test failures related to randomization by passing the same `--seed` value 98 | # # as the one that triggered the failure. 99 | # Kernel.srand config.seed 100 | end 101 | --------------------------------------------------------------------------------