From d4206370675dcc7f131b6162d59ef2af2341b248 Mon Sep 17 00:00:00 2001 From: Patrick Edelman Date: Mon, 16 Mar 2015 17:24:11 -0700 Subject: [PATCH] Complete rewrite of Bigcommerce API Client. - Bump major version to 1.0.0 - Introduces a new configuration syntax - Support for domain objects - Support for both legacy and oauth authentication - Add comprehensive examples - Add complete testing coverage - Add complete resource coverage from developer documentation - Add support for parsing server errors - And much more! --- .autotest | 2 - .gitignore | 34 +- .rspec | 3 +- .rubocop.yml | 620 ++++++++++++++++++ .travis.yml | 13 +- CHANGELOG.md | 11 + CONTRIBUTING.md | 119 ++++ DEPENDENCIES.md | 7 + Gemfile | 19 +- Guardfile | 22 + LICENSE | 30 +- README.md | 131 ++-- RELEASING.md | 64 ++ Rakefile | 14 +- bigcommerce.gemspec | 75 +-- examples/README.md | 148 +++++ examples/configuration/legacy_auth.rb | 12 + examples/configuration/oauth.rb | 9 + examples/content/blog_post.rb | 39 ++ examples/content/blog_tag.rb | 10 + examples/content/redirect.rb | 43 ++ examples/customers/customer.rb | 36 + examples/customers/customer_address.rb | 50 ++ examples/customers/customer_group.rb | 35 + examples/exception_handling.rb | 50 ++ examples/geography/country.rb | 16 + examples/geography/state.rb | 19 + examples/marketing/coupon.rb | 44 ++ examples/orders/order.rb | 53 ++ examples/orders/order_coupon.rb | 17 + examples/orders/order_message.rb | 17 + examples/orders/order_product.rb | 23 + examples/orders/order_shipping_address.rb | 23 + examples/orders/order_status.rb | 15 + examples/orders/order_tax.rb | 17 + examples/orders/shipment.rb | 57 ++ examples/payments/payment_method.rb | 10 + examples/products/brand.rb | 36 + examples/products/bulk_pricing_rule.rb | 47 ++ examples/products/category.rb | 37 ++ examples/products/configurable_field.rb | 29 + examples/products/custom_field.rb | 44 ++ .../products/google_product_search_mapping.rb | 12 + examples/products/option.rb | 37 ++ examples/products/option_set.rb | 35 + examples/products/option_set_option.rb | 50 ++ examples/products/option_value.rb | 43 ++ examples/products/product.rb | 44 ++ examples/products/product_image.rb | 42 ++ examples/products/product_option.rb | 17 + examples/products/product_review.rb | 12 + examples/products/product_rule.rb | 54 ++ examples/products/product_video.rb | 45 ++ examples/products/sku.rb | 48 ++ examples/shipping/shipping_method.rb | 13 + examples/store/store_info.rb | 10 + examples/system/time.rb | 10 + examples/tax/tax_class.rb | 13 + examples/webhooks/webhook.rb | 29 + lib/big_commerce.rb | 1 - lib/bigcommerce.rb | 58 +- lib/bigcommerce/api.rb | 477 -------------- lib/bigcommerce/connection.rb | 171 ----- lib/bigcommerce/exception.rb | 51 ++ lib/bigcommerce/middleware/auth.rb | 16 + lib/bigcommerce/middleware/http_exception.rb | 14 + lib/bigcommerce/product.rb | 13 - lib/bigcommerce/request.rb | 89 +++ lib/bigcommerce/resource.rb | 50 -- lib/bigcommerce/resource_actions.rb | 51 ++ .../resources/content/blog_post.rb | 31 + lib/bigcommerce/resources/content/blog_tag.rb | 17 + lib/bigcommerce/resources/content/redirect.rb | 21 + .../resources/customers/customer.rb | 30 + .../resources/customers/customer_address.rb | 34 + .../resources/customers/customer_group.rb | 21 + .../resources/geography/country.rb | 22 + lib/bigcommerce/resources/geography/state.rb | 25 + lib/bigcommerce/resources/marketing/coupon.rb | 30 + lib/bigcommerce/resources/orders/order.rb | 73 +++ .../resources/orders/order_coupon.rb | 20 + .../resources/orders/order_message.rb | 23 + .../resources/orders/order_product.rb | 64 ++ .../orders/order_shipping_address.rb | 50 ++ .../resources/orders/order_status.rb | 16 + lib/bigcommerce/resources/orders/order_tax.rb | 23 + lib/bigcommerce/resources/orders/shipment.rb | 30 + .../resources/payments/payment_method.rb | 17 + lib/bigcommerce/resources/products/brand.rb | 23 + .../resources/products/bulk_pricing_rule.rb | 26 + .../resources/products/category.rb | 29 + .../resources/products/configurable_field.rb | 30 + .../resources/products/custom_field.rb | 24 + .../products/google_product_search_mapping.rb | 26 + lib/bigcommerce/resources/products/option.rb | 20 + .../resources/products/option_set.rb | 18 + .../resources/products/option_set_option.rb | 19 + .../resources/products/option_value.rb | 15 + lib/bigcommerce/resources/products/product.rb | 97 +++ .../resources/products/product_image.rb | 31 + .../resources/products/product_option.rb | 17 + .../resources/products/product_review.rb | 22 + .../resources/products/product_rule.rb | 31 + .../resources/products/product_video.rb | 24 + lib/bigcommerce/resources/products/sku.rb | 29 + lib/bigcommerce/resources/resource.rb | 10 + .../resources/shipping/shipping_method.rb | 15 + .../resources/store/store_information.rb | 37 ++ lib/bigcommerce/resources/system/time.rb | 15 + lib/bigcommerce/resources/tax/tax_class.rb | 15 + lib/bigcommerce/resources/webhooks/webhook.rb | 22 + lib/bigcommerce/subresource_actions.rb | 43 ++ lib/bigcommerce/version.rb | 5 +- spec/big_commerce_spec.rb | 9 - spec/bigcommerce/bigcommerce_spec.rb | 76 +++ spec/bigcommerce/unit/actions_spec.rb | 151 +++++ spec/bigcommerce/unit/exception_spec.rb | 53 ++ spec/bigcommerce/unit/middleware/auth_spec.rb | 18 + .../unit/middleware/http_exception_spec.rb | 40 ++ spec/bigcommerce/unit/request_spec.rb | 180 +++++ .../unit/resources/content/blog_post_spec.rb | 12 + .../unit/resources/content/blog_tag_spec.rb | 12 + .../unit/resources/content/redirect_spec.rb | 12 + .../customers/customer_address_spec.rb | 21 + .../customers/customer_group_spec.rb | 12 + .../unit/resources/customers/customer_spec.rb | 12 + .../unit/resources/geography/country_spec.rb | 12 + .../unit/resources/geography/state_spec.rb | 21 + .../unit/resources/marketing/coupon_spec.rb | 12 + .../resources/orders/order_product_spec.rb | 21 + .../orders/order_shipping_address_spec.rb | 21 + .../unit/resources/orders/order_spec.rb | 13 + .../unit/resources/orders/shipment_spec.rb | 21 + .../resources/payments/payment_method_spec.rb | 23 + .../unit/resources/products/brand_spec.rb | 12 + .../products/bulk_pricing_rule_spec.rb | 21 + .../unit/resources/products/category_spec.rb | 12 + .../products/configurable_field_spec.rb | 21 + .../resources/products/custom_field_spec.rb | 21 + .../google_product_search_mapping_spec.rb | 14 + .../resources/products/option_set_spec.rb | 12 + .../unit/resources/products/option_spec.rb | 12 + .../resources/products/product_image_spec.rb | 21 + .../resources/products/product_review_spec.rb | 14 + .../resources/products/product_rule_spec.rb | 21 + .../unit/resources/products/product_spec.rb | 13 + .../resources/products/product_video_spec.rb | 21 + .../unit/resources/products/sku_spec.rb | 21 + .../unit/resources/resource_spec.rb | 4 + .../store_info/store_information_spec.rb | 12 + .../unit/resources/system/time_spec.rb | 12 + spec/bigcommerce/unit/version_spec.rb | 7 + .../api/v2/orders/filters_orders_by_date.yml | 47 -- .../v2/orders/gets_the_orders_collection.yml | 47 -- spec/fixtures/brands.json | 9 - spec/fixtures/categories.json | 20 - spec/fixtures/countries.json | 10 - spec/fixtures/order.json | 1 - spec/fixtures/time.json | 1 - spec/integration/orders_spec.rb | 18 - spec/spec_helper.rb | 34 +- spec/support/integration_context.rb | 13 - spec/support/mock_api_context.rb | 10 - spec/unit/api_request_spec.rb | 34 - spec/unit/api_spec.rb | 49 -- spec/unit/connection_spec.rb | 23 - spec/unit/date_time_spec.rb | 31 - spec/unit/version_spec.rb | 13 - 168 files changed, 4918 insertions(+), 1260 deletions(-) delete mode 100644 .autotest create mode 100644 .rubocop.yml create mode 100644 CHANGELOG.md create mode 100644 CONTRIBUTING.md create mode 100644 DEPENDENCIES.md create mode 100644 Guardfile create mode 100644 RELEASING.md create mode 100644 examples/README.md create mode 100644 examples/configuration/legacy_auth.rb create mode 100644 examples/configuration/oauth.rb create mode 100644 examples/content/blog_post.rb create mode 100644 examples/content/blog_tag.rb create mode 100644 examples/content/redirect.rb create mode 100644 examples/customers/customer.rb create mode 100644 examples/customers/customer_address.rb create mode 100644 examples/customers/customer_group.rb create mode 100644 examples/exception_handling.rb create mode 100644 examples/geography/country.rb create mode 100644 examples/geography/state.rb create mode 100644 examples/marketing/coupon.rb create mode 100644 examples/orders/order.rb create mode 100644 examples/orders/order_coupon.rb create mode 100644 examples/orders/order_message.rb create mode 100644 examples/orders/order_product.rb create mode 100644 examples/orders/order_shipping_address.rb create mode 100644 examples/orders/order_status.rb create mode 100644 examples/orders/order_tax.rb create mode 100644 examples/orders/shipment.rb create mode 100644 examples/payments/payment_method.rb create mode 100644 examples/products/brand.rb create mode 100644 examples/products/bulk_pricing_rule.rb create mode 100644 examples/products/category.rb create mode 100644 examples/products/configurable_field.rb create mode 100644 examples/products/custom_field.rb create mode 100644 examples/products/google_product_search_mapping.rb create mode 100644 examples/products/option.rb create mode 100644 examples/products/option_set.rb create mode 100644 examples/products/option_set_option.rb create mode 100644 examples/products/option_value.rb create mode 100644 examples/products/product.rb create mode 100644 examples/products/product_image.rb create mode 100644 examples/products/product_option.rb create mode 100644 examples/products/product_review.rb create mode 100644 examples/products/product_rule.rb create mode 100644 examples/products/product_video.rb create mode 100644 examples/products/sku.rb create mode 100644 examples/shipping/shipping_method.rb create mode 100644 examples/store/store_info.rb create mode 100644 examples/system/time.rb create mode 100644 examples/tax/tax_class.rb create mode 100644 examples/webhooks/webhook.rb delete mode 100644 lib/big_commerce.rb delete mode 100644 lib/bigcommerce/api.rb delete mode 100644 lib/bigcommerce/connection.rb create mode 100644 lib/bigcommerce/exception.rb create mode 100644 lib/bigcommerce/middleware/auth.rb create mode 100644 lib/bigcommerce/middleware/http_exception.rb delete mode 100644 lib/bigcommerce/product.rb create mode 100644 lib/bigcommerce/request.rb delete mode 100644 lib/bigcommerce/resource.rb create mode 100644 lib/bigcommerce/resource_actions.rb create mode 100644 lib/bigcommerce/resources/content/blog_post.rb create mode 100644 lib/bigcommerce/resources/content/blog_tag.rb create mode 100644 lib/bigcommerce/resources/content/redirect.rb create mode 100644 lib/bigcommerce/resources/customers/customer.rb create mode 100644 lib/bigcommerce/resources/customers/customer_address.rb create mode 100644 lib/bigcommerce/resources/customers/customer_group.rb create mode 100644 lib/bigcommerce/resources/geography/country.rb create mode 100644 lib/bigcommerce/resources/geography/state.rb create mode 100644 lib/bigcommerce/resources/marketing/coupon.rb create mode 100644 lib/bigcommerce/resources/orders/order.rb create mode 100644 lib/bigcommerce/resources/orders/order_coupon.rb create mode 100644 lib/bigcommerce/resources/orders/order_message.rb create mode 100644 lib/bigcommerce/resources/orders/order_product.rb create mode 100644 lib/bigcommerce/resources/orders/order_shipping_address.rb create mode 100644 lib/bigcommerce/resources/orders/order_status.rb create mode 100644 lib/bigcommerce/resources/orders/order_tax.rb create mode 100644 lib/bigcommerce/resources/orders/shipment.rb create mode 100644 lib/bigcommerce/resources/payments/payment_method.rb create mode 100644 lib/bigcommerce/resources/products/brand.rb create mode 100644 lib/bigcommerce/resources/products/bulk_pricing_rule.rb create mode 100644 lib/bigcommerce/resources/products/category.rb create mode 100644 lib/bigcommerce/resources/products/configurable_field.rb create mode 100644 lib/bigcommerce/resources/products/custom_field.rb create mode 100644 lib/bigcommerce/resources/products/google_product_search_mapping.rb create mode 100644 lib/bigcommerce/resources/products/option.rb create mode 100644 lib/bigcommerce/resources/products/option_set.rb create mode 100644 lib/bigcommerce/resources/products/option_set_option.rb create mode 100644 lib/bigcommerce/resources/products/option_value.rb create mode 100644 lib/bigcommerce/resources/products/product.rb create mode 100644 lib/bigcommerce/resources/products/product_image.rb create mode 100644 lib/bigcommerce/resources/products/product_option.rb create mode 100644 lib/bigcommerce/resources/products/product_review.rb create mode 100644 lib/bigcommerce/resources/products/product_rule.rb create mode 100644 lib/bigcommerce/resources/products/product_video.rb create mode 100644 lib/bigcommerce/resources/products/sku.rb create mode 100644 lib/bigcommerce/resources/resource.rb create mode 100644 lib/bigcommerce/resources/shipping/shipping_method.rb create mode 100644 lib/bigcommerce/resources/store/store_information.rb create mode 100644 lib/bigcommerce/resources/system/time.rb create mode 100644 lib/bigcommerce/resources/tax/tax_class.rb create mode 100644 lib/bigcommerce/resources/webhooks/webhook.rb create mode 100644 lib/bigcommerce/subresource_actions.rb delete mode 100644 spec/big_commerce_spec.rb create mode 100644 spec/bigcommerce/bigcommerce_spec.rb create mode 100644 spec/bigcommerce/unit/actions_spec.rb create mode 100644 spec/bigcommerce/unit/exception_spec.rb create mode 100644 spec/bigcommerce/unit/middleware/auth_spec.rb create mode 100644 spec/bigcommerce/unit/middleware/http_exception_spec.rb create mode 100644 spec/bigcommerce/unit/request_spec.rb create mode 100644 spec/bigcommerce/unit/resources/content/blog_post_spec.rb create mode 100644 spec/bigcommerce/unit/resources/content/blog_tag_spec.rb create mode 100644 spec/bigcommerce/unit/resources/content/redirect_spec.rb create mode 100644 spec/bigcommerce/unit/resources/customers/customer_address_spec.rb create mode 100644 spec/bigcommerce/unit/resources/customers/customer_group_spec.rb create mode 100644 spec/bigcommerce/unit/resources/customers/customer_spec.rb create mode 100644 spec/bigcommerce/unit/resources/geography/country_spec.rb create mode 100644 spec/bigcommerce/unit/resources/geography/state_spec.rb create mode 100644 spec/bigcommerce/unit/resources/marketing/coupon_spec.rb create mode 100644 spec/bigcommerce/unit/resources/orders/order_product_spec.rb create mode 100644 spec/bigcommerce/unit/resources/orders/order_shipping_address_spec.rb create mode 100644 spec/bigcommerce/unit/resources/orders/order_spec.rb create mode 100644 spec/bigcommerce/unit/resources/orders/shipment_spec.rb create mode 100644 spec/bigcommerce/unit/resources/payments/payment_method_spec.rb create mode 100644 spec/bigcommerce/unit/resources/products/brand_spec.rb create mode 100644 spec/bigcommerce/unit/resources/products/bulk_pricing_rule_spec.rb create mode 100644 spec/bigcommerce/unit/resources/products/category_spec.rb create mode 100644 spec/bigcommerce/unit/resources/products/configurable_field_spec.rb create mode 100644 spec/bigcommerce/unit/resources/products/custom_field_spec.rb create mode 100644 spec/bigcommerce/unit/resources/products/google_product_search_mapping_spec.rb create mode 100644 spec/bigcommerce/unit/resources/products/option_set_spec.rb create mode 100644 spec/bigcommerce/unit/resources/products/option_spec.rb create mode 100644 spec/bigcommerce/unit/resources/products/product_image_spec.rb create mode 100644 spec/bigcommerce/unit/resources/products/product_review_spec.rb create mode 100644 spec/bigcommerce/unit/resources/products/product_rule_spec.rb create mode 100644 spec/bigcommerce/unit/resources/products/product_spec.rb create mode 100644 spec/bigcommerce/unit/resources/products/product_video_spec.rb create mode 100644 spec/bigcommerce/unit/resources/products/sku_spec.rb create mode 100644 spec/bigcommerce/unit/resources/resource_spec.rb create mode 100644 spec/bigcommerce/unit/resources/store_info/store_information_spec.rb create mode 100644 spec/bigcommerce/unit/resources/system/time_spec.rb create mode 100644 spec/bigcommerce/unit/version_spec.rb delete mode 100644 spec/fixtures/api/v2/orders/filters_orders_by_date.yml delete mode 100644 spec/fixtures/api/v2/orders/gets_the_orders_collection.yml delete mode 100644 spec/fixtures/brands.json delete mode 100644 spec/fixtures/categories.json delete mode 100644 spec/fixtures/countries.json delete mode 100644 spec/fixtures/order.json delete mode 100644 spec/fixtures/time.json delete mode 100644 spec/integration/orders_spec.rb delete mode 100644 spec/support/integration_context.rb delete mode 100644 spec/support/mock_api_context.rb delete mode 100644 spec/unit/api_request_spec.rb delete mode 100644 spec/unit/api_spec.rb delete mode 100644 spec/unit/connection_spec.rb delete mode 100644 spec/unit/date_time_spec.rb delete mode 100644 spec/unit/version_spec.rb diff --git a/.autotest b/.autotest deleted file mode 100644 index 575af35..0000000 --- a/.autotest +++ /dev/null @@ -1,2 +0,0 @@ -require 'autotest/bundler' -require 'autotest/restart' diff --git a/.gitignore b/.gitignore index 9c8c640..c3301b3 100644 --- a/.gitignore +++ b/.gitignore @@ -1,19 +1,17 @@ -# Bundler -/.bundle -/Gemfile.lock -/pkg -/vendor/bundle - -# CI Reporter -/spec/reports - -# Code coverage -/coverage - -# Ignore compiled gems -/*.gem - -# Rspec -/tmp - +*.gem +*.rbc .DS_Store +.bundle +.rvmrc +.ruby-version +.yardoc +.rake_tasks~ +Gemfile.lock +coverage/* +doc/* +log/* +pkg/* +.idea/* +tmp/* +.env +.env-* diff --git a/.rspec b/.rspec index ac8bc25..671a582 100644 --- a/.rspec +++ b/.rspec @@ -1 +1,2 @@ ---colour --format d +--colour +--format=documentation diff --git a/.rubocop.yml b/.rubocop.yml new file mode 100644 index 0000000..07e02fb --- /dev/null +++ b/.rubocop.yml @@ -0,0 +1,620 @@ +# This is the default configuration file. Enabling and disabling is configured +# in separate files. This file adds all other parameters apart from Enabled. + +# Common configuration. +AllCops: + # Include gemspec and Rakefile + Include: + - '**/*.gemspec' + - '**/*.podspec' + - '**/*.jbuilder' + - '**/*.rake' + - '**/*.opal' + - '**/Gemfile' + - '**/Rakefile' + - '**/Capfile' + - '**/Guardfile' + - '**/Podfile' + - '**/Thorfile' + - '**/Vagrantfile' + - '**/Berksfile' + - '**/Cheffile' + - '**/Vagabondfile' + Exclude: + - 'vendor/**/*' + - 'spec/**/*' + # By default, the rails cops are not run. Override in project or home + # directory .rubocop.yml files, or by giving the -R/--rails option. + RunRailsCops: false + # Cop names are not displayed in offense messages by default. Change behavior + # by overriding DisplayCopNames, or by giving the -D/--display-cop-names + # option. + DisplayCopNames: false + # Additional cops that do not reference a style guide rule may be enabled by + # default. Change behavior by overriding StyleGuideCopsOnly, or by giving + # the --only-guide-cops option. + StyleGuideCopsOnly: false + +# Indent private/protected/public as deep as method definitions +Style/Documentation: + Enabled: false + +Style/AccessModifierIndentation: + EnforcedStyle: indent + SupportedStyles: + - outdent + - indent + +# Align the elements of a hash literal if they span more than one line. +Style/AlignHash: + # Alignment of entries using hash rocket as separator. Valid values are: + # + # key - left alignment of keys + # 'a' => 2 + # 'bb' => 3 + # separator - alignment of hash rockets, keys are right aligned + # 'a' => 2 + # 'bb' => 3 + # table - left alignment of keys, hash rockets, and values + # 'a' => 2 + # 'bb' => 3 + EnforcedHashRocketStyle: key + # Alignment of entries using colon as separator. Valid values are: + # + # key - left alignment of keys + # a: 0 + # bb: 1 + # separator - alignment of colons, keys are right aligned + # a: 0 + # bb: 1 + # table - left alignment of keys and values + # a: 0 + # bb: 1 + EnforcedColonStyle: key + # Select whether hashes that are the last argument in a method call should be + # inspected? Valid values are: + # + # always_inspect - Inspect both implicit and explicit hashes. + # Registers an offense for: + # function(a: 1, + # b: 2) + # Registers an offense for: + # function({a: 1, + # b: 2}) + # always_ignore - Ignore both implicit and explicit hashes. + # Accepts: + # function(a: 1, + # b: 2) + # Accepts: + # function({a: 1, + # b: 2}) + # ignore_implicit - Ignore only implicit hashes. + # Accepts: + # function(a: 1, + # b: 2) + # Registers an offense for: + # function({a: 1, + # b: 2}) + # ignore_explicit - Ignore only explicit hashes. + # Accepts: + # function({a: 1, + # b: 2}) + # Registers an offense for: + # function(a: 1, + # b: 2) + EnforcedLastArgumentHashStyle: always_inspect + SupportedLastArgumentHashStyles: + - always_inspect + - always_ignore + - ignore_implicit + - ignore_explicit + +Style/AlignParameters: + # Alignment of parameters in multi-line method calls. + # + # The `with_first_parameter` style aligns the following lines along the same + # column as the first parameter. + # + # method_call(a, + # b) + # + # The `with_fixed_indentation` style aligns the following lines with one + # level of indentation relative to the start of the line with the method call. + # + # method_call(a, + # b) + EnforcedStyle: with_first_parameter + SupportedStyles: + - with_first_parameter + - with_fixed_indentation + +Style/AndOr: + # Whether `and` and `or` are banned only in conditionals (conditionals) + # or completely (always). + EnforcedStyle: always + SupportedStyles: + - always + - conditionals + + +# Checks if usage of %() or %Q() matches configuration. +Style/BarePercentLiterals: + EnforcedStyle: bare_percent + SupportedStyles: + - percent_q + - bare_percent + +Style/BracesAroundHashParameters: + EnforcedStyle: no_braces + SupportedStyles: + # The `braces` style enforces braces around all method parameters that are + # hashes. + - braces + # The `no_braces` style checks that the last parameter doesn't have braces + # around it. + - no_braces + # The `context_dependent` style checks that the last parameter doesn't have + # braces around it, but requires braces if the second to last parameter is + # also a hash literal. + - context_dependent + +# Indentation of `when`. +Style/CaseIndentation: + IndentWhenRelativeTo: case + +Style/ClassAndModuleChildren: + # Checks the style of children definitions at classes and modules. + # + # Basically there are two different styles: + # + # `nested` - have each child on a separate line + # class Foo + # class Bar + # end + # end + # + # `compact` - combine definitions as much as possible + # class Foo::Bar + # end + # + # The compact style is only forced, for classes / modules with one child. + EnforcedStyle: nested + SupportedStyles: + - nested + - compact + +Style/ClassCheck: + EnforcedStyle: is_a? + SupportedStyles: + - is_a? + - kind_of? + +# Align with the style guide. +Style/CollectionMethods: + # Mapping from undesired method to desired_method + # e.g. to use `detect` over `find`: + # + # CollectionMethods: + # PreferredMethods: + # find: detect + PreferredMethods: + collect: 'map' + collect!: 'map!' + inject: 'reduce' + detect: 'find' + find_all: 'select' + +# Checks formatting of special comments +Style/CommentAnnotation: + Keywords: + - TODO + - FIXME + - OPTIMIZE + - HACK + - REVIEW + +# Multi-line method chaining should be done with leading dots. +Style/DotPosition: + EnforcedStyle: leading + SupportedStyles: + - leading + - trailing + +# Use empty lines between defs. +Style/EmptyLineBetweenDefs: + # If true, this parameter means that single line method definitions don't + # need an empty line between them. + AllowAdjacentOneLineDefs: false + +Style/EmptyLinesAroundBlockBody: + EnforcedStyle: no_empty_lines + SupportedStyles: + - empty_lines + - no_empty_lines + +Style/EmptyLinesAroundClassBody: + EnforcedStyle: no_empty_lines + SupportedStyles: + - empty_lines + - no_empty_lines + +Style/EmptyLinesAroundModuleBody: + EnforcedStyle: no_empty_lines + SupportedStyles: + - empty_lines + - no_empty_lines + +Style/FileName: + # File names listed in AllCops:Include are excluded by default. Add extra + # excludes here. + Exclude: [] + +Style/FirstParameterIndentation: + EnforcedStyle: special_for_inner_method_call_in_parentheses + SupportedStyles: + # The first parameter should always be indented one step more than the + # preceding line. + - consistent + # The first parameter should normally be indented one step more than the + # preceding line, but if it's a parameter for a method call that is itself + # a parameter in a method call, then the inner parameter should be indented + # relative to the inner method. + - special_for_inner_method_call + # Same as special_for_inner_method_call except that the special rule only + # applies if the outer method call encloses its arguments in parentheses. + - special_for_inner_method_call_in_parentheses + +# Checks use of for or each in multiline loops. +Style/For: + EnforcedStyle: each + SupportedStyles: + - for + - each + +# Enforce the method used for string formatting. +Style/FormatString: + EnforcedStyle: format + SupportedStyles: + - format + - sprintf + - percent + +# Built-in global variables are allowed by default. +Style/GlobalVars: + AllowedVariables: [] + +# `MinBodyLength` defines the number of lines of the a body of an if / unless +# needs to have to trigger this cop +Style/GuardClause: + MinBodyLength: 1 + +Style/HashSyntax: + EnforcedStyle: ruby19 + SupportedStyles: + - ruby19 + - ruby19_no_mixed_keys + - hash_rockets + +Style/IfUnlessModifier: + MaxLineLength: 90 + +Style/IndentationWidth: + # Number of spaces for each indentation level. + Width: 2 + +# Checks the indentation of the first key in a hash literal. +Style/IndentHash: + # The value `special_inside_parentheses` means that hash literals with braces + # that have their opening brace on the same line as a surrounding opening + # round parenthesis, shall have their first key indented relative to the + # first position inside the parenthesis. + # The value `consistent` means that the indentation of the first key shall + # always be relative to the first position of the line where the opening + # brace is. + EnforcedStyle: special_inside_parentheses + SupportedStyles: + - special_inside_parentheses + - consistent + +Style/LambdaCall: + EnforcedStyle: call + SupportedStyles: + - call + - braces + +Style/Next: + # With `always` all conditions at the end of an iteration needs to be + # replaced by next - with `skip_modifier_ifs` the modifier if like this one + # are ignored: [1, 2].each { |a| return 'yes' if a == 1 } + EnforcedStyle: skip_modifier_ifs + # `MinBodyLength` defines the number of lines of the a body of an if / unless + # needs to have to trigger this cop + MinBodyLength: 3 + SupportedStyles: + - skip_modifier_ifs + - always + +Style/NonNilCheck: + # With `IncludeSemanticChanges` set to `true`, this cop reports offenses for + # `!x.nil?` and autocorrects that and `x != nil` to solely `x`, which is + # **usually** OK, but might change behavior. + # + # With `IncludeSemanticChanges` set to `false`, this cop does not report + # offenses for `!x.nil?` and does no changes that might change behavior. + IncludeSemanticChanges: false + +Style/MethodDefParentheses: + EnforcedStyle: require_parentheses + SupportedStyles: + - require_parentheses + - require_no_parentheses + +Style/MethodName: + EnforcedStyle: snake_case + SupportedStyles: + - snake_case + - camelCase + +Style/MultilineOperationIndentation: + EnforcedStyle: aligned + SupportedStyles: + - aligned + - indented + +Style/NumericLiterals: + MinDigits: 5 + +# Allow safe assignment in conditions. +Style/ParenthesesAroundCondition: + AllowSafeAssignment: true + +Style/PercentLiteralDelimiters: + PreferredDelimiters: + '%': () + '%i': () + '%q': () + '%Q': () + '%r': '{}' + '%s': () + '%w': () + '%W': () + '%x': () + +Style/PercentQLiterals: + EnforcedStyle: lower_case_q + SupportedStyles: + - lower_case_q # Use %q when possible, %Q when necessary + - upper_case_q # Always use %Q + +Style/PredicateName: + # Predicate name prefices. + NamePrefix: + - is_ + - has_ + - have_ + # Predicate name prefices that should be removed. + NamePrefixBlacklist: + - is_ + - has_ + - have_ + +Style/RaiseArgs: + EnforcedStyle: exploded + SupportedStyles: + - compact # raise Exception.new(msg) + - exploded # raise Exception, msg + +Style/RedundantReturn: + # When true allows code like `return x, y`. + AllowMultipleReturnValues: false + +Style/RegexpLiteral: + # The maximum number of (escaped) slashes that a slash-delimited regexp is + # allowed to have. If there are more slashes, a %r regexp shall be used. + MaxSlashes: 1 + +Style/Semicolon: + # Allow ; to separate several expressions on the same line. + AllowAsExpressionSeparator: false + +Style/SignalException: + EnforcedStyle: semantic + SupportedStyles: + - only_raise + - only_fail + - semantic + +Style/SingleLineBlockParams: + Methods: + - reduce: + - a + - e + - inject: + - a + - e + +Style/SingleLineMethods: + AllowIfMethodIsEmpty: true + +Style/StringLiterals: + EnforcedStyle: single_quotes + SupportedStyles: + - single_quotes + - double_quotes + +Style/StringLiteralsInInterpolation: + EnforcedStyle: single_quotes + SupportedStyles: + - single_quotes + - double_quotes + +Style/SpaceAroundBlockParameters: + EnforcedStyleInsidePipes: no_space + SupportedStyles: + - space + - no_space + +Style/SpaceAroundEqualsInParameterDefault: + EnforcedStyle: space + SupportedStyles: + - space + - no_space + +Style/SpaceBeforeBlockBraces: + EnforcedStyle: space + SupportedStyles: + - space + - no_space + +Style/SpaceInsideBlockBraces: + EnforcedStyle: space + SupportedStyles: + - space + - no_space + # Valid values are: space, no_space + EnforcedStyleForEmptyBraces: no_space + # Space between { and |. Overrides EnforcedStyle if there is a conflict. + SpaceBeforeBlockParameters: true + +Style/SpaceInsideHashLiteralBraces: + EnforcedStyle: space + EnforcedStyleForEmptyBraces: no_space + SupportedStyles: + - space + - no_space + +Style/SymbolProc: + # A list of method names to be ignored by the check. + # The names should be fairly unique, otherwise you'll end up ignoring lots of code. + IgnoredMethods: + - respond_to + +Style/TrailingBlankLines: + EnforcedStyle: final_newline + SupportedStyles: + - final_newline + - final_blank_line + +Style/TrailingComma: + # If EnforcedStyleForMultiline is comma, the cop requires a comma after the + # last item of a list, but only for lists where each item is on its own line. + # If EnforcedStyleForMultiline is consistent_comma, the cop requires a comma + # after the last item of a list, for all lists. + EnforcedStyleForMultiline: no_comma + SupportedStyles: + - comma + - consistent_comma + - no_comma + +# TrivialAccessors doesn't require exact name matches and doesn't allow +# predicated methods by default. +Style/TrivialAccessors: + ExactNameMatch: false + AllowPredicates: false + # Allows trivial writers that don't end in an equal sign. e.g. + # + # def on_exception(action) + # @on_exception=action + # end + # on_exception :restart + # + # Commonly used in DSLs + AllowDSLWriters: false + Whitelist: + - to_ary + - to_a + - to_c + - to_enum + - to_h + - to_hash + - to_i + - to_int + - to_io + - to_open + - to_path + - to_proc + - to_r + - to_regexp + - to_str + - to_s + - to_sym + +Style/VariableName: + EnforcedStyle: snake_case + SupportedStyles: + - snake_case + - camelCase + +Style/WhileUntilModifier: + MaxLineLength: 90 + +Style/WordArray: + MinSize: 0 + # The regular expression WordRegex decides what is considered a word. + WordRegex: !ruby/regexp '/\A[\p{Word}]+\z/' + +##################### Metrics ################################## + +Metrics/AbcSize: + # The ABC size is a calculated magnitude, so this number can be a Fixnum or + # a Float. + Max: 20 + +Metrics/BlockNesting: + Max: 3 + +Metrics/ClassLength: + CountComments: false # count full line comments? + Max: 100 + +# Avoid complex methods. +Metrics/CyclomaticComplexity: + Max: 6 + +Metrics/LineLength: + Max: 90 + # To make it possible to copy or click on URIs in the code, we allow lines + # contaning a URI to be longer than Max. + AllowURI: true + URISchemes: + - http + - https + +Metrics/MethodLength: + CountComments: false # count full line comments? + Max: 15 + +Metrics/ParameterLists: + Max: 5 + CountKeywordArgs: true + +Metrics/PerceivedComplexity: + Max: 7 + +##################### Lint ################################## + +# Allow safe assignment in conditions. +Lint/AssignmentInCondition: + AllowSafeAssignment: true + +# Align ends correctly. +Lint/EndAlignment: + # The value `keyword` means that `end` should be aligned with the matching + # keyword (if, while, etc.). + # The value `variable` means that in assignments, `end` should be aligned + # with the start of the variable on the left hand side of `=`. In all other + # situations, `end` should still be aligned with the keyword. + AlignWith: keyword + SupportedStyles: + - keyword + - variable + +Lint/DefEndAlignment: + # The value `def` means that `end` should be aligned with the def keyword. + # The value `start_of_line` means that `end` should be aligned with method + # calls like `private`, `public`, etc, if present in front of the `def` + # keyword on the same line. + AlignWith: start_of_line + SupportedStyles: + - start_of_line + - def diff --git a/.travis.yml b/.travis.yml index 250160a..e91ee4a 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,10 +1,15 @@ language: ruby +cache: bundler + +# http://docs.travis-ci.com/user/workers/container-based-infrastructure/ +sudo: false + rvm: + - jruby-head + - ruby-head + - rbx-2.2.10 + - 2.2.1 - 2.1.5 - 2.0.0 - 1.9.3 - jruby-19mode -env: API_URL=https://store-vnh06c71.mybigcommerce.com API_USER=admin API_PASS=123456 - -matrix: - fast_finish: true diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..7b911f8 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,11 @@ +## Next Release + +* Your contribution here. + +## 1.0.0 +Please note that this is the start of a new major release which breaks all backward compatibility. + +* [#89](https://github.com/bigcommerce/bigcommerce-api-ruby/pull/89): Complete rewrite of Bigcommerce API Client. - [@pedelman](https://github.com/pedelman). + +## 0.x (Legacy) +For the old version of the API Client please view the [0.x branch](https://github.com/bigcommerce/bigcommerce-api-ruby/tree/0.x). diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..12a2d8e --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,119 @@ +# Contributing to Bigcommerce + + +We would love to see contributors! You're encouraged to submit [pull requests](https://github.com/bigcommerce/bigcommerce-api-ruby/pulls), [propose features, and discuss issues](https://github.com/bigcommerce/bigcommerce-api-ruby/issues). + +#### Fork the Project + +Fork the [project on Github](https://github.com/bigcommerce/bigcommerce-api-ruby) and check out your copy. + +``` +git clone your_forked_version_of_bigcommerce_api_ruby +cd bigcommerce-api-ruby +git remote add upstream https://github.com/bigcommerce/bigcommerce-api-ruby.git +``` + +#### Create a Feature Branch + +Make sure your fork is up-to-date and create a topic branch for your feature or bug fix. + +``` +git checkout master +git pull upstream master +git checkout -b my-feature-branch +``` + +#### Bundle Install and Test + +Ensure that you can build the project and run tests. + +``` +bundle install +bundle exec rake +``` + +#### Installing the gem locally (useful to run examples) + +This will build the gem locally into the pkg directory, you can then install it manually by targeting that directory specifically. + +``` +bundle exec rake build +gem install pkg/bigcommerce-1.x.x.gem +``` + +#### Write Tests + +Try to write a test that reproduces the problem you're trying to fix or describes a feature that you want to build. Add to [spec/bigcommerce](spec/bigcommerce). + +We definitely appreciate pull requests that highlight or reproduce a problem, even without a fix. + +#### Write Code + +Implement your feature or bug fix. + +Ruby style is enforced with [Rubocop](https://github.com/bbatsov/rubocop), run `bundle exec rubocop` and fix any style issues highlighted. + +Make sure that `bundle exec rake` completes without errors. + +#### Write Documentation + +Document any external behavior in the [README](README.md). + +#### Update Changelog + +Add a line to [CHANGELOG](CHANGELOG.md) under *Next Release*. Make it look like every other line, including your name and link to your Github account. + +#### Commit Changes + +Make sure git knows your name and email address: + +``` +git config --global user.name "Your Name" +git config --global user.email "contributor@example.com" +``` + +Writing good commit logs is important. A commit log should describe what changed and why. + +``` +git add ... +git commit +``` + +#### Push + +``` +git push origin my-feature-branch +``` + +#### Make a Pull Request + +Go to https://github.com/contributor/bigcommerce-api-ruby and select your feature branch. Click the 'Pull Request' button and fill out the form. Pull requests are usually reviewed within a few days. + +#### Rebase + +If you've been working on a change for a while, rebase with upstream/master. + +``` +git fetch upstream +git rebase upstream/master +git push origin my-feature-branch -f +``` + +#### Update CHANGELOG Again + +Update the [CHANGELOG](CHANGELOG.md) with the pull request number. A typical entry looks as follows. + +``` +* [#123](https://github.com/bigcommerce/bigcommerce-api-ruby/pull/123): Added products resource - [@contributor](https://github.com/contributor). +``` + +Amend your previous commit and force push the changes. + +``` +git commit --amend +git push origin my-feature-branch -f +``` + +#### Check on Your Pull Request + +Go back to your pull request after a few minutes and see whether it passed muster with Travis-CI. Everything should look green, otherwise fix issues and amend your commit as described above. diff --git a/DEPENDENCIES.md b/DEPENDENCIES.md new file mode 100644 index 0000000..292437a --- /dev/null +++ b/DEPENDENCIES.md @@ -0,0 +1,7 @@ +### Bigcommerce 💙 Open Source + +Many thanks to the contributors and authors of the following libraries! + +- [Faraday](https://github.com/lostisland/faraday) Simple, but flexible HTTP client library, with support for multiple backends. - [MIT](https://github.com/lostisland/faraday/blob/master/LICENSE.md) +- [Faraday Middleware](https://github.com/lostisland/faraday_middleware) Various Faraday middlewares for Faraday-based API wrappers. - [MIT](https://github.com/lostisland/faraday_middleware/blob/master/LICENSE.md) +- [Hashie](https://github.com/intridea/hashie) Hashie is a collection of classes and mixins that make hashes more powerful. - [MIT](https://github.com/intridea/hashie/blob/master/LICENSE) diff --git a/Gemfile b/Gemfile index 180cd37..6a0c722 100644 --- a/Gemfile +++ b/Gemfile @@ -1,10 +1,15 @@ -source 'http://rubygems.org' +source 'https://rubygems.org' +gemspec -platforms :rbx do - gem 'racc' - gem 'rubinius-coverage' - gem 'rubysl', '~> 2.0' - gem 'psych' +group :development do + gem 'pry' + gem 'rubocop' + gem 'guard' + gem 'guard-rspec' end -gemspec +group :test do + gem 'rspec' + gem 'simplecov' + gem 'coveralls' +end diff --git a/Guardfile b/Guardfile new file mode 100644 index 0000000..657ae38 --- /dev/null +++ b/Guardfile @@ -0,0 +1,22 @@ +guard 'rspec', all_on_start: false, cmd: 'bundle exec rspec' do + # Watch spec directory + watch(/^spec\/.+_spec\.rb/) + + # Watch lib/*.rb + watch(/^lib\/(.+)\.rb/) do |m| + "spec/bigcommerce/#{m[1]}_spec.rb" + end + + # Watch lib/bigcommerce/*.rb + watch(%r{^lib/bigcommerce/(.+).rb$}) do |m| + "spec/bigcommerce/unit/#{m[1]}_spec.rb" + end + + # Watch lib/bigcommerce/(middleware|resources)/*.rb + watch(%r{^lib/bigcommerce/(middleware|resources)/(.+).rb$}) do |m| + "spec/bigcommerce/unit/#{m[1]}/#{m[2]}_spec.rb" + end + + # Watch spec_helper + watch('spec/spec_helper.rb') { 'spec' } +end diff --git a/LICENSE b/LICENSE index 0eef486..3d697f0 100644 --- a/LICENSE +++ b/LICENSE @@ -1,20 +1,20 @@ Copyright (C) Bigcommerce, 2015. All rights reserved. -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the "Software"), +to deal in the Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE +OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md index c8d42c8..22e5e28 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# Bigcommerce API V2 - Ruby Client +# Bigcommerce [![Gem Version](https://badge.fury.io/rb/bigcommerce.png)](https://rubygems.org/gems/bigcommerce) [![Build Status](https://travis-ci.org/bigcommerce/bigcommerce-api-ruby.png?branch=master)](https://travis-ci.org/bigcommerce/bigcommerce-api-ruby) @@ -6,104 +6,95 @@ [![Code Climate](https://codeclimate.com/github/bigcommerce/bigcommerce-api-ruby.png)](https://codeclimate.com/github/bigcommerce/bigcommerce-api-ruby) [![Coverage Status](https://coveralls.io/repos/bigcommerce/bigcommerce-api-ruby/badge.png?branch=master)](https://coveralls.io/r/bigcommerce/bigcommerce-api-ruby?branch=master) -This library provides a wrapper around the Bigcommerce REST API for use within -Ruby apps or via the console. +This is the official Bigcommerce API client to support our Rest API. You can find more information about becoming a Bigcommerce developer here: [developer.bigcommerce.com](http://developer.bigcommerce.com). -### Note +#### ⚠️ A note about the current client: ⚠️ +This is a preview release of the 1.0.0 version of the Bigcommerce API Client. Please report issues if they come up. -If you find anything that is missing or needs clean up, please feel free to fork -it and submit a changes with your pull request. +We have introduced a new major version of the API client and it is a complete rewrite (for the better). If you want to see the old version of the API client, please view it here: [Bigcommerce API client v0.x](https://github.com/bigcommerce/bigcommerce-api-ruby/tree/0.x). We recommend that developers upgrade to the latest client, but we will still support our developers who are unable to upgrade. -## Requirements -- Ruby 1.9+ +## Installation +Bigcommerce is available on Rubygems: -To connect to the API, you need the following credentials: +```sh +gem install bigcommerce --pre +``` -For the OAuth API: +You can also add it to your Gemfile. -- Create and register an app at [developer.bigcommerce.com](https://developer.bigcommerce.com). -- Have a callback URL defined -- Prepare the `client_id` credential +```rb +gem 'bigcommerce', '>= 1.0.0.beta' +``` -For the Legacy API: +## Getting Started +In order to make requests to our API, you must register as a developer and have your credentials ready. -- Secure URL pointing to a Bigcommerce store -- Username of an authorized admin user of the store -- API key for the user +We currently have two different authentication schemes you can use depending on your use-case. -A valid API key is required to authenticate requests. To grant API access for a user, go to Control Panel > Users > Edit User and make sure that the 'Enable API access?' checkbox is ticked. +#### Public Apps +Public apps can be submitted to Bigcommerce App Store, allowing other businesses to install it in their Bigcommerce stores. -## Installation +[More Information](https://developer.bigcommerce.com/api/using-oauth-intro) -Download the lib folder and copy it to a path accessible within your app, or -install the package directly from Rubygems: +#### Private Apps +To develop a custom integration for one store, your app needs to use Basic Authentication. -```sh -gem install bigcommerce -``` +[More Information](https://developer.bigcommerce.com/api/legacy/basic-auth) -## Configuration +## Usage +For full examples on using the API client, please see the [examples folder](examples). -#### OAuth Authentication +## Configuration +In order to authenticate the API client, you will need to configure the client like this: -In order to create a new Bigcommerce application, please visit [developer.bigcommerce.com](https://developer.bigcommerce.com). Its free to sign up and only takes a moment. Once you have created your app, you can get a `client_id`. +#### Single Click (Public Apps): -To use the API client in your Ruby code, provide the required credentials as -follows: +- ```client_id```: Obtained from the "My Apps" section on the [developer portal](http://developer.bigcommerce.com). +- ```access_token```: Obtained after a token exchange in the auth callback. +- ```store_hash```: Also obtained after the token exchange. ```rb -require 'bigcommerce' - -api = Bigcommerce::Api.new({ - :store_hash => 'STORE_HASH', - :client_id => 'CLIENT_ID', - :access_token => 'ACCESS_TOKEN' -}) +Bigcommerce.configure do |config| + config.store_hash = 'store_hash' + config.client_id = 'client_id' + config.access_token = 'access_token' +end ``` -__NOTE:__ You do not need extra SSL certificates when connecting to the OAuth version of the api. - -#### Legacy Credentials +#### Private Apps: -To use the API client with the legacy credentials you can visit the main store page and under the "Setup & Tools" dropdown, you will see a link for the legacy API credentials. +To get all the private app credentials, simply visit your store admin page and navigate to the Settings > Legacy API Settings. Once there, you can create a new username to authenticate with. ```rb -require 'bigcommerce' - -api = Bigcommerce::Api.new({ - :store_url => "https://store.mybigcommerce.com", - :username => "username", - :api_key => "api_key" -}) +Bigcommerce.configure do |config| + config.auth = 'legacy' + config.url = 'https://api_path.com' + config.username = 'username' + config.api_key = 'api_key' +end ``` -You can also enable SSL for the Legacy API. +__SSL Configuration:__ -```rb -require 'bigcommerce' - -api = Bigcommerce::Api.new({ - :store_url => "https://store.mybigcommerce.com", - :username => "username", - :api_key => "api_key", - :ssl_client_cert => OpenSSL::X509::Certificate.new(File.read("cert.pem")), - :ssl_client_key => OpenSSL::PKey::RSA.new(File.read("key.pem"), "passphrase, if any"), - :ssl_ca_file => "ca_certificate.pem", - :verify_ssl => OpenSSL::SSL::VERIFY_PEER -}) -``` -Remember that the fields `:ssl_client_cert`, `:ssl_client_key`, `:ssl_ca_file` -and `:verify_ssl` are all required when enabling SSL certificates. - -## Connecting to the store - -Once you have authenticated with the OAuth or Legacy credentials, ping the time method to check that your configuration is working and you can connect successfully to the store: +If you are using your own self-signed certificate, you can pass SSL options to Faraday. This is not required, but may be useful in special edge cases. ```rb -ping = api.time() +Bigcommerce.configure do |config| + config.auth = 'legacy' + config.url = 'https://api_path.com' + config.username = 'username' + config.api_key = 'api_key' + config.ssl = { + # Faraday options here + } +end ``` -## Reference +For more information about configuring SSL with Faraday, please see the following: + +- [Faraday SSL example](https://gist.github.com/mislav/938183) +- [Setting up SSL certificates](https://github.com/lostisland/faraday/wiki/Setting-up-SSL-certificates) -For full reference about the resources and supported endpoints, please see [developer.bigcommerce.com](https://developer.bigcommerce.com). \ No newline at end of file +## Contributing +See [CONTRIBUTING.md](CONTRIBUTING.md) diff --git a/RELEASING.md b/RELEASING.md new file mode 100644 index 0000000..35bb015 --- /dev/null +++ b/RELEASING.md @@ -0,0 +1,64 @@ +# Releasing Bigcommerce API Client + +There're no particular rules about when to release the Bigcommerce API client. Release bug fixes frequently, features not so frequently, and breaking API changes rarely. + +### Before A Release + +Run tests, check that all tests succeed locally. + +```sh +bundle install +bundle exec rake +``` + +This will ensure both style and that all the specs pass locally. Next, check that the last build succeeded in [Travis CI](https://travis-ci.org/bigcommerce/bigcommerce-api-ruby) for all supported platforms. + +Increment the version, modify [lib/bigcommerce/version.rb](lib/bigcommerce/version.rb). + +* Increment the third number (minor version) if the release has bug fixes and/or very minor features, only (eg. change `1.0.1` to `1.0.2`). +* Increment the second number (patch version) if the release contains major features or breaking API changes (eg. change `1.0.10` to `1.1.0`). + +Change "Next Release" in [CHANGELOG.md](CHANGELOG.md) to the new version. + +```markdown +1.1.0 (4/13/2015) +================= +``` + +Commit your changes. + +```sh +git add CHANGELOG.md lib/bigcommerce/version.rb +git commit -m "Preparing for release, 1.1.0." +git push origin master +``` + +### Release 🎉 + +```sh +$ rake release + +bigcommerce 1.1.0 built to pkg/bigcommerce-1.1.0.gem. +Tagged v1.1.0. +Pushed git commits and tags. +Pushed bigcommerce 1.1.0 to rubygems.org. +``` + +### Prepare for the Next Version + +Add the next release to [CHANGELOG.md](CHANGELOG.md). + +```markdown +Next Release +============ + +* Your contribution here. +``` + +Commit your changes. + +```sh +git add CHANGELOG.md README.md +git commit -m "Preparing for next release." +git push origin master +``` diff --git a/Rakefile b/Rakefile index ebf293e..856481c 100644 --- a/Rakefile +++ b/Rakefile @@ -1,11 +1,13 @@ -require 'bundler/gem_tasks' -require 'ci/reporter/rake/rspec' require 'rspec/core/rake_task' +require 'bundler/gem_tasks' +require 'bigcommerce' -Bundler::GemHelper.install_tasks - -RSpec::Core::RakeTask.new(:spec) do |spec| +RSpec::Core::RakeTask.new do |spec| spec.pattern = 'spec/**/*_spec.rb' + spec.verbose = false end -task :default => ['ci:setup:rspec', :spec] +require 'rubocop/rake_task' +RuboCop::RakeTask.new(:rubocop) + +task default: [:rubocop, :spec] diff --git a/bigcommerce.gemspec b/bigcommerce.gemspec index f9e38fa..f715d96 100644 --- a/bigcommerce.gemspec +++ b/bigcommerce.gemspec @@ -1,59 +1,28 @@ -# -*- encoding: utf-8 -*- -# stub: bigcommerce 0.9.0 ruby lib +lib = File.expand_path('../lib', __FILE__) +$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) +require 'bigcommerce/version' Gem::Specification.new do |s| - s.name = "bigcommerce" - s.version = "0.10.0" - - s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= - s.authors = ["Mark Rickerby", "Rob Howard", "Saranyan Vigraham", "Sasha Gerrand"] - s.date = "2015-01-27" - s.description = "Enables Ruby applications to communicate with the Bigcommerce API V2." + s.name = 'bigcommerce' + s.homepage = 'https://github.com/bigcommerce/bigcommerce-api-ruby' + s.authors = ['Patrick Edelman'] + s.version = Bigcommerce::VERSION s.license = 'MIT' - s.email = ["mark.rickerby@bigcommerce.com", "rob.howard@bigcommerce.com", "saranyan.vigraham@bigcommerce.com", "sasha.gerrand@bigcommerce.com"] - s.files = ["LICENSE", "Rakefile", "README.md", "bigcommerce.gemspec", "./lib/big_commerce.rb", "./lib/bigcommerce/api.rb", "./lib/bigcommerce/connection.rb", "./lib/bigcommerce/version.rb", "./lib/bigcommerce/resource.rb", "./lib/bigcommerce/product.rb", "./lib/bigcommerce.rb", "./spec/big_commerce_spec.rb", "./spec/integration/orders_spec.rb", "./spec/spec_helper.rb", "./spec/support/integration_context.rb", "./spec/support/mock_api_context.rb", "./spec/unit/api_request_spec.rb", "./spec/unit/api_spec.rb", "./spec/unit/connection_spec.rb", "./spec/unit/date_time_spec.rb", "./spec/unit/version_spec.rb", "spec/big_commerce_spec.rb", "spec/integration/orders_spec.rb", "spec/unit/api_request_spec.rb", "spec/unit/api_spec.rb", "spec/unit/connection_spec.rb", "spec/unit/date_time_spec.rb", "spec/unit/version_spec.rb"] - s.homepage = "http://github.com/bigcommerce/bigcommerce-api-ruby" - s.require_paths = ["lib"] - s.rubygems_version = "2.1.11" - s.summary = "Enables Ruby applications to communicate with the Bigcommerce API" - s.test_files = ["spec/big_commerce_spec.rb", "spec/integration/orders_spec.rb", "spec/unit/api_request_spec.rb", "spec/unit/api_spec.rb", "spec/unit/connection_spec.rb", "spec/unit/date_time_spec.rb", "spec/unit/version_spec.rb"] - if s.respond_to? :specification_version then - s.specification_version = 4 + s.description = 'Bigcommerce API Ruby client library. Allows developers to \ + easily communicate with the Bigcommerce API, for either CLI tools or public \ + apps. More info: http://developer.bigcommerce.com' + s.summary = 'Ruby client library for the Bigcommerce v2 API' + + s.required_ruby_version = '>= 1.9.3' + s.require_paths = ['lib'] + s.files = `git ls-files`.split($ORS) + s.test_files = Dir['spec/**/*.rb'] + + s.add_development_dependency 'rake' + s.add_development_dependency 'bundler' - if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then - s.add_runtime_dependency(%q, [">= 0"]) - s.add_runtime_dependency(%q, [">= 0"]) - s.add_runtime_dependency(%q, [">= 0"]) - s.add_development_dependency(%q, [">= 0"]) - s.add_development_dependency(%q, [">= 0"]) - s.add_development_dependency(%q, [">= 0"]) - s.add_development_dependency(%q, [">= 0"]) - s.add_development_dependency(%q, ["~> 2.11"]) - s.add_development_dependency(%q, [">= 0"]) - s.add_development_dependency(%q, ["= 1.9"]) - else - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, ["~> 2.11"]) - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, ["= 1.9"]) - end - else - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, ["~> 2.11"]) - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, ["= 1.9"]) - end + s.add_dependency 'faraday' + s.add_dependency 'faraday_middleware' + s.add_dependency 'hashie' end diff --git a/examples/README.md b/examples/README.md new file mode 100644 index 0000000..4b78d6c --- /dev/null +++ b/examples/README.md @@ -0,0 +1,148 @@ +# Examples +In this directory you can find examples which you may find helpful to reference in development. If you have some useful snippets, please feel free to open a PR into the appropriate file(s). + +#### Resource Reference +For reference on the individual resources and the schema of the objects, please visit [developer.bigcommerce.com](https://developer.bigcommerce.com). + +## Configuration +#### [Private Apps](configuration/legacy_auth.rb) +Public apps (also known as Single-Click Apps) must use OAuth authentication. + +#### [Public Apps](configuration/oauth.rb) +To develop a custom integration for one store, your app needs to use Basic Authentication. + +## Content +#### [Blog Posts](content/blog_post.rb) +A content entry in the store’s blog + +#### [Blog Tags](content/blog_tag.rb) +Index of tags used on the store’s blog. + +#### [Redirects](content/redirect.rb) +A 301 redirect, mapping from a given URL path to another URL + +## Customers +#### [Customers](customers/customer.rb) +Identity and account details for customers shopping on Bigcommerce stores + +#### [Customer Addresses](customers/customer_address.rb) +Postal address belonging to a Customer + +#### [Customer Groups](customers/customer_group.rb) +Grouping of customers who share the same level of access and discounts at a store + +## Geography +#### [Countries](geography/country.rb) +A country or territory, identifiable by an ISO 3166 country code + +#### [States](geography/state.rb) +A state or province, identifiable by an ISO 3166 subdivision code + +## Marketing +#### [Coupons](marketing/coupon.rb) +Applies a category or product discount to an order for customers who enter a given code + +## Orders +#### [Orders](orders/order.rb) +The order object contains a record of the purchase agreement between a shopper and a merchant. + +#### [Order Coupons](orders/order_coupon.rb) +Coupon code applied to an order + +#### [Order Messages](orders/order_message.rb) +Messages associated with an order. + +#### [Order Products](orders/order_product.rb) +Product line items associated with an order. + +#### [Order Shipping Addresses](orders/order_shipping_address.rb) +Shipping addresses associated with an order. + +#### [Order Statuses](orders/order_status.rb) +Statuses that can be assigned to orders. Each status represents a state in the fulfilment workflow. + +#### [Order Taxes](orders/order_tax.rb) +Taxes applied to an order. + +#### [Shipments](orders/shipment.rb) +Shipping package consignments tracked from an order. + +## Payments +#### [Payment Methods](payments/payment_methods.rb) +Enabled payment methods. + +## Products +#### [Brands](products/brand.rb) +Brand facets for identifying and categorising products according to their manufacturer or company metonym. + +#### [Bulk Pricing Rules](products/bulk_pricing_rule.rb) +Bulk pricing rules applied to a product. + +#### [Categories](products/category.rb) +Index of hierarchical categories used to organise and group products. + +#### [Configurable Fields ](products/configurable_field.rb) +Configurable fields associated with a product. + +#### [Custom Fields](products/custom_field.rb) +Custom fields associated with a product. + +#### [Google Product Search Mappings](products/google_product_search_mapping.rb) +Custom fields associated with a product. + +#### [Options](products/option.rb) +Shared attributes that control value facets on a product. + +#### [Option Sets](products/option_set.rb) +A reusable set of option facets that can be applied to products. + +#### [Option Set Options](products/option_set_option.rb) +Options belonging to an option set. + +#### [Option Values](products/option_value.rb) +Values that can be selected for an option. + +#### [Products](products/product.rb) +Catalog of saleable items in the store. + +#### [Product Images](products/product_image.rb) +Images associated with a product. + +#### [Product Options](products/product_option.rb) +Options associated directly with a product. + +#### [Product Reviews](products/product_review.rb) +Reviews associated to a product. + +#### [Product Rules](products/product_rule.rb) +Rules that modify the default behaviour of products. + +#### [Product Videos](products/product_video.rb) +Embedded videos displayed on product listings. + +#### [SKUs](products/sku.rb) +Stock Keeping Unit identifiers associated with products. + +## Shipping +#### [Shipping Methods](shipping/shipping_method.rb) +List of enabled shipping methods. + +## Store +#### [Store Information](store/store_info.rb) +Metadata that describes the store. + +## System +#### [Time](system/time.rb) +Timestamp ping to check the system status. + +## Tax +#### [Tax Classes](tax/tax_class.rb) +Applies a category or product discount to an order for customers who enter a given code + +## Webhooks +#### [Webhooks](webhooks/webhook.rb) +Applies a category or product discount to an order for customers who enter a given code + +## Exception Handling +#### [Exceptions](exception_handling.rb) +All the errors we will throw with a convenient method to rescue the errors and take an action for each type diff --git a/examples/configuration/legacy_auth.rb b/examples/configuration/legacy_auth.rb new file mode 100644 index 0000000..6b7e6ee --- /dev/null +++ b/examples/configuration/legacy_auth.rb @@ -0,0 +1,12 @@ +require 'bigcommerce' + +Bigcommerce.configure do |config| + config.auth = 'legacy' + # You will get this url when registering for an API key + config.url = ENV['BC_API_ENDPOINT_LEGACY'] + config.username = ENV['BC_USERNAME'] + config.api_key = ENV['BC_API_KEY'] +end + +puts Bigcommerce::System.time +puts Bigcommerce.api_limit diff --git a/examples/configuration/oauth.rb b/examples/configuration/oauth.rb new file mode 100644 index 0000000..d9917d8 --- /dev/null +++ b/examples/configuration/oauth.rb @@ -0,0 +1,9 @@ +require 'bigcommerce' + +Bigcommerce.configure do |config| + config.store_hash = ENV['BC_STORE_HASH'] + config.client_id = ENV['BC_CLIENT_ID'] + config.access_token = ENV['BC_ACCESS_TOKEN'] +end + +puts Bigcommerce::System.time diff --git a/examples/content/blog_post.rb b/examples/content/blog_post.rb new file mode 100644 index 0000000..a9c0874 --- /dev/null +++ b/examples/content/blog_post.rb @@ -0,0 +1,39 @@ +require 'bigcommerce' + +Bigcommerce.configure do |config| + config.store_hash = ENV['BC_STORE_HASH'] + config.client_id = ENV['BC_CLIENT_ID'] + config.access_token = ENV['BC_ACCESS_TOKEN'] +end + +# List blog posts +@posts = Bigcommerce::BlogPost.all(page: 1) +puts @posts + +# Get a blog post +puts Bigcommerce::BlogPost.find(@posts[0].id) + +# Get a count of blog posts +puts Bigcommerce::BlogPost.count + +# Create a blog post +@post = Bigcommerce::BlogPost.create( + title: 'Brand new producrts for sale!', + body: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do \ + eiusmod tempor incididunt ut labore et dolore magna aliqua. \ + Excepteur sint occaecat cupidatat non proident, sunt in culpa qui \ + officia deserunt mollit anim id est laborum.' +) +puts @post + +# Update a blog post +puts Bigcommerce::BlogPost.update( + @post.id, + title: 'Oops wrong title.' +) + +# Delete a blog post +puts Bigcommerce::BlogPost.destroy(@post.id) + +# Delete all blog posts +# puts Bigcommerce::BlogPost.destroy_all diff --git a/examples/content/blog_tag.rb b/examples/content/blog_tag.rb new file mode 100644 index 0000000..e9c951f --- /dev/null +++ b/examples/content/blog_tag.rb @@ -0,0 +1,10 @@ +require 'bigcommerce' + +Bigcommerce.configure do |config| + config.store_hash = ENV['BC_STORE_HASH'] + config.client_id = ENV['BC_CLIENT_ID'] + config.access_token = ENV['BC_ACCESS_TOKEN'] +end + +# List blog tags +puts Bigcommerce::BlogTag.all diff --git a/examples/content/redirect.rb b/examples/content/redirect.rb new file mode 100644 index 0000000..1ddcf0b --- /dev/null +++ b/examples/content/redirect.rb @@ -0,0 +1,43 @@ +require 'bigcommerce' + +Bigcommerce.configure do |config| + config.store_hash = ENV['BC_STORE_HASH'] + config.client_id = ENV['BC_CLIENT_ID'] + config.access_token = ENV['BC_ACCESS_TOKEN'] +end + +# List redirects +@redirects = Bigcommerce::Redirect.all(page: 1) +puts @redirects + +# Get a redirect +puts Bigcommerce::Redirect.find(@redirects[0].id) + +# Get a count of redirects +puts Bigcommerce::Redirect.count + +# Create a redirect +@redirect = Bigcommerce::Redirect.create( + path: '/womens_clothing', + forward: { + type: 'category', + ref: 3 + } +) +puts @redirect + +# Update a redirect +puts Bigcommerce::Redirect.update( + @redirect.id, + path: '/womens_clothing', + forward: { + type: 'category', + ref: 3 + } +) + +# Delete a redirect +puts Bigcommerce::Redirect.destroy(@redirect.id) + +# Delete all redirects +# puts Bigcommerce::Redirect.destroy_all diff --git a/examples/customers/customer.rb b/examples/customers/customer.rb new file mode 100644 index 0000000..eeab597 --- /dev/null +++ b/examples/customers/customer.rb @@ -0,0 +1,36 @@ +require 'bigcommerce' + +Bigcommerce.configure do |config| + config.store_hash = ENV['BC_STORE_HASH'] + config.client_id = ENV['BC_CLIENT_ID'] + config.access_token = ENV['BC_ACCESS_TOKEN'] +end + +# List customers +puts Bigcommerce::Customer.all(page: 1) + +# Get a customer +puts Bigcommerce::Customer.find(1) + +# Get a count of customers +puts Bigcommerce::Customer.count + +# Create a customer +@customer = Bigcommerce::Customer.create( + first_name: 'Karl', + last_name: 'The Fog', + email: 'test@example.com' +) +puts @customer + +# Update a customer +puts Bigcommerce::Customer.update( + @customer.id, + first_name: 'Karrrl' +) + +# Delete a customer +puts Bigcommerce::Customer.destroy(@customer.id) + +# Delete all customers +# puts Bigcommerce::Customer.destroy_all diff --git a/examples/customers/customer_address.rb b/examples/customers/customer_address.rb new file mode 100644 index 0000000..e10e7ce --- /dev/null +++ b/examples/customers/customer_address.rb @@ -0,0 +1,50 @@ +require 'bigcommerce' + +Bigcommerce.configure do |config| + config.store_hash = ENV['BC_STORE_HASH'] + config.client_id = ENV['BC_CLIENT_ID'] + config.access_token = ENV['BC_ACCESS_TOKEN'] +end + +@customer = Bigcommerce::Customer.all[0] + +# List a customer address +@customer_addresses = Bigcommerce::CustomerAddress.all(@customer.id) +puts @customer_addresses + +# Get a customer address +puts Bigcommerce::CustomerAddress.find(@customer.id, @customer_addresses[0].id) + +# Get a count of customer addresses +puts Bigcommerce::CustomerAddress.count(@customer.id) + +# Get a count of all customer addresses for all customers +puts Bigcommerce::CustomerAddress.count_all + +# Create a customer address +@customer_address = Bigcommerce::CustomerAddress.create( + @customer.id, + first_name: 'Foo', + last_name: 'Bar', + phone: '5555555555', + street_1: '685 Market St.', + city: 'San Francisco', + state: 'California', + zip: '94019', + country: 'United States' +) +puts @customer_address + +# Update a customer address +puts Bigcommerce::CustomerAddress.update( + @customer.id, + @customer_address.id, + first_name: 'Foo', + last_name: 'Bar' +) + +# Delete a customer address +puts Bigcommerce::CustomerAddress.destroy(@customer.id, @customer_address.id) + +# Delete all customer addresses +# puts Bigcommerce::CustomerAddress.destroy_all(@customer.id) diff --git a/examples/customers/customer_group.rb b/examples/customers/customer_group.rb new file mode 100644 index 0000000..8994572 --- /dev/null +++ b/examples/customers/customer_group.rb @@ -0,0 +1,35 @@ +require 'bigcommerce' +require 'securerandom' + +Bigcommerce.configure do |config| + config.store_hash = ENV['BC_STORE_HASH'] + config.client_id = ENV['BC_CLIENT_ID'] + config.access_token = ENV['BC_ACCESS_TOKEN'] +end + +# List all customer groups +puts Bigcommerce::CustomerGroup.all + +# Get a customer group +puts Bigcommerce::CustomerGroup.find(1) + +# Get a count of all customer groups +puts Bigcommerce::CustomerGroup.count + +# Create a customer group +@customer_group = Bigcommerce::CustomerGroup.create( + name: "Customer Group #{SecureRandom.hex}" +) +puts @customer_group + +# Update a customer group +puts Bigcommerce::CustomerGroup.update( + @customer_group.id, + name: "Customer_group #{SecureRandom.hex}" +) + +# Delete a customer group +puts Bigcommerce::CustomerGroup.destroy(@customer_group.id) + +# Delete all customer groups +# puts Bigcommerce::CustomerGroup.destroy_all diff --git a/examples/exception_handling.rb b/examples/exception_handling.rb new file mode 100644 index 0000000..7569819 --- /dev/null +++ b/examples/exception_handling.rb @@ -0,0 +1,50 @@ +require 'bigcommerce' + +Bigcommerce.configure do |config| + config.store_hash = ENV['BC_STORE_HASH'] + config.client_id = ENV['BC_CLIENT_ID'] + config.access_token = ENV['BC_ACCESS_TOKEN'] +end + +# rubocop:disable MethodLength, Metrics/AbcSize: +def bc_handle_exception(&block) + # Below is a list of all the errors we will throw + block.call +rescue Bigcommerce::BadRequest => e + puts e.inspect +rescue Bigcommerce::Unauthorized => e + puts e.inspect +rescue Bigcommerce::Forbidden => e + puts e.inspect +rescue Bigcommerce::NotFound => e + puts e.inspect +rescue Bigcommerce::MethodNotAllowed => e + puts e.inspect +rescue Bigcommerce::NotAccepted => e + puts e.inspect +rescue Bigcommerce::TimeOut => e + puts e.inspect +rescue Bigcommerce::ResourceConflict => e + puts e.inspect +rescue Bigcommerce::TooManyRequests => e + puts e.inspect +rescue Bigcommerce::InternalServerError => e + puts e.inspect +rescue Bigcommerce::BadGateway => e + puts e.inspect +rescue Bigcommerce::ServiceUnavailable => e + puts e.inspect +rescue Bigcommerce::GatewayTimeout => e + puts e.inspect +rescue Bigcommerce::BandwidthLimitExceeded => e + puts e.inspect +rescue => e + puts "Some other Error #{e.inspect}" +end + +Bigcommerce::HttpError::ERRORS.each do |k, v| + bc_handle_exception do + # This will be your request that you want to protect from exceptions + fail v, k + end +end diff --git a/examples/geography/country.rb b/examples/geography/country.rb new file mode 100644 index 0000000..2c37eb4 --- /dev/null +++ b/examples/geography/country.rb @@ -0,0 +1,16 @@ +require 'bigcommerce' + +Bigcommerce.configure do |config| + config.store_hash = ENV['BC_STORE_HASH'] + config.client_id = ENV['BC_CLIENT_ID'] + config.access_token = ENV['BC_ACCESS_TOKEN'] +end + +# List countries +puts Bigcommerce::Country.all(page: 1) + +# Get a country +puts Bigcommerce::Country.find(226) + +# Get a count of countries +puts Bigcommerce::Country.count diff --git a/examples/geography/state.rb b/examples/geography/state.rb new file mode 100644 index 0000000..c0c59ec --- /dev/null +++ b/examples/geography/state.rb @@ -0,0 +1,19 @@ +require 'bigcommerce' + +Bigcommerce.configure do |config| + config.store_hash = ENV['BC_STORE_HASH'] + config.client_id = ENV['BC_CLIENT_ID'] + config.access_token = ENV['BC_ACCESS_TOKEN'] +end + +# List countries +puts Bigcommerce::State.all(226) + +# Get a country +puts Bigcommerce::State.find(226, 10) + +# Get a count of countries +puts Bigcommerce::State.count(226) + +# Get a count of all states for all countries +puts Bigcommerce::State.count_all diff --git a/examples/marketing/coupon.rb b/examples/marketing/coupon.rb new file mode 100644 index 0000000..9272979 --- /dev/null +++ b/examples/marketing/coupon.rb @@ -0,0 +1,44 @@ +require 'bigcommerce' +require 'securerandom' + +Bigcommerce.configure do |config| + config.store_hash = ENV['BC_STORE_HASH'] + config.client_id = ENV['BC_CLIENT_ID'] + config.access_token = ENV['BC_ACCESS_TOKEN'] +end + +# List coupons +@coupons = Bigcommerce::Coupon.all +puts @coupons + +# Get a coupon +puts Bigcommerce::Coupon.find(@coupons[0].id) + +# Get a count of coupons +puts Bigcommerce::Coupon.count + +# Create a coupon +@coupon = Bigcommerce::Coupon.create( + name: SecureRandom.hex, + code: SecureRandom.hex, + type: 'per_item_discount', + amount: 5, + applies_to: { + entity: 'categories', + ids: [0] + } +) +puts @coupon + +# Update a coupon +puts Bigcommerce::Coupon.update( + @coupon.id, + name: SecureRandom.hex, + amount: 10 +) + +# Delete a coupon +puts Bigcommerce::Coupon.destroy(@coupon.id) + +# Delete all coupons +# puts Bigcommerce::Coupon.destroy_all diff --git a/examples/orders/order.rb b/examples/orders/order.rb new file mode 100644 index 0000000..957ebbc --- /dev/null +++ b/examples/orders/order.rb @@ -0,0 +1,53 @@ +require 'bigcommerce' + +Bigcommerce.configure do |config| + config.store_hash = ENV['BC_STORE_HASH'] + config.client_id = ENV['BC_CLIENT_ID'] + config.access_token = ENV['BC_ACCESS_TOKEN'] +end + +# List orders +@orders = Bigcommerce::Order.all +puts @orders + +# Get an order +@order = @orders[0] +puts Bigcommerce::Order.find(@order.id) + +# Get a count of orders +puts Bigcommerce::Order.count + +# Create an order +@order = Bigcommerce::Order.create( + billing_address: { + first_name: 'Karl', + last_name: 'The Fog', + street_1: '685 Market St.', + city: 'San Francisco', + state: 'California', + zip: '94019', + country: 'United States', + email: 'test@example.com' + }, + products: [ + { + product_id: 34, + quantity: 2 + } + ] +) +puts @order + +# Update an order +puts Bigcommerce::Order.update( + @order.id, + billing_address: { + last_name: 'TheFog' + } +) + +# Delete an order +puts Bigcommerce::Order.destroy(@order.id) + +# Delete all orders +# puts Bigcommerce::Order.destroy_all diff --git a/examples/orders/order_coupon.rb b/examples/orders/order_coupon.rb new file mode 100644 index 0000000..b3822e9 --- /dev/null +++ b/examples/orders/order_coupon.rb @@ -0,0 +1,17 @@ +require 'bigcommerce' + +Bigcommerce.configure do |config| + config.store_hash = ENV['BC_STORE_HASH'] + config.client_id = ENV['BC_CLIENT_ID'] + config.access_token = ENV['BC_ACCESS_TOKEN'] +end + +@order = Bigcommerce::Order.all[0] + +# List order coupons +@order_coupons = Bigcommerce::OrderCoupon.all(@order.id) +puts @order_coupons + +# Get an order coupon +@order_coupon = @order_coupons[0] +puts Bigcommerce::OrderCoupon.find(@order.id, @order_coupon.id) diff --git a/examples/orders/order_message.rb b/examples/orders/order_message.rb new file mode 100644 index 0000000..3284289 --- /dev/null +++ b/examples/orders/order_message.rb @@ -0,0 +1,17 @@ +require 'bigcommerce' + +Bigcommerce.configure do |config| + config.store_hash = ENV['BC_STORE_HASH'] + config.client_id = ENV['BC_CLIENT_ID'] + config.access_token = ENV['BC_ACCESS_TOKEN'] +end + +@order = Bigcommerce::Order.all[0] + +# List order messages +@order_messages = Bigcommerce::OrderMessage.all(@order.id) +puts @order_messages + +# Get an order message +@order_message = @order_messages[0] +puts Bigcommerce::OrderMessage.find(@order.id, @order_message.id) diff --git a/examples/orders/order_product.rb b/examples/orders/order_product.rb new file mode 100644 index 0000000..8610664 --- /dev/null +++ b/examples/orders/order_product.rb @@ -0,0 +1,23 @@ +require 'bigcommerce' + +Bigcommerce.configure do |config| + config.store_hash = ENV['BC_STORE_HASH'] + config.client_id = ENV['BC_CLIENT_ID'] + config.access_token = ENV['BC_ACCESS_TOKEN'] +end + +@order = Bigcommerce::Order.all[0] + +# List order products +@order_products = Bigcommerce::OrderProduct.all(@order.id) +puts @order_products + +# Get an order product +@order_product = @order_products[0] +puts Bigcommerce::OrderProduct.find(@order.id, @order_product.id) + +# Get a count of order products +puts Bigcommerce::OrderProduct.count(@order.id) + +# Get a count of all order products for all orders +puts Bigcommerce::OrderProduct.count_all diff --git a/examples/orders/order_shipping_address.rb b/examples/orders/order_shipping_address.rb new file mode 100644 index 0000000..eb6c202 --- /dev/null +++ b/examples/orders/order_shipping_address.rb @@ -0,0 +1,23 @@ +require 'bigcommerce' + +Bigcommerce.configure do |config| + config.store_hash = ENV['BC_STORE_HASH'] + config.client_id = ENV['BC_CLIENT_ID'] + config.access_token = ENV['BC_ACCESS_TOKEN'] +end + +@order = Bigcommerce::Order.all[0] + +# List order shipping address +@order_shipping_addresses = Bigcommerce::OrderShippingAddress.all(@order.id) +puts @order_shipping_addresses + +# Get an order shipping address +@order_shipping_address = @order_shipping_addresses[0] +puts Bigcommerce::OrderShippingAddress.find(@order.id, @order_shipping_address.id) + +# Get a count of order shipping addresses +puts Bigcommerce::OrderShippingAddress.count(@order.id) + +# Get a count of all order shipping addresses for all order +puts Bigcommerce::OrderShippingAddress.count_all diff --git a/examples/orders/order_status.rb b/examples/orders/order_status.rb new file mode 100644 index 0000000..4a3a81a --- /dev/null +++ b/examples/orders/order_status.rb @@ -0,0 +1,15 @@ +require 'bigcommerce' + +Bigcommerce.configure do |config| + config.store_hash = ENV['BC_STORE_HASH'] + config.client_id = ENV['BC_CLIENT_ID'] + config.access_token = ENV['BC_ACCESS_TOKEN'] +end + +# List order statuses +@order_statuses = Bigcommerce::OrderStatus.all +puts @order_statuses + +# Get an order status +@order_status = @order_statuses[0] +puts Bigcommerce::OrderStatus.find(@order_status.id) diff --git a/examples/orders/order_tax.rb b/examples/orders/order_tax.rb new file mode 100644 index 0000000..9076b01 --- /dev/null +++ b/examples/orders/order_tax.rb @@ -0,0 +1,17 @@ +require 'bigcommerce' + +Bigcommerce.configure do |config| + config.store_hash = ENV['BC_STORE_HASH'] + config.client_id = ENV['BC_CLIENT_ID'] + config.access_token = ENV['BC_ACCESS_TOKEN'] +end + +@order = Bigcommerce::Order.find(109) + +# List order taxes +@order_taxes = Bigcommerce::OrderTax.all(@order.id) +puts @order_taxes + +# Get an order tax +@order_tax = @order_taxes[0] +puts Bigcommerce::OrderTax.find(@order.id, @order_tax.id) diff --git a/examples/orders/shipment.rb b/examples/orders/shipment.rb new file mode 100644 index 0000000..db4ec51 --- /dev/null +++ b/examples/orders/shipment.rb @@ -0,0 +1,57 @@ +require 'bigcommerce' + +Bigcommerce.configure do |config| + config.store_hash = ENV['BC_STORE_HASH'] + config.client_id = ENV['BC_CLIENT_ID'] + config.access_token = ENV['BC_ACCESS_TOKEN'] +end + +@order = Bigcommerce::Order.all[0] + +# Create a shipment +@order_product = Bigcommerce::OrderProduct.all(@order.id)[0] + +@order_address = Bigcommerce::OrderShippingAddress.all(@order.id)[0] + +@shipment = Bigcommerce::Shipment.create( + @order.id, + tracking_number: 'ups12345', + comments: 'Notes about the shipment', + order_address_id: @order_address.id, + items: [ + { + order_product_id: @order_product.id, + quantity: 1 + } + ] +) +puts @shipment + +# List shipments +@shipments = Bigcommerce::Shipment.all(@order.id) +puts @shipments + +# Get a shipment +@shipment = @shipments[0] +puts Bigcommerce::Shipment.find(@order.id, @shipment.id) + +# Get a count of shipments +puts Bigcommerce::Shipment.count(@order.id) + +# Get a count of all shipments for all orders +puts Bigcommerce::Shipment.count_all + +# Update a shipment +puts Bigcommerce::Shipment.update( + @order.id, + @shipment.id, + tracking_number: 'fedex1245', + comments: 'Notes about the shipment', + order_address_id: @order_address.id +) + +# Delete a shipment +puts Bigcommerce::Shipment.destroy(@order.id, @shipment.id) + +# Delete multiple shipments +# puts Bigcommerce::Shipment.destroy_all(@order.id) diff --git a/examples/payments/payment_method.rb b/examples/payments/payment_method.rb new file mode 100644 index 0000000..a4d3dbc --- /dev/null +++ b/examples/payments/payment_method.rb @@ -0,0 +1,10 @@ +require 'bigcommerce' + +Bigcommerce.configure do |config| + config.store_hash = ENV['BC_STORE_HASH'] + config.client_id = ENV['BC_CLIENT_ID'] + config.access_token = ENV['BC_ACCESS_TOKEN'] +end + +# List payment methods +puts Bigcommerce::PaymentMethod.all diff --git a/examples/products/brand.rb b/examples/products/brand.rb new file mode 100644 index 0000000..970a4e6 --- /dev/null +++ b/examples/products/brand.rb @@ -0,0 +1,36 @@ +require 'bigcommerce' +require 'securerandom' + +Bigcommerce.configure do |config| + config.store_hash = ENV['BC_STORE_HASH'] + config.client_id = ENV['BC_CLIENT_ID'] + config.access_token = ENV['BC_ACCESS_TOKEN'] +end + +# List brands +puts Bigcommerce::Brand.all(page: 2) + +# Get a brand +puts Bigcommerce::Brand.find(10) + +# Get a count of brands +puts Bigcommerce::Brand.count + +# Create a brand +@brand = Bigcommerce::Brand.create( + name: SecureRandom.hex, + page_title: "Title #{SecureRandom.hex}" +) +puts @brand + +# Update a brand +puts Bigcommerce::Brand.update( + @brand.id, + name: 'Foobar' +) + +# Delete a brand +puts Bigcommerce::Brand.destroy(@brand.id) + +# Delete all brands +# Bigcommerce::Brand.destroy_all diff --git a/examples/products/bulk_pricing_rule.rb b/examples/products/bulk_pricing_rule.rb new file mode 100644 index 0000000..96ce3c0 --- /dev/null +++ b/examples/products/bulk_pricing_rule.rb @@ -0,0 +1,47 @@ +require 'bigcommerce' +require 'securerandom' + +Bigcommerce.configure do |config| + config.store_hash = ENV['BC_STORE_HASH'] + config.client_id = ENV['BC_CLIENT_ID'] + config.access_token = ENV['BC_ACCESS_TOKEN'] +end + +@product = Bigcommerce::Product.all[0] + +# Create a products bulk pricing rule +@bulk_pricing_rule = Bigcommerce::BulkPricingRule.create( + @product.id, + min: 1, + max: 5, + type: 'price', + type_value: 2 +) +puts @bulk_pricing_rule + +# List bulk pricing rules +puts Bigcommerce::BulkPricingRule.all(@product.id) + +# Get a product bulk pricing rule +puts Bigcommerce::BulkPricingRule.find(@product.id, @bulk_pricing_rule.id) + +# Get a count of bulk pricing rules +puts Bigcommerce::BulkPricingRule.count(@product.id) + +# Get a count of all bulk pricing rules for all products +puts Bigcommerce::BulkPricingRule.count_all + +# Update a bulk pricing rule +puts Bigcommerce::BulkPricingRule.update( + @product.id, + @bulk_pricing_rule.id, + min: 2, + type: 'price', + type_value: 2 +) + +# Delete a product bulk pricing rule +puts Bigcommerce::BulkPricingRule.destroy(@product.id, @bulk_pricing_rule.id) + +# Delete multiple bulk pricing rules +# puts Bigcommerce::BulkPricingRule.destroy(@product.id) diff --git a/examples/products/category.rb b/examples/products/category.rb new file mode 100644 index 0000000..49a6315 --- /dev/null +++ b/examples/products/category.rb @@ -0,0 +1,37 @@ +require 'bigcommerce' +require 'securerandom' + +Bigcommerce.configure do |config| + config.store_hash = ENV['BC_STORE_HASH'] + config.client_id = ENV['BC_CLIENT_ID'] + config.access_token = ENV['BC_ACCESS_TOKEN'] +end + +# List categories +@categories = Bigcommerce::Category.all +puts @categories + +# Get a category +@category = @categories[0] +puts Bigcommerce::Category.find(@category.id) + +# Get a count of categories +puts Bigcommerce::Category.count + +# Create a category +@category = Bigcommerce::Category.create( + name: SecureRandom.hex +) +puts @category + +# Update a category +puts Bigcommerce::Category.update( + @category.id, + name: 'Foobar' +) + +# Delete a category +puts Bigcommerce::Category.destroy(@category.id) + +# Delete all categories +# Bigcommerce::Category.destroy_all diff --git a/examples/products/configurable_field.rb b/examples/products/configurable_field.rb new file mode 100644 index 0000000..5c84971 --- /dev/null +++ b/examples/products/configurable_field.rb @@ -0,0 +1,29 @@ +require 'bigcommerce' + +Bigcommerce.configure do |config| + config.store_hash = ENV['BC_STORE_HASH'] + config.client_id = ENV['BC_CLIENT_ID'] + config.access_token = ENV['BC_ACCESS_TOKEN'] +end + +@product = Bigcommerce::Product.all[0] + +# List configurable fields +@configurable_fields = Bigcommerce::ConfigurableField.all(@product.id) +puts @configurable_fields + +# Get a configurable field +@configurable_field = @configurable_fields[0] +puts Bigcommerce::ConfigurableField.all(@product.id, @configurable_field.id) + +# Get a count of configurable fields +puts Bigcommerce::ConfigurableField.count(@product.id) + +# Get a count of all configurable fields for all products +puts Bigcommerce::ConfigurableField.count(@product.id) + +# Delete a configurable field +puts Bigcommerce::ConfigurableField.destroy(@product.id, @configurable_field.id) + +# Delete multiple configurable fields +# puts Bigcommerce::ConfigurableField.destroy_all(@product.id) diff --git a/examples/products/custom_field.rb b/examples/products/custom_field.rb new file mode 100644 index 0000000..dc6eb61 --- /dev/null +++ b/examples/products/custom_field.rb @@ -0,0 +1,44 @@ +require 'bigcommerce' +require 'securerandom' + +Bigcommerce.configure do |config| + config.store_hash = ENV['BC_STORE_HASH'] + config.client_id = ENV['BC_CLIENT_ID'] + config.access_token = ENV['BC_ACCESS_TOKEN'] +end + +@product = Bigcommerce::Product.all[0] + +# Create a custom field +@custom_field = Bigcommerce::CustomField.create( + @product.id, + name: SecureRandom.hex, + text: SecureRandom.hex +) +puts @custom_field + +# List custom fields +puts Bigcommerce::CustomField.all(@product.id) + +# Get a custom field +puts Bigcommerce::CustomField.find(@product.id, @custom_field.id) + +# Get a count of custom fields +puts Bigcommerce::CustomField.count(@product.id) + +# Get a count of custom fields for all products +puts Bigcommerce::CustomField.count_all + +# Update a custom field +puts Bigcommerce::CustomField.update( + @product.id, + @custom_field.id, + name: ':)', + text: ':)' +) + +# Delete a custom field +puts Bigcommerce::CustomField.destroy(@product.id, @custom_field.id) + +# Delete multiple custom fields +# puts Bigcommerce::CustomField.destroy_all(@product.id) diff --git a/examples/products/google_product_search_mapping.rb b/examples/products/google_product_search_mapping.rb new file mode 100644 index 0000000..99cec74 --- /dev/null +++ b/examples/products/google_product_search_mapping.rb @@ -0,0 +1,12 @@ +require 'bigcommerce' + +Bigcommerce.configure do |config| + config.store_hash = ENV['BC_STORE_HASH'] + config.client_id = ENV['BC_CLIENT_ID'] + config.access_token = ENV['BC_ACCESS_TOKEN'] +end + +@product = Bigcommerce::Product.all[0] + +# List Google product search mappings +puts Bigcommerce::GoogleProductSearchMapping.all(@product.id) diff --git a/examples/products/option.rb b/examples/products/option.rb new file mode 100644 index 0000000..2103b86 --- /dev/null +++ b/examples/products/option.rb @@ -0,0 +1,37 @@ +require 'bigcommerce' +require 'securerandom' + +Bigcommerce.configure do |config| + config.store_hash = ENV['BC_STORE_HASH'] + config.client_id = ENV['BC_CLIENT_ID'] + config.access_token = ENV['BC_ACCESS_TOKEN'] +end + +# Create an option +@option = Bigcommerce::Option.create( + name: SecureRandom.hex, + type: 'CS' +) +puts @option + +# List options +puts Bigcommerce::Option.all + +# Get an option +puts Bigcommerce::Option.find(@option.id) + +# Get a count of options +puts Bigcommerce::Option.count + +# Update an option +puts Bigcommerce::Option.update( + @option.id, + name: ':)', + type: 'CS' +) + +# Delete an option +puts Bigcommerce::Option.destroy(@option.id) + +# Delete all options +# Bigcommerce::Option.destroy_all diff --git a/examples/products/option_set.rb b/examples/products/option_set.rb new file mode 100644 index 0000000..a8deed6 --- /dev/null +++ b/examples/products/option_set.rb @@ -0,0 +1,35 @@ +require 'bigcommerce' +require 'securerandom' + +Bigcommerce.configure do |config| + config.store_hash = ENV['BC_STORE_HASH'] + config.client_id = ENV['BC_CLIENT_ID'] + config.access_token = ENV['BC_ACCESS_TOKEN'] +end + +# Create an option set +@option_set = Bigcommerce::OptionSet.create( + name: SecureRandom.hex +) +puts @option_set + +# List option sets +puts Bigcommerce::OptionSet.all + +# Get an option set +puts Bigcommerce::OptionSet.find(@option_set.id) + +# Get a count of option sets +puts Bigcommerce::OptionSet.count + +# Update an option set +puts Bigcommerce::OptionSet.update( + @option_set.id, + name: ':)' +) + +# Delete an option set +puts Bigcommerce::OptionSet.destroy(@option_set.id) + +# Delete all option sets +# Bigcommerce::OptionSet.destroy_all diff --git a/examples/products/option_set_option.rb b/examples/products/option_set_option.rb new file mode 100644 index 0000000..c73a2bd --- /dev/null +++ b/examples/products/option_set_option.rb @@ -0,0 +1,50 @@ +require 'bigcommerce' +require 'securerandom' + +Bigcommerce.configure do |config| + config.store_hash = ENV['BC_STORE_HASH'] + config.client_id = ENV['BC_CLIENT_ID'] + config.access_token = ENV['BC_ACCESS_TOKEN'] +end + +@option_set = Bigcommerce::OptionSet.create( + name: SecureRandom.hex +) + +@option = Bigcommerce::Option.create( + name: SecureRandom.hex, + type: 'CS' +) + +# Create an option set option +@option_set_option = Bigcommerce::OptionSetOption.create( + @option_set.id, + option_id: @option.id, + display_name: SecureRandom.hex, + sort_order: 1, + is_required: true +) +puts @option_set_option + +# List option set options +puts Bigcommerce::OptionSetOption.all(@option_set.id) + +puts Bigcommerce::OptionSetOption.count(@option_set.id) + +# Get an option set option +puts Bigcommerce::OptionSetOption.find(@option_set.id, @option_set_option.id) + +# Update an option set option +puts Bigcommerce::OptionSetOption.update( + @option_set.id, + @option_set_option.id, + display_name: 'Pick a color...', + sort_order: 2, + is_required: false +) + +# Delete an option set option +puts Bigcommerce::OptionSetOption.destroy(@option_set.id, @option_set_option.id) + +# Delete multiple option set options +# puts Bigcommerce::OptionSetOption.destroy_all(@option_set.id) diff --git a/examples/products/option_value.rb b/examples/products/option_value.rb new file mode 100644 index 0000000..ad23908 --- /dev/null +++ b/examples/products/option_value.rb @@ -0,0 +1,43 @@ +require 'bigcommerce' +require 'securerandom' + +Bigcommerce.configure do |config| + config.store_hash = ENV['BC_STORE_HASH'] + config.client_id = ENV['BC_CLIENT_ID'] + config.access_token = ENV['BC_ACCESS_TOKEN'] +end + +@option = Bigcommerce::Option.create( + name: SecureRandom.hex, + type: 'CS' +) + +# Create an option value +@option_value = Bigcommerce::OptionValue.create( + @option.id, + label: SecureRandom.hex, + sort_order: 0, + value: '#FFFFFF' +) +puts @option_value + +# List option values +puts Bigcommerce::OptionValue.all(@option.id) + +# Get an option value +puts Bigcommerce::OptionValue.find(@option.id, @option_value.id) + +# Update an option value +puts Bigcommerce::OptionValue.update( + @option.id, + @option_value.id, + label: SecureRandom.hex, + sort_order: 0, + value: '#000000' +) + +# Delete an option value +puts Bigcommerce::OptionValue.destroy(@option.id, @option_value.id) + +# Delete multiple option values +# puts Bigcommerce::OptionValue.destroy_all(@option.id) diff --git a/examples/products/product.rb b/examples/products/product.rb new file mode 100644 index 0000000..223fb0c --- /dev/null +++ b/examples/products/product.rb @@ -0,0 +1,44 @@ +require 'bigcommerce' +require 'securerandom' + +Bigcommerce.configure do |config| + config.store_hash = ENV['BC_STORE_HASH'] + config.client_id = ENV['BC_CLIENT_ID'] + config.access_token = ENV['BC_ACCESS_TOKEN'] +end + +# List products +@products = Bigcommerce::Product.all +puts @products + +# Get a product +@product = @products[0] +puts Bigcommerce::Product.find(@product.id) + +# Get products count +puts Bigcommerce::Product.count + +# Create a product +@category = Bigcommerce::Category.all[0] +@product = Bigcommerce::Product.create( + name: SecureRandom.hex, + type: 'physical', + description: SecureRandom.hex, + price: '19.95', + categories: [@category.id], + availability: 'available', + weight: '0.5' +) +puts @product + +# Update a product +puts Bigcommerce::Product.update( + @product.id, + custom_url: '/foo-bar/' +) + +# Delete a product +puts Bigcommerce::Product.destroy(@product.id) + +# Delete all products +# puts Bigcommerce::Product.destroy_all diff --git a/examples/products/product_image.rb b/examples/products/product_image.rb new file mode 100644 index 0000000..7c6d6cc --- /dev/null +++ b/examples/products/product_image.rb @@ -0,0 +1,42 @@ +require 'bigcommerce' + +Bigcommerce.configure do |config| + config.store_hash = ENV['BC_STORE_HASH'] + config.client_id = ENV['BC_CLIENT_ID'] + config.access_token = ENV['BC_ACCESS_TOKEN'] +end + +@product = Bigcommerce::Product.all[0] + +# List product images +@product_images = Bigcommerce::ProductImage.all(@product.id) +puts @product_images + +# Get a count of product images +puts Bigcommerce::ProductImage.count(@product.id) + +# Get a count of all product images for all products +puts Bigcommerce::ProductImage.count_all + +# Create a product image +@product_image = Bigcommerce::ProductImage.create( + @product.id, + image_file: 'http://i.imgur.com/Z5aV28x.gif' +) +puts @product_image + +# Get a product image +puts Bigcommerce::ProductImage.find(@product.id, @product_image.id) + +# Update a product image +puts Bigcommerce::ProductImage.update( + @product.id, + @product_image.id, + image_file: 'http://i.imgur.com/4Dl6Y9d.gif' +) + +# Delete a product image +puts Bigcommerce::ProductImage.destroy(@product.id, @product_image.id) + +# Delete all product images +# puts Bigcommerce::ProductImage.destroy_all(@product.id) diff --git a/examples/products/product_option.rb b/examples/products/product_option.rb new file mode 100644 index 0000000..b890404 --- /dev/null +++ b/examples/products/product_option.rb @@ -0,0 +1,17 @@ +require 'bigcommerce' + +Bigcommerce.configure do |config| + config.store_hash = ENV['BC_STORE_HASH'] + config.client_id = ENV['BC_CLIENT_ID'] + config.access_token = ENV['BC_ACCESS_TOKEN'] +end + +@product = Bigcommerce::Product.all[0] + +# List product options +@product_options = Bigcommerce::ProductOption.all(@product.id) +puts @product_options + +# Get a product option +@product_option = @product_options[0] +puts Bigcommerce::ProductOption.find(@product.id, @product_option.id) diff --git a/examples/products/product_review.rb b/examples/products/product_review.rb new file mode 100644 index 0000000..b06c9d9 --- /dev/null +++ b/examples/products/product_review.rb @@ -0,0 +1,12 @@ +require 'bigcommerce' + +Bigcommerce.configure do |config| + config.store_hash = ENV['BC_STORE_HASH'] + config.client_id = ENV['BC_CLIENT_ID'] + config.access_token = ENV['BC_ACCESS_TOKEN'] +end + +@product = Bigcommerce::Product.all[0] + +# List product reviews +puts Bigcommerce::ProductReview.all(@product.id) diff --git a/examples/products/product_rule.rb b/examples/products/product_rule.rb new file mode 100644 index 0000000..d41f256 --- /dev/null +++ b/examples/products/product_rule.rb @@ -0,0 +1,54 @@ +require 'bigcommerce' + +Bigcommerce.configure do |config| + config.store_hash = ENV['BC_STORE_HASH'] + config.client_id = ENV['BC_CLIENT_ID'] + config.access_token = ENV['BC_ACCESS_TOKEN'] +end + +@product = Bigcommerce::Product.all[0] + +# List product rules +@product_rules = Bigcommerce::ProductRule.all(@product.id) +puts @product_rules + +# Get a count of product rules +puts Bigcommerce::ProductRule.count(@product.id) + +# Get a count of all product rules for all products +puts Bigcommerce::ProductRule.count_all + +# Create a product rule +@product_rule = Bigcommerce::ProductRule.create( + @product.id, + conditions: [ + { + product_option_id: 95, + option_value_id: 13, + sku_id: nil + } + ] +) +puts @product_rule + +# Get a product rule +puts Bigcommerce::ProductRule.find(@product.id, @product_rule.id) + +# Update a product rule +puts Bigcommerce::ProductRule.update( + @product.id, + @product_rule.id, + conditions: [ + { + product_option_id: 95, + option_value_id: 12, + sku_id: nil + } + ] +) + +# Delete a product rule +puts Bigcommerce::ProductRule.destroy(@product.id, @product_rule.id) + +# Delete all product rules +# puts Bigcommerce::ProductRule.destroy_all(@product.id) diff --git a/examples/products/product_video.rb b/examples/products/product_video.rb new file mode 100644 index 0000000..6e3092e --- /dev/null +++ b/examples/products/product_video.rb @@ -0,0 +1,45 @@ +require 'bigcommerce' + +Bigcommerce.configure do |config| + config.store_hash = ENV['BC_STORE_HASH'] + config.client_id = ENV['BC_CLIENT_ID'] + config.access_token = ENV['BC_ACCESS_TOKEN'] +end + +@product = Bigcommerce::Product.all[0] + +# Create a product video +@product_video = Bigcommerce::ProductVideo.create( + @product.id, + url: 'https://www.youtube.com/watch?v=T9RFb8xXZlk' +) +puts @product_video + +# List product videos +@product_videos = Bigcommerce::ProductVideo.all(@product.id) +puts @product_videos + +# Get a count of product videos +puts Bigcommerce::ProductVideo.count(@product.id) + +# Get a count of all product videos for all products +puts Bigcommerce::ProductVideo.count_all + +# Get a product video +puts Bigcommerce::ProductVideo.find(@product.id, @product_video.id) + +# Update a product video +# TODO +# puts Bigcommerce::ProductVideo.update( +# @product.id, +# @product_video.id, +# url: 'https://www.youtube.com/watch?v=LXgTp40Y3zo' +# ) + +# Delete a product video +# TODO +# puts Bigcommerce::ProductVideo.destroy(@product.id, product_video.id) + +# Delete all product videos +# TODO +# puts Bigcommerce::ProductVideo.destroy_all(@product.id) diff --git a/examples/products/sku.rb b/examples/products/sku.rb new file mode 100644 index 0000000..65e1ff6 --- /dev/null +++ b/examples/products/sku.rb @@ -0,0 +1,48 @@ +require 'bigcommerce' +require 'securerandom' + +Bigcommerce.configure do |config| + config.store_hash = ENV['BC_STORE_HASH'] + config.client_id = ENV['BC_CLIENT_ID'] + config.access_token = ENV['BC_ACCESS_TOKEN'] +end + +@product = Bigcommerce::Product.all[0] + +# Create a product sku +@sku = Bigcommerce::Sku.create( + @product.id, + sku: SecureRandom.hex, + options: [ + product_option_id: 95, + option_value_id: 10 + ] +) +puts @sku + +# List product skus +@skus = Bigcommerce::Sku.all(@product.id) +puts @skus + +# Get a count of product skus +puts Bigcommerce::Sku.count + +# Get a product sku +puts Bigcommerce::Sku.find(@product.id, @sku.id) + +# Update a product sku +puts Bigcommerce::Sku.update( + @product.id, + @sku.id, + sku: SecureRandom.hex, + options: [ + product_option_id: 95, + option_value_id: 7 + ] +) + +# Delete a product image +puts Bigcommerce::Sku.destroy(@product.id, @sku.id) + +# Delete all product skus +# puts Bigcommerce::Sku.destroy_all(@product.id) diff --git a/examples/shipping/shipping_method.rb b/examples/shipping/shipping_method.rb new file mode 100644 index 0000000..ff564c3 --- /dev/null +++ b/examples/shipping/shipping_method.rb @@ -0,0 +1,13 @@ +require 'bigcommerce' + +Bigcommerce.configure do |config| + config.store_hash = ENV['BC_STORE_HASH'] + config.client_id = ENV['BC_CLIENT_ID'] + config.access_token = ENV['BC_ACCESS_TOKEN'] +end + +# List shipping methods +puts Bigcommerce::ShippingMethod.all + +# Get a shipping method +puts Bigcommerce::ShippingMethod.find(1) diff --git a/examples/store/store_info.rb b/examples/store/store_info.rb new file mode 100644 index 0000000..a9d6b83 --- /dev/null +++ b/examples/store/store_info.rb @@ -0,0 +1,10 @@ +require 'bigcommerce' + +Bigcommerce.configure do |config| + config.store_hash = ENV['BC_STORE_HASH'] + config.client_id = ENV['BC_CLIENT_ID'] + config.access_token = ENV['BC_ACCESS_TOKEN'] +end + +# Get store information +puts Bigcommerce::StoreInfo.info diff --git a/examples/system/time.rb b/examples/system/time.rb new file mode 100644 index 0000000..6a574cf --- /dev/null +++ b/examples/system/time.rb @@ -0,0 +1,10 @@ +require 'bigcommerce' + +Bigcommerce.configure do |config| + config.store_hash = ENV['BC_STORE_HASH'] + config.client_id = ENV['BC_CLIENT_ID'] + config.access_token = ENV['BC_ACCESS_TOKEN'] +end + +# Get current server time +puts Bigcommerce::System.time diff --git a/examples/tax/tax_class.rb b/examples/tax/tax_class.rb new file mode 100644 index 0000000..b080483 --- /dev/null +++ b/examples/tax/tax_class.rb @@ -0,0 +1,13 @@ +require 'bigcommerce' + +Bigcommerce.configure do |config| + config.store_hash = ENV['BC_STORE_HASH'] + config.client_id = ENV['BC_CLIENT_ID'] + config.access_token = ENV['BC_ACCESS_TOKEN'] +end + +# List tax classes +puts Bigcommerce::TaxClass.all + +# Get a tax classes +puts Bigcommerce::TaxClass.find(1) diff --git a/examples/webhooks/webhook.rb b/examples/webhooks/webhook.rb new file mode 100644 index 0000000..264513a --- /dev/null +++ b/examples/webhooks/webhook.rb @@ -0,0 +1,29 @@ +require 'bigcommerce' + +Bigcommerce.configure do |config| + config.store_hash = ENV['BC_STORE_HASH'] + config.client_id = ENV['BC_CLIENT_ID'] + config.access_token = ENV['BC_ACCESS_TOKEN'] +end + +# List all webhooks +puts Bigcommerce::Webhook.all + +# Get a webhook +puts Bigcommerce::Webhook.find(1) + +# Create a webhook +@webhook = Bigcommerce::Webhook.create( + scope: 'store/order/*', + destination: 'https://app.example.com/orders' +) + +# Update a webhook +puts Bigcommerce::Webhook.update( + @webhook.id, + scope: 'store/order/*', + destination: 'https://app.example.com/products' +) + +# Delete a webhook +puts Bigcommerce::Webhook.destroy(@webhook.id) diff --git a/lib/big_commerce.rb b/lib/big_commerce.rb deleted file mode 100644 index 2d11a0a..0000000 --- a/lib/big_commerce.rb +++ /dev/null @@ -1 +0,0 @@ -raise "'big_commerce' (BigCommerce::Api) is no longer supported. Please require 'bigcommerce' (Bigcommerce::Api)" diff --git a/lib/bigcommerce.rb b/lib/bigcommerce.rb index 391f493..62767ab 100644 --- a/lib/bigcommerce.rb +++ b/lib/bigcommerce.rb @@ -1,9 +1,51 @@ -require "cgi" -require "json" -require 'rest-client' -require "uri" -require 'bigcommerce/api' -require 'bigcommerce/connection' +require 'hashie' +require 'faraday_middleware' require 'bigcommerce/version' -require 'bigcommerce/resource' -require 'bigcommerce/product' +require 'bigcommerce/middleware/auth' +require 'bigcommerce/middleware/http_exception' +require 'bigcommerce/resources/resource' + +module Bigcommerce + resources = File.join(File.dirname(__FILE__), 'bigcommerce', 'resources', '**', '*.rb') + Dir.glob(resources, &method(:require)) + + DEFAULTS = { + base_url: 'https://api.bigcommerce.com' + } + + HEADERS = { + 'accept' => 'application/json', + 'content-type' => 'application/json', + 'user-agent' => 'bigcommerce-api-ruby' + } + + class << self + attr_reader :api + attr_accessor :api_limit + + def configure + config = Hashie::Mash.new + yield(config) + ssl_options = config.ssl if config.auth == 'legacy' + + @api = Faraday.new(url: build_url(config), ssl: ssl_options) do |conn| + conn.request :json + conn.headers = HEADERS + if config.auth == 'legacy' + conn.use Faraday::Request::BasicAuthentication, config.username, config.api_key + else + conn.use Bigcommerce::Middleware::Auth, config + end + conn.use Bigcommerce::Middleware::HttpException + conn.adapter Faraday.default_adapter + end + end + + def build_url(config) + return config.url if config.auth == 'legacy' + + base = ENV['BC_API_ENDPOINT'].nil? ? DEFAULTS[:base_url] : ENV['BC_API_ENDPOINT'] + "#{base}/stores/#{config.store_hash}/v2" + end + end +end diff --git a/lib/bigcommerce/api.rb b/lib/bigcommerce/api.rb deleted file mode 100644 index 9305b5e..0000000 --- a/lib/bigcommerce/api.rb +++ /dev/null @@ -1,477 +0,0 @@ -require 'date' -require 'ostruct' - -module Bigcommerce - class Api - - attr_reader :page - - def initialize(configuration={}) - @connection = Connection.new(configuration) - end - - def connection - @connection - end - - def store_url=(store_url) - @connection.store_url = store_url - end - - def username=(username) - @connection.username = username - end - - def api_key=(api_key) - @connection.api_key = api_key - end - - def verify_ssl=(verify) - @connection.verify_ssl = verify - end - - def ca_file=(path) - @connection.ca_file = path - end - - def to_rfc2822(datetime) - datetime.strftime("%a, %d %b %Y %H:%M:%S %z") - end - - def time - @connection.get '/time' - end - - def store_information - @connection.get '/store' - end - - def brands(options={}) - @connection.get("/brands", options) - end - - def brands_count - @connection.get '/brands/count' - end - - def brand(id) - @connection.get("/brands/#{id}", {}) - end - - def create_brands(options={}) - @connection.post("/brands", options) - end - - def update_brand(id, options={}) - @connection.put("/brands/#{id}", options) - end - - def delete_brand(id) - @connection.delete("/brands/#{id}") - end - - def coupons(options={}) - @connection.get("/coupons", options) - end - - def create_coupons(options={}) - @connection.post("/coupons", options) - end - - def update_coupon(id, options={}) - @connection.put("/coupons/#{id}", options) - end - - def categories(options={}) - @connection.get("/categories", options) - end - - def categories_count - @connection.get '/categories/count' - end - - def category(id) - @connection.get("/categories/#{id}", {}) - end - - def create_categories(options={}) - @connection.post("/categories", options) - end - - def update_category(id, options={}) - @connection.put("/categories/#{id}", options) - end - - def delete_category(id) - @connection.delete("/categories/#{id}") - end - - def countries(options={}) - @connection.get("/countries", options) - end - - def country(id) - @connection.get("/countries/#{id}", {}) - end - - def countries_states(options={}) - @connection.get("/countries/states", options) - end - - def countries_state(id, options={}) - @connection.get("/countries/#{id}/states", {}) - end - - def customers(options = {}) - @connection.get("/customers", options) - end - - def customer(id) - @connection.get('/customers/' + id.to_s, {}) - end - - def customer_addresses(id, options = {}) - @connection.get("/customers/#{id}/addresses", options) - end - - def customer_address(customer_id, address_id) - @connection.get("/customers/#{customer_id}/addresses/#{address_id}",{}) - end - - def options(options={}) - @connection.get("/options", options) - end - - def options_count - @connection.get '/options/count' - end - - def option(id) - @connection.get("/options/#{id}",{}) - end - - def create_option(options={}) - @connection.post("/options", options) - end - - def update_option(id, options={}) - @connection.put("/options/#{id}", options) - end - - def delete_option(id) - @connection.delete("/options/#{id}") - end - - def options_values(options={}) - @connection.get("/options/values", options) - end - - def options_value(id, options={}) - @connection.get("/options/#{id}/values", options) - end - - def create_options_values(options_id, options={}) - @connection.post("/options/#{options_id}/values", options) - end - - def update_options_value(options_id, values_id, options={}) - @connection.put("/options/#{options_id}/values/#{values_id}", options) - end - - def optionsets(options={}) - @connection.get("/optionsets", options) - end - - def optionsets_count - @connection.get '/optionsets/count' - end - - def optionset(id) - @connection.get("/optionsets/#{id}", {}) - end - - def create_optionset(options={}) - @connection.post("/optionsets", options) - end - - def update_optionset(id, options={}) - @connection.put("/optionsets/#{id}", options) - end - - def delete_optionset(id) - @connection.delete("/optionsets/#{id}") - end - - def optionsets_options(options={}) - @connection.get("/optionsets/options", options) - end - - def optionset_options(id) - @connection.get("/optionsets/#{id}/options", {}) - end - - def optionsets_option(id) - @connection.get("/optionsets/options/#{id}", {}) - end - - def create_optionset_option(id, options={}) - @connection.post("/optionsets/#{id}/options", options) - end - - def update_optionset_option(optionset_id, option_id, options={}) - @connection.put("/optionsets/#{optionset_id}/options/#{option_id}", options) - end - - def orders(options={}) - @connection.get("/orders", options) - end - - def orders_by_date(date, options={}) - if date.is_a?(String) - date = DateTime.parse(date) - end - @connection.get('/orders', options.merge!(:min_date_created => to_rfc2822(date))) - end - - def orders_modified_since(date) - @connection.get('/orders', {}, {'If-Modified-Since' => to_rfc2822(date)}) - end - - def order(id,options={}) - @connection.get("/orders/#{id}", options) - end - - def update_order(id,options={}) - @connection.put("/orders/#{id}", options) - end - - def orders_count(options={}) - @connection.get("/orders/count", options) - end - - def orders_coupons(id,options={}) - @connection.get("/orders/#{id}/coupons", options) - end - - def orders_coupon(order_id,coupon_id,options={}) - @connection.get("/orders/#{order_id}/coupons/#{coupon_id}", options) - end - - def orders_products(id,options={}) - @connection.get("/orders/#{id}/products", options) - end - - def orders_product(order_id,product_id,options={}) - @connection.get("/orders/#{order_id}/products/#{product_id}", options) - end - - def orders_shipments(id,options={}) - @connection.get("/orders/#{id}/shipments", options) - end - - def create_orders_shipments(id, options={}) - @connection.post("/orders/#{id}/shipments", options) - end - - def orders_shipment(order_id,shipment_id,options={}) - @connection.get("/orders/#{order_id}/shipments/#{shipment_id}", options) - end - - def update_orders_shipment(order_id,shipment_id,options={}) - @connection.put("/orders/#{order_id}/shipments/#{shipment_id}", options) - end - - def orders_shippingaddresses(id,options={}) - @connection.get("/orders/#{id}/shippingaddresses", options) - end - - def orders_shippingaddress(order_id,shippingaddress_id,options={}) - @connection.get("/orders/#{order_id}/shippingaddresses/#{shippingaddress_id}", options) - end - - def orderstatuses(options={}) - @connection.get("/orderstatuses", options) - end - - def orderstatus(id,options={}) - @connection.get("/orderstatuses/#{id}", options) - end - - def products(options={}) - @connection.get("/products", options) - end - - def products_count(options={}) - @connection.get('/products/count', options) - end - - def product(id,options={}) - @connection.get("/products/#{id}", options) - end - - def create_products(options={}) - @connection.post('/products', options) - end - - def update_products(id, options={}) - @connection.put("/products/#{id}", options) - end - - def delete_products(id) - @connection.delete("/products/#{id}") - end - - def products_discountrules(options={}) - @connection.get("/products/discountrules", options) - end - - def product_discountrules(product_id, options={}) - @connection.get("/products/#{product_id}/discountrules", options) - end - - def products_discountrule(product_id, discountrule_id,options={}) - @connection.get("/products/#{product_id}/discountrules/#{discountrule_id}", options) - end - - def products_configurablefields(options={}) - @connection.get("/products/configurablefields", options) - end - - def product_configurablefields(product_id, options={}) - @connection.get("/products/#{product_id}/configurablefields", options) - end - - def products_configurablefield(product_id, configurable_field_id, options={}) - @connection.get("/products/#{product_id}/configurablefields/#{configurable_field_id}", options) - end - - def products_customfields(options={}) - @connection.get("/products/customfields", options) - end - - def product_customfields(product_id, options={}) - @connection.get("/products/#{product_id}/customfields", options) - end - - def create_product_customfield(product_id, options={}) - @connection.post("/products/#{product_id}/customfields", options) - end - - def update_product_customfield(product_id, custom_field_id, options={}) - @connection.put("/products/#{product_id}/customfields/#{custom_field_id}", options) - end - - def delete_product_customfield(product_id, custom_field_id) - @connection.delete("/products/#{product_id}/customfields/#{custom_field_id}") - end - - def delete_product_customfields(product_id) - @connection.delete("/products/#{product_id}/customfields") - end - - def products_customfield(product_id, custom_field_id, options={}) - @connection.get("/products/#{product_id}/customfields/#{custom_field_id}", options) - end - - def product_images(product_id, options={}) - @connection.get("/products/#{product_id}/images", options) - end - - def create_product_images(product_id, options={}) - @connection.post("/products/#{product_id}/images", options) - end - - def create_products_images(options={}) - @connection.post("/products/images", options) - end - - def products_image(product_id, image_id, options={}) - @connection.get("/products/#{product_id}/images/#{image_id}", options) - end - - def update_products_image(product_id,image_id,options={}) - @connection.put("/products/#{product_id}/images/#{image_id}", options) - end - - def product_options(product_id, options={}) - @connection.get("/products/#{product_id}/options", options) - end - - def products_option(product_id,option_id, options={}) - @connection.get("/products/#{product_id}/options/#{option_id}", options) - end - - def product_rules(product_id, options={}) - @connection.get("/products/#{product_id}/rules", options) - end - - def create_products_rules(options={}) - @connection.post("/products/rules", options) - end - - def products_rule(product_id,rule_id,options={}) - @connection.get("/products/#{product_id}/rules/#{rule_id}", options) - end - - def update_products_rule(product_id, rule_id, options={}) - @connection.put("/products/#{product_id}/rules/#{rule_id}", options) - end - - def product_skus(product_id, options={}) - @connection.get("/products/#{product_id}/skus", options) - end - - def create_products_skus(options={}) - @connection.post("/products/skus", options) - end - - def products_sku(product_id, sku_id, options={}) - @connection.get("/products/#{product_id}/skus/#{sku_id}", options) - end - - def update_products_sku(product_id, sku_id, options={}) - @connection.put("/products/#{product_id}/skus/#{sku_id}", options) - end - - def product_videos(product_id, options={}) - @connection.get("/products/#{product_id}/videos", options) - end - - def products_video(product_id, video_id, options={}) - @connection.get("/products/#{product_id}/videos/#{video_id}", options) - end - - def count(result) - result["count"] - end - - def collection(resource_path, options={}) - if (options["resource_class"]) - klass = options["resource_class"] - else - klass = Resource - end - Enumerator.new do |yielder| - count = -1 - if options[:starting_page] - @page = options[:starting_page] - else - @page = 1 - end - until count == 0 - buffer = @connection.get(resource_path, {page: page}) - count = buffer.count - buffer.each do |item| - yielder << klass.new(item, @connection) - p @connection.remaining_rate_limit - end - @page += 1 - end - end - end - - def resource(result) - result - end - end -end diff --git a/lib/bigcommerce/connection.rb b/lib/bigcommerce/connection.rb deleted file mode 100644 index 6096a06..0000000 --- a/lib/bigcommerce/connection.rb +++ /dev/null @@ -1,171 +0,0 @@ -module Bigcommerce - class Connection - attr_reader :configuration, :remaining_rate_limit - - def initialize(configuration) - @configuration = {} - configuration.each do |key, val| - send(key.to_s + "=", val) - end - end - - def store_hash=(store_hash) - @configuration[:store_hash] = store_hash - end - - def client_id=(client_id) - @configuration[:client_id] = client_id - end - - def access_token=(access_token) - @configuration[:access_token] = access_token - end - - def store_url=(store_url) - url = URI.parse(store_url) - @configuration[:store_url] = url.scheme + "://" + url.host - end - - def username=(username) - @configuration[:username] = username - end - - def api_key=(api_key) - @configuration[:api_key] = api_key - end - - def verify_peer=(verify) - @configuration[:verify_ssl] = verify - end - - def ssl_ca_file=(path) - @configuration.ssl_ca_file = path - end - - def ssl_client_key=(path,passphrase=nil) - if passphrase.nil? - @configuration.ssl_client_key = OpenSSL::PKey::RSA.new(File.read(path)) - else - @configuration.ssl_client_key = OpenSSL::PKey::RSA.new(File.read(path), passphrase) - end - end - - def ssl_client_cert=(path) - @configuration.client_cert = OpenSSL::X509::Certificate.new(File.read(path)) - end - - def get(path, options = {}, headers = {}) - request(:get, path, options, headers) - end - - def post(path, options = {}, headers = {}) - request(:post, path, options, headers) - end - - def put(path, options = {}, headers = {}) - request(:put, path, options, headers) - end - - def delete(path, options = {}, headers = {}) - request(:delete, path, options, headers) - end - - # Make a request to the bigcommerce API using either Legacy or OAuth - def request(method, path, options,headers={}) - if oauth? - request_oauth(method, path, options, headers) - else - request_legacy(method, path, options, headers) - end - end - - private - - def oauth? - @configuration[:store_hash] && @configuration[:client_id] && @configuration[:access_token] - end - - def request_oauth(method, path, options, headers={}) - uri = File.join((ENV['BC_API_ENDPOINT'] || 'https://api.bigcommerce.com'), '/stores', @configuration[:store_hash], '/v2', path) - - rest_client = RestClient::Resource.new uri.to_s, { - headers: headers.merge({ - 'X-Auth-Client' => @configuration[:client_id], - 'X-Auth-Token' => @configuration[:access_token], - :accept => :json, - :content_type => :json - }) - } - - response = case method - when :get then - rest_client.get :params => options - when :post then - rest_client.post(options.to_json) - when :put then - rest_client.put(options.to_json) - when :delete then - rest_client.delete - when :head then - rest_client.head - when :options then - rest_client.options - else - raise 'Unsupported method!' - end - - if (200..201) === response.code - JSON.parse response - elsif response.code == 204 - {} - end - end - - def request_legacy(method, path, options, headers={}) - resource_options = { - :user => @configuration[:username], - :password => @configuration[:api_key], - :headers => headers - } - - rest_client = RestClient::Resource.new "#{@configuration[:store_url]}/api/v2#{path}.json", resource_options - - if @configuration[:ssl_client_key] && @configuration[:ssl_client_cert] && @configuration[:ssl_ca_file] - rest_client = RestClient::Resource.new( - "#{@configuration[:store_url]}/api/v2#{path}.json", - :username => @configuration[:username], - :password => @configuration[:api_key], - :ssl_client_cert => @configuration[:ssl_client_cert], - :ssl_client_key => @configuration[:ssl_client_key], - :ssl_ca_file => @configuration[:ssl_ca_file], - :verify_ssl => @configuration[:verify_ssl] - ) - end - - response = case method - when :get then - rest_client.get :params => options, :accept => :json, :content_type => :json - when :post then - rest_client.post(options.to_json, :content_type => :json, :accept => :json) - when :put then - rest_client.put(options.to_json, :content_type => :json, :accept => :json) - when :delete then - rest_client.delete - when :head then - rest_client.head - when :options then - rest_client.options - else - raise 'Unsupported method!' - end - - @remaining_rate_limit = response.headers[:x_bc_apilimit_remaining] - if (200..201) === response.code - JSON.parse response - elsif response.code == 204 - {} - end - end - - end -end diff --git a/lib/bigcommerce/exception.rb b/lib/bigcommerce/exception.rb new file mode 100644 index 0000000..8a461d4 --- /dev/null +++ b/lib/bigcommerce/exception.rb @@ -0,0 +1,51 @@ +module Bigcommerce + class HttpError < StandardError + attr_accessor :response_headers + def initialize(headers) + @response_headers = headers + end + end + + class BadRequest < HttpError; end + class Unauthorized < HttpError; end + class Forbidden < HttpError; end + class NotFound < HttpError; end + class MethodNotAllowed < HttpError; end + class NotAccepted < HttpError; end + class TimeOut < HttpError; end + class ResourceConflict < HttpError; end + class TooManyRequests < HttpError; end + class InternalServerError < HttpError; end + class BadGateway < HttpError; end + class ServiceUnavailable < HttpError; end + class GatewayTimeout < HttpError; end + class BandwidthLimitExceeded < HttpError; end + + module HttpErrors + ERRORS = { + 400 => Bigcommerce::BadRequest, + 401 => Bigcommerce::Unauthorized, + 403 => Bigcommerce::Forbidden, + 404 => Bigcommerce::NotFound, + 405 => Bigcommerce::MethodNotAllowed, + 406 => Bigcommerce::NotAccepted, + 408 => Bigcommerce::TimeOut, + 409 => Bigcommerce::ResourceConflict, + 429 => Bigcommerce::TooManyRequests, + 500 => Bigcommerce::InternalServerError, + 502 => Bigcommerce::BadGateway, + 503 => Bigcommerce::ServiceUnavailable, + 504 => Bigcommerce::GatewayTimeout, + 509 => Bigcommerce::BandwidthLimitExceeded + } + + def throw_http_exception!(code, env) + return unless ERRORS.keys.include? code + error_hash = env.body.empty? ? {} : JSON.parse(env.body, symbolize_names: true) + unless env[:response_headers]['X-Retry-After'].nil? + error_hash[:retry_after] = env[:response_headers]['X-Retry-After'].to_i + end + fail ERRORS[code].new(error_hash), env.body + end + end +end diff --git a/lib/bigcommerce/middleware/auth.rb b/lib/bigcommerce/middleware/auth.rb new file mode 100644 index 0000000..27d66f3 --- /dev/null +++ b/lib/bigcommerce/middleware/auth.rb @@ -0,0 +1,16 @@ +module Bigcommerce + module Middleware + class Auth < Faraday::Middleware + def initialize(app, options = {}) + @app = app + @options = options + end + + def call(env) + env[:request_headers]['X-Auth-Client'] = @options[:client_id] + env[:request_headers]['X-Auth-Token'] = @options[:access_token] + @app.call env + end + end + end +end diff --git a/lib/bigcommerce/middleware/http_exception.rb b/lib/bigcommerce/middleware/http_exception.rb new file mode 100644 index 0000000..276d20a --- /dev/null +++ b/lib/bigcommerce/middleware/http_exception.rb @@ -0,0 +1,14 @@ +require 'bigcommerce/exception' + +module Bigcommerce + module Middleware + class HttpException < Faraday::Response::Middleware + include Bigcommerce::HttpErrors + + def on_complete(env) + throw_http_exception! env[:status].to_i, env + env + end + end + end +end diff --git a/lib/bigcommerce/product.rb b/lib/bigcommerce/product.rb deleted file mode 100644 index 03db17b..0000000 --- a/lib/bigcommerce/product.rb +++ /dev/null @@ -1,13 +0,0 @@ -module Bigcommerce - class Product < Resource - - # Here we memoize brand, so we can re-use it across different products - # Note we store this across the class - def brand - key = @hash["brand"]["resource"] - @@some_method ||= {} - @@some_method[key] ||= @connection.get(@hash["brand"]["resource"]) - end - - end -end diff --git a/lib/bigcommerce/request.rb b/lib/bigcommerce/request.rb new file mode 100644 index 0000000..8cceafd --- /dev/null +++ b/lib/bigcommerce/request.rb @@ -0,0 +1,89 @@ +require 'json' + +module Bigcommerce + class PathBuilder + attr_reader :uri + + def initialize(uri) + @uri = uri + end + + # This takes the @uri and inserts the keys to form a path. + # To start we make sure that for nil/numeric values, we wrap those into an + # array. We then scan the string for %d and %s to find the number of times + # we possibly need to insert keys into the URI. Next, we check the size of + # the keys array, if the keys size is less than the number of possible keys + # in the URI, we will remove the trailing %d or %s, then remove the + # trailing /. We then pass the keys into the uri to form the path. + # ex. foo/%d/bar/%d => foo/1/bar/2 + def build(keys = []) + keys = [] if keys.nil? + keys = [keys] if keys.is_a? Numeric + ids = uri.scan('%d').count + uri.scan('%s').count + str = ids > keys.size ? uri.chomp('%d').chomp('%s').chomp('/') : uri + (str % keys).chomp('/') + end + + def to_s + @uri + end + end + + class Request < Module + def initialize(uri) + @uri = uri + end + + def included(base) + base.extend ClassMethods + path_builder = PathBuilder.new @uri + base.define_singleton_method :path do + path_builder + end + end + + module ClassMethods + def get(path, params = nil) + response = raw_request(:get, path, params) + build_response_object response + end + + def delete(path) + response = raw_request(:delete, path) + response.body + end + + def post(path, params) + response = raw_request(:post, path, params) + build_response_object response + end + + def put(path, params) + response = raw_request(:put, path, params) + build_response_object response + end + + def raw_request(method, path, params = nil) + response = Bigcommerce.api.send(method, path.to_s, params) + Bigcommerce.api_limit = response.headers['X-BC-ApiLimit-Remaining'] + response + end + + private + + def build_response_object(response) + json = parse response.body + if json.is_a? Array + json.map { |obj| new obj } + else + new json + end + end + + def parse(json) + return [] if json.empty? + JSON.parse(json, symbolize_names: true) + end + end + end +end diff --git a/lib/bigcommerce/resource.rb b/lib/bigcommerce/resource.rb deleted file mode 100644 index 8af9a96..0000000 --- a/lib/bigcommerce/resource.rb +++ /dev/null @@ -1,50 +0,0 @@ -module Bigcommerce - class Resource - - def metaclass - class << self; self; end - end - - def initialize hash, connection - @connection = connection - @hash = hash - @hash.each do |key, value| - if (value.class == Hash) - self.resourceify(key, value) - end - end - @full_hash = @hash - end - - def [](key) - @hash[key] - end - - def []=(key,value) - @hash[key] = value - end - - def resourceify(name, data) - if (!self.respond_to?(name.to_sym)) - self.metaclass.send(:define_method, name) do - @connection.get data["resource"] - end - end - end - - def load(*sub_resources) - sub_resources.each do |sub_resource| - begin - @full_hash[sub_resource.to_s] = self.send(sub_resource) - rescue RuntimeError => e - puts e - end - end - end - - def to_json - @full_hash.to_json - end - - end -end diff --git a/lib/bigcommerce/resource_actions.rb b/lib/bigcommerce/resource_actions.rb new file mode 100644 index 0000000..95472d0 --- /dev/null +++ b/lib/bigcommerce/resource_actions.rb @@ -0,0 +1,51 @@ +module Bigcommerce + class ResourceActions < Module + attr_reader :options + + def initialize(options = {}) + @options = options + tap do |mod| + mod.define_singleton_method :_options do + mod.options + end + end + end + + def included(base) + base.send(:include, Request.new(options[:uri])) + base.extend(ClassMethods) + options[:disable_methods] ||= [] + methods = ClassMethods.public_instance_methods & options[:disable_methods] + methods.each { |name| base.send(:remove_method, name) } + end + + module ClassMethods + def all(params = {}) + get path.build, params + end + + def find(resource_id) + fail ArgumentError if resource_id.nil? + get path.build(resource_id) + end + + def create(params) + post path.build, params + end + + def update(resource_id, params) + fail ArgumentError if resource_id.nil? + put path.build(resource_id), params + end + + def destroy(resource_id) + fail ArgumentError if resource_id.nil? + delete path.build(resource_id) + end + + def destroy_all + delete path.build + end + end + end +end diff --git a/lib/bigcommerce/resources/content/blog_post.rb b/lib/bigcommerce/resources/content/blog_post.rb new file mode 100644 index 0000000..b4a33e7 --- /dev/null +++ b/lib/bigcommerce/resources/content/blog_post.rb @@ -0,0 +1,31 @@ +# Blog Post +# Content entries in the store's blog. +# https://developer.bigcommerce.com/api/stores/v2/blog/posts + +module Bigcommerce + class BlogPost < Resource + include Bigcommerce::ResourceActions.new uri: 'blog/posts/%d' + + property :id + property :url + property :count + property :preview_url + property :body + property :tags + property :summary + property :title + property :content + property :author + property :author_url + property :is_published + property :published_date + property :published_at + property :meta_description + property :meta_keywords + property :thumbnail_path + + def self.count + get 'blog/posts/count' + end + end +end diff --git a/lib/bigcommerce/resources/content/blog_tag.rb b/lib/bigcommerce/resources/content/blog_tag.rb new file mode 100644 index 0000000..737b7f6 --- /dev/null +++ b/lib/bigcommerce/resources/content/blog_tag.rb @@ -0,0 +1,17 @@ +# Blog Tag +# Index of tags used on the store's blog. +# https://developer.bigcommerce.com/api/stores/v2/blog/tags + +module Bigcommerce + class BlogTag < Resource + include Bigcommerce::Request.new 'blog/tags' + + property :id + property :tag + property :post_ids + + def self.all + get path.build + end + end +end diff --git a/lib/bigcommerce/resources/content/redirect.rb b/lib/bigcommerce/resources/content/redirect.rb new file mode 100644 index 0000000..507abe7 --- /dev/null +++ b/lib/bigcommerce/resources/content/redirect.rb @@ -0,0 +1,21 @@ +# Redirect +# Redirects are used to create custom URL paths that map to resources on the +# storefront (such as products, categories, brands, etc.) or manually defined +# static URLs. +# https://developer.bigcommerce.com/api/stores/v2/redirects + +module Bigcommerce + class Redirect < Resource + include Bigcommerce::ResourceActions.new uri: 'redirects/%d' + + property :id + property :count + property :path + property :forward + property :url + + def self.count + get 'redirects/count' + end + end +end diff --git a/lib/bigcommerce/resources/customers/customer.rb b/lib/bigcommerce/resources/customers/customer.rb new file mode 100644 index 0000000..5618069 --- /dev/null +++ b/lib/bigcommerce/resources/customers/customer.rb @@ -0,0 +1,30 @@ +# Customer +# Identity and account details for customers shopping at a Bigcommerce store. +# https://developer.bigcommerce.com/api/stores/v2/customers + +module Bigcommerce + class Customer < Resource + include Bigcommerce::ResourceActions.new uri: 'customers/%d' + + property :id + property :_authentication + property :count + property :company + property :first_name + property :last_name + property :email + property :phone + property :date_created + property :date_modified + property :store_credit + property :registration_ip_address + property :customer_group_id + property :notes + property :addresses + property :tax_exempt_category + + def self.count + get 'customers/count' + end + end +end diff --git a/lib/bigcommerce/resources/customers/customer_address.rb b/lib/bigcommerce/resources/customers/customer_address.rb new file mode 100644 index 0000000..181e21f --- /dev/null +++ b/lib/bigcommerce/resources/customers/customer_address.rb @@ -0,0 +1,34 @@ +# Customer Address +# Postal addresses belonging to a customer. +# https://developer.bigcommerce.com/api/stores/v2/customers/addresses + +module Bigcommerce + class CustomerAddress < Resource + include Bigcommerce::SubresourceActions.new uri: 'customers/%d/addresses/%d' + + property :id + property :customer_id + property :first_name + property :address_type + property :count + property :last_name + property :company + property :street_1 + property :street_2 + property :city + property :state + property :zip + property :country + property :country_iso2 + property :phone + property :adderss_type + + def self.count_all + get 'customers/addresses/count' + end + + def self.count(customer_id) + get "customers/#{customer_id}/addresses/count" + end + end +end diff --git a/lib/bigcommerce/resources/customers/customer_group.rb b/lib/bigcommerce/resources/customers/customer_group.rb new file mode 100644 index 0000000..dbbe9e9 --- /dev/null +++ b/lib/bigcommerce/resources/customers/customer_group.rb @@ -0,0 +1,21 @@ +# Customer Group +# Groups of customers who share the same level of access and discounts +# at a store. +# https://developer.bigcommerce.com/api/stores/v2/customer_groups + +module Bigcommerce + class CustomerGroup < Resource + include Bigcommerce::ResourceActions.new uri: 'customer_groups/%d' + + property :id + property :name + property :count + property :is_default + property :category_access + property :discount_rules + + def self.count + get 'customer_groups/count' + end + end +end diff --git a/lib/bigcommerce/resources/geography/country.rb b/lib/bigcommerce/resources/geography/country.rb new file mode 100644 index 0000000..155de61 --- /dev/null +++ b/lib/bigcommerce/resources/geography/country.rb @@ -0,0 +1,22 @@ +# Country +# Countries and territories, identified by their ISO 3166 country codes. +# https://developer.bigcommerce.com/api/stores/v2/countries + +module Bigcommerce + class Country < Resource + include Bigcommerce::ResourceActions.new( + uri: 'countries/%d', + disable: [:create, :update, :destroy, :destroy_all]) + + property :id + property :count + property :country + property :country_iso2 + property :country_iso3 + property :states + + def self.count + get 'countries/count' + end + end +end diff --git a/lib/bigcommerce/resources/geography/state.rb b/lib/bigcommerce/resources/geography/state.rb new file mode 100644 index 0000000..536d9e5 --- /dev/null +++ b/lib/bigcommerce/resources/geography/state.rb @@ -0,0 +1,25 @@ +# State +# States and subdivisions belonging to countries. +# https://developer.bigcommerce.com/api/stores/v2/countries/states + +module Bigcommerce + class State < Resource + include Bigcommerce::SubresourceActions.new( + uri: 'countries/%d/states/%d', + disable: [:create, :update, :destroy, :destroy_all]) + + property :id + property :count + property :state + property :state_abbreviation + property :country_id + + def self.count(country_id) + get "countries/#{country_id}/states/count" + end + + def self.count_all + get 'countries/states/count' + end + end +end diff --git a/lib/bigcommerce/resources/marketing/coupon.rb b/lib/bigcommerce/resources/marketing/coupon.rb new file mode 100644 index 0000000..53b58ba --- /dev/null +++ b/lib/bigcommerce/resources/marketing/coupon.rb @@ -0,0 +1,30 @@ +# Coupon +# Category or product discounts that can be applied to orders for customers +# who enter a given code. +# https://developer.bigcommerce.com/api/stores/v2/coupons + +module Bigcommerce + class Coupon < Resource + include Bigcommerce::ResourceActions.new uri: 'coupons/%d' + + property :id + property :name + property :type + property :count + property :amount + property :min_purchase + property :expires + property :enabled + property :code + property :applies_to + property :num_uses + property :max_uses + property :max_uses_per_customer + property :restricted_to + property :shipping_methods + + def self.count + get 'coupons/count' + end + end +end diff --git a/lib/bigcommerce/resources/orders/order.rb b/lib/bigcommerce/resources/orders/order.rb new file mode 100644 index 0000000..60ba1ab --- /dev/null +++ b/lib/bigcommerce/resources/orders/order.rb @@ -0,0 +1,73 @@ +# Order +# Purchases from a store. +# https://developer.bigcommerce.com/api/stores/v2/orders + +module Bigcommerce + class Order < Resource + include Bigcommerce::ResourceActions.new uri: 'orders/%d' + + property :id + property :count + property :customer_id + property :date_created + property :date_modified + property :date_shipped + property :status_id + property :status + property :subtotal_ex_tax + property :subtotal_inc_tax + property :subtotal_tax + property :base_shipping_cost + property :shipping_cost_ex_tax + property :shipping_cost_inc_tax + property :shipping_cost_tax + property :shipping_cost_tax_class_id + property :base_handling_cost + property :handling_cost_ex_tax + property :handling_cost_inc_tax + property :handling_cost_tax + property :handling_cost_tax_class_id + property :base_wrapping_cost + property :wrapping_cost_ex_tax + property :wrapping_cost_inc_tax + property :wrapping_cost_tax + property :wrapping_cost_tax_class_id + property :total_ex_tax + property :total_inc_tax + property :total_tax + property :items_total + property :items_shipped + property :payment_method + property :payment_provider_id + property :payment_status + property :refunded_amount + property :order_is_digital + property :store_credit_amount + property :gift_certificate_amount + property :ip_address + property :geoip_country + property :geoip_country_iso2 + property :currency_id + property :currency_code + property :currency_exchange_rate + property :default_currency_id + property :default_currency_code + property :staff_notes + property :customer_message + property :discount_amount + property :coupon_discount + property :shipping_address_count + property :is_deleted + property :ebay_order_id + property :billing_address + property :order_source + property :external_source + property :products + property :shipping_addresses + property :coupons + + def self.count(params = {}) + get 'orders/count', params + end + end +end diff --git a/lib/bigcommerce/resources/orders/order_coupon.rb b/lib/bigcommerce/resources/orders/order_coupon.rb new file mode 100644 index 0000000..6c5f228 --- /dev/null +++ b/lib/bigcommerce/resources/orders/order_coupon.rb @@ -0,0 +1,20 @@ +# Order Coupon +# Coupons applied to an order. +# https://developer.bigcommerce.com/api/stores/v2/orders/coupons + +module Bigcommerce + class OrderCoupon < Resource + include Bigcommerce::SubresourceActions.new( + uri: 'orders/%d/coupons/%d', + disable: [:create, :update, :destroy, :destroy_all]) + + property :id + property :coupon_id + property :order_id + property :code + property :amount + property :type + property :type + property :discount + end +end diff --git a/lib/bigcommerce/resources/orders/order_message.rb b/lib/bigcommerce/resources/orders/order_message.rb new file mode 100644 index 0000000..2ac2786 --- /dev/null +++ b/lib/bigcommerce/resources/orders/order_message.rb @@ -0,0 +1,23 @@ +# Order Message +# Messages associated with an order. +# https://developer.bigcommerce.com/api/stores/v2/orders/messages + +module Bigcommerce + class OrderMessage < Resource + include Bigcommerce::SubresourceActions.new( + uri: 'orders/%d/messages/%d', + disable: [:create, :update, :destroy, :destroy_all]) + + property :id + property :order_id + property :staff_id + property :customer_id + property :type + property :subject + property :message + property :status + property :is_flagged + property :date_created + property :customer + end +end diff --git a/lib/bigcommerce/resources/orders/order_product.rb b/lib/bigcommerce/resources/orders/order_product.rb new file mode 100644 index 0000000..608ebf1 --- /dev/null +++ b/lib/bigcommerce/resources/orders/order_product.rb @@ -0,0 +1,64 @@ +# Order Product +# Product line items associated with an order. +# https://developer.bigcommerce.com/api/stores/v2/orders/products + +module Bigcommerce + class OrderProduct < Resource + include Bigcommerce::SubresourceActions.new( + uri: 'orders/%d/products/%d', + disable: [:create, :update, :destroy, :destroy_all]) + + property :id + property :order_id + property :product_id + property :order_address_id + property :name + property :sku + property :type + property :count + property :base_price + property :price_ex_tax + property :price_inc_tax + property :price_tax + property :base_total + property :total_ex_tax + property :total_inc_tax + property :total_tax + property :weight + property :quantity + property :base_cost_price + property :cost_price_inc_tax + property :cost_price_ex_tax + property :cost_price_tax + property :is_refunded + property :refund_amount + property :return_id + property :wrapping_name + property :base_wrapping_cost + property :wrapping_cost_ex_tax + property :wrapping_cost_inc_tax + property :wrapping_cost_tax + property :wrapping_message + property :quantity_shipped + property :event_name + property :event_date + property :fixed_shipping_cost + property :ebay_item_id + property :ebay_transaction_id + property :option_set_id + property :parent_order_product_id + property :is_bundled_product, from: :'is_bundled_product ' + property :bin_picking_number + property :applied_discounts + property :product_options + property :configurable_fields + + def self.count(order_id) + get "orders/#{order_id}/products/count" + end + + def self.count_all + get 'orders/products/count' + end + end +end diff --git a/lib/bigcommerce/resources/orders/order_shipping_address.rb b/lib/bigcommerce/resources/orders/order_shipping_address.rb new file mode 100644 index 0000000..160e6b3 --- /dev/null +++ b/lib/bigcommerce/resources/orders/order_shipping_address.rb @@ -0,0 +1,50 @@ +# Order Shipping Addresses +# Shipping addresses associated with an order. +# https://developer.bigcommerce.com/api/stores/v2/orders/shipping_addresses + +module Bigcommerce + class OrderShippingAddress < Resource + include Bigcommerce::SubresourceActions.new( + uri: 'orders/%d/shipping_addresses/%d', + disable: [:create, :update, :destroy, :destroy_all]) + + property :id + property :order_id + property :count + property :first_name + property :last_name + property :company + property :street_1 + property :street_2 + property :city + property :zip + property :country + property :country_iso2 + property :state + property :email + property :phone + property :items_total + property :items_shipped + property :shipping_method + property :base_cost + property :cost_ex_tax + property :cost_inc_tax + property :cost_tax + property :cost_tax_class_id + property :base_handling_cost + property :handling_cost_ex_tax + property :handling_cost_inc_tax + property :handling_cost_tax + property :handling_cost_tax_class_id + property :shipping_zone_id + property :shipping_zone_name + + def self.count(order_id) + get "orders/#{order_id}/shipping_addresses/count" + end + + def self.count_all + get 'orders/shipping_addresses/count' + end + end +end diff --git a/lib/bigcommerce/resources/orders/order_status.rb b/lib/bigcommerce/resources/orders/order_status.rb new file mode 100644 index 0000000..6c9c91b --- /dev/null +++ b/lib/bigcommerce/resources/orders/order_status.rb @@ -0,0 +1,16 @@ +# Order Status +# Statuses that can be assigned to orders. Each status represents a state in +# the fulfilment workflow. +# https://developer.bigcommerce.com/api/stores/v2/order_statuses + +module Bigcommerce + class OrderStatus < Resource + include Bigcommerce::ResourceActions.new( + uri: 'order_statuses/%d', + disable: [:create, :update, :destroy, :destroy_all]) + + property :id + property :name + property :order + end +end diff --git a/lib/bigcommerce/resources/orders/order_tax.rb b/lib/bigcommerce/resources/orders/order_tax.rb new file mode 100644 index 0000000..96a3724 --- /dev/null +++ b/lib/bigcommerce/resources/orders/order_tax.rb @@ -0,0 +1,23 @@ +# Order Shipping Addresses +# Shipping addresses associated with an order. +# https://developer.bigcommerce.com/api/stores/v2/orders/shipping_addresses + +module Bigcommerce + class OrderTax < Resource + include Bigcommerce::SubresourceActions.new( + uri: 'orders/%d/taxes/%d', + disable: [:create, :update, :destroy, :destroy_all]) + + property :id + property :order_id + property :order_address_id + property :tax_rate_id + property :tax_class_id + property :name + property :tax_class, from: :class + property :rate + property :priority + property :priority_amount + property :line_amount + end +end diff --git a/lib/bigcommerce/resources/orders/shipment.rb b/lib/bigcommerce/resources/orders/shipment.rb new file mode 100644 index 0000000..0784892 --- /dev/null +++ b/lib/bigcommerce/resources/orders/shipment.rb @@ -0,0 +1,30 @@ +# Order Shipment +# Shipping package consignments tracked from an order. +# https://developer.bigcommerce.com/api/stores/v2/orders/shipments + +module Bigcommerce + class Shipment < Resource + include Bigcommerce::SubresourceActions.new uri: 'orders/%d/shipments/%d' + + property :id + property :order_id + property :count + property :customer_id + property :order_address_id + property :date_created + property :tracking_number + property :shipping_method + property :comments + property :billing_address + property :shipping_address + property :items + + def self.count(order_id) + get "orders/#{order_id}/shipments/count" + end + + def self.count_all + get 'orders/shipments/count' + end + end +end diff --git a/lib/bigcommerce/resources/payments/payment_method.rb b/lib/bigcommerce/resources/payments/payment_method.rb new file mode 100644 index 0000000..47b3bf7 --- /dev/null +++ b/lib/bigcommerce/resources/payments/payment_method.rb @@ -0,0 +1,17 @@ +# Payment Method +# Enabled payment methods. +# https://developer.bigcommerce.com/api/stores/v2/payments/methods + +module Bigcommerce + class PaymentMethod < Resource + include Bigcommerce::Request.new 'payments/methods' + + property :code + property :name + property :test_mode + + def self.all(params = {}) + get path.build, params + end + end +end diff --git a/lib/bigcommerce/resources/products/brand.rb b/lib/bigcommerce/resources/products/brand.rb new file mode 100644 index 0000000..79759eb --- /dev/null +++ b/lib/bigcommerce/resources/products/brand.rb @@ -0,0 +1,23 @@ +# Brand +# Brand facets for identifying and categorising products according +# to their manufacturer or company metonym. +# https://developer.bigcommerce.com/api/stores/v2/brands + +module Bigcommerce + class Brand < Resource + include Bigcommerce::ResourceActions.new uri: 'brands/%d' + + property :id + property :name + property :count + property :page_title + property :meta_keywords + property :meta_description + property :image_file + property :search_keywords + + def self.count + get 'brands/count' + end + end +end diff --git a/lib/bigcommerce/resources/products/bulk_pricing_rule.rb b/lib/bigcommerce/resources/products/bulk_pricing_rule.rb new file mode 100644 index 0000000..75c62d0 --- /dev/null +++ b/lib/bigcommerce/resources/products/bulk_pricing_rule.rb @@ -0,0 +1,26 @@ +# Bulk Pricing Rule +# Bulk pricing rules applied to a product. +# https://developer.bigcommerce.com/api/stores/v2/products/discount_rules + +module Bigcommerce + class BulkPricingRule < Resource + include Bigcommerce::SubresourceActions.new( + uri: 'products/%d/discount_rules/%d') + + property :id + property :count + property :product_id + property :min + property :max + property :type + property :type_value + + def self.count(product_id) + get "products/#{product_id}/discount_rules/count" + end + + def self.count_all + get 'products/discount_rules/count' + end + end +end diff --git a/lib/bigcommerce/resources/products/category.rb b/lib/bigcommerce/resources/products/category.rb new file mode 100644 index 0000000..6d17346 --- /dev/null +++ b/lib/bigcommerce/resources/products/category.rb @@ -0,0 +1,29 @@ +# Category +# Index of hierarchical categories used to organise and group products. +# https://developer.bigcommerce.com/api/stores/v2/categories + +module Bigcommerce + class Category < Resource + include Bigcommerce::ResourceActions.new uri: 'categories/%d' + + property :id + property :parent_id + property :name + property :count + property :description + property :sort_order + property :page_title + property :meta_keywords + property :meta_description + property :layout_file + property :parent_category_list + property :image_file + property :is_visible + property :search_keywords + property :url + + def self.count + get 'categories/count' + end + end +end diff --git a/lib/bigcommerce/resources/products/configurable_field.rb b/lib/bigcommerce/resources/products/configurable_field.rb new file mode 100644 index 0000000..ce3c569 --- /dev/null +++ b/lib/bigcommerce/resources/products/configurable_field.rb @@ -0,0 +1,30 @@ +# Configurable Field +# Configurable fields associated with a product. +# https://developer.bigcommerce.com/api/stores/v2/products/configurable_fields + +module Bigcommerce + class ConfigurableField < Resource + include Bigcommerce::SubresourceActions.new( + uri: 'products/%d/configurable_fields/%d', + disable: [:create, :update]) + + property :id + property :product_id + property :count + property :name + property :type + property :allowed_file_types + property :max_size + property :select_options + property :is_required + property :sort_order + + def self.count(product_id) + get "products/#{product_id}/configurable_fields/count" + end + + def self.count_all + get 'products/configurable_fields/count' + end + end +end diff --git a/lib/bigcommerce/resources/products/custom_field.rb b/lib/bigcommerce/resources/products/custom_field.rb new file mode 100644 index 0000000..e78ec10 --- /dev/null +++ b/lib/bigcommerce/resources/products/custom_field.rb @@ -0,0 +1,24 @@ +# Custom Field +# Custom fields associated with a product. +# https://developer.bigcommerce.com/api/stores/v2/products/custom_fields + +module Bigcommerce + class CustomField < Resource + include Bigcommerce::SubresourceActions.new( + uri: 'products/%d/custom_fields/%d') + + property :id + property :product_id + property :count + property :name + property :text + + def self.count(product_id) + get "products/#{product_id}/custom_fields/count" + end + + def self.count_all + get 'products/custom_fields/count' + end + end +end diff --git a/lib/bigcommerce/resources/products/google_product_search_mapping.rb b/lib/bigcommerce/resources/products/google_product_search_mapping.rb new file mode 100644 index 0000000..251b043 --- /dev/null +++ b/lib/bigcommerce/resources/products/google_product_search_mapping.rb @@ -0,0 +1,26 @@ +# Google Product Search Mapping +# Google Product Search mappings for a product. +# https://developer.bigcommerce.com/api/stores/v2/products/googleproductsearch + +module Bigcommerce + class GoogleProductSearchMapping < Resource + include Bigcommerce::Request.new 'products/%d/googleproductsearch' + + property :enabled + property :product_id + property :category_id + property :custom_item + property :global_trade_item_number + property :manufacturer_part_number + property :gender + property :age_group + property :color + property :size + property :material + property :pattern + + def self.all(product_id) + get path.build(product_id) + end + end +end diff --git a/lib/bigcommerce/resources/products/option.rb b/lib/bigcommerce/resources/products/option.rb new file mode 100644 index 0000000..5a74ac5 --- /dev/null +++ b/lib/bigcommerce/resources/products/option.rb @@ -0,0 +1,20 @@ +# Option +# Shared attributes that control value facets on a product. +# https://developer.bigcommerce.com/api/stores/v2/options + +module Bigcommerce + class Option < Resource + include Bigcommerce::ResourceActions.new uri: 'options/%d' + + property :id + property :name + property :count + property :display_name + property :type + property :values + + def self.count + get 'options/count' + end + end +end diff --git a/lib/bigcommerce/resources/products/option_set.rb b/lib/bigcommerce/resources/products/option_set.rb new file mode 100644 index 0000000..a79160f --- /dev/null +++ b/lib/bigcommerce/resources/products/option_set.rb @@ -0,0 +1,18 @@ +# Option Set +# A reusable set of option facets that can be applied to products. +# https://developer.bigcommerce.com/api/stores/v2/options_sets + +module Bigcommerce + class OptionSet < Resource + include Bigcommerce::ResourceActions.new uri: 'option_sets/%d' + + property :id + property :name + property :count + property :options + + def self.count + get 'option_sets/count' + end + end +end diff --git a/lib/bigcommerce/resources/products/option_set_option.rb b/lib/bigcommerce/resources/products/option_set_option.rb new file mode 100644 index 0000000..cebb43c --- /dev/null +++ b/lib/bigcommerce/resources/products/option_set_option.rb @@ -0,0 +1,19 @@ +# Option Set Option +# Options belonging to an option set. +# https://developer.bigcommerce.com/api/stores/v2/option_sets/options + +module Bigcommerce + class OptionSetOption < Resource + include Bigcommerce::SubresourceActions.new( + uri: 'option_sets/%d/options/%d') + + property :id + property :option_id + property :option_set_id + property :display_name + property :sort_order + property :is_required + property :option + property :values + end +end diff --git a/lib/bigcommerce/resources/products/option_value.rb b/lib/bigcommerce/resources/products/option_value.rb new file mode 100644 index 0000000..43fe487 --- /dev/null +++ b/lib/bigcommerce/resources/products/option_value.rb @@ -0,0 +1,15 @@ +# Option Value +# Values that can be selected for an option. +# https://developer.bigcommerce.com/api/stores/v2/options/values + +module Bigcommerce + class OptionValue < Resource + include Bigcommerce::SubresourceActions.new uri: 'options/%d/values/%d' + + property :id + property :option_id + property :label + property :sort_order + property :value + end +end diff --git a/lib/bigcommerce/resources/products/product.rb b/lib/bigcommerce/resources/products/product.rb new file mode 100644 index 0000000..e02262b --- /dev/null +++ b/lib/bigcommerce/resources/products/product.rb @@ -0,0 +1,97 @@ +# Product +# Catalog of saleable items in the store. +# https://developer.bigcommerce.com/api/stores/v2/products + +module Bigcommerce + class Product < Resource + include Bigcommerce::ResourceActions.new uri: 'products/%d' + + property :id + property :count + property :keyword_filter + property :name + property :type + property :sku + property :description + property :search_keywords + property :availability_description + property :price + property :cost_price + property :retail_price + property :sale_price + property :calculated_price + property :sort_order + property :is_visible + property :is_featured + property :related_products + property :inventory_level + property :inventory_warning_level + property :warranty + property :weight + property :width + property :height + property :depth + property :fixed_cost_shipping_price + property :is_free_shipping + property :inventory_tracking + property :rating_total + property :rating_count + property :total_sold + property :date_created + property :brand_id + property :view_count + property :page_title + property :meta_keywords + property :meta_description + property :layout_file + property :is_price_hidden + property :price_hidden_label + property :categories + property :date_modified + property :event_date_field_name + property :event_date_type + property :event_date_start + property :event_date_end + property :myob_asset_account + property :myob_income_account + property :myob_expense_account + property :peachtree_gl_account + property :condition + property :is_condition_shown + property :preorder_release_date + property :is_preorder_only + property :preorder_message + property :order_quantity_minimum + property :order_quantity_maximum + property :open_graph_type + property :open_graph_title + property :open_graph_description + property :is_open_graph_thumbnail + property :upc + property :date_last_imported + property :option_set_id + property :tax_class_id + property :option_set_display + property :bin_picking_number + property :custom_url + property :availability + property :brand + property :downloads + property :images + property :discount_rules + property :configurable_fields + property :custom_fields + property :videos + property :skus + property :rules + property :option_set + property :options + property :tax_class + property :avalara_product_tax_code + property :primary_image + + def self.count(params = {}) + get 'products/count', params + end + end +end diff --git a/lib/bigcommerce/resources/products/product_image.rb b/lib/bigcommerce/resources/products/product_image.rb new file mode 100644 index 0000000..3dffbae --- /dev/null +++ b/lib/bigcommerce/resources/products/product_image.rb @@ -0,0 +1,31 @@ +# Product Image +# Images associated with a product. +# https://developer.bigcommerce.com/api/stores/v2/products/images + +module Bigcommerce + class ProductImage < Resource + include Bigcommerce::SubresourceActions.new uri: 'products/%d/images/%d' + + property :id + property :count + property :product_id + property :image_file + property :is_thumbnail + property :sort_order + property :zoom_url + property :thumbnail_url + property :standard_url + property :tiny_url + property :is_sample + property :description + property :date_created + + def self.count(product_id) + get "products/#{product_id}/images/count" + end + + def self.count_all + get 'products/images/count' + end + end +end diff --git a/lib/bigcommerce/resources/products/product_option.rb b/lib/bigcommerce/resources/products/product_option.rb new file mode 100644 index 0000000..c6bebd2 --- /dev/null +++ b/lib/bigcommerce/resources/products/product_option.rb @@ -0,0 +1,17 @@ +# Product Option +# Options associated directly with a product. +# https://developer.bigcommerce.com/api/stores/v2/products/options + +module Bigcommerce + class ProductOption < Resource + include Bigcommerce::SubresourceActions.new( + uri: 'products/%d/options/%d', + disable: [:create, :update, :destroy, :destroy_all]) + + property :id + property :option_id + property :display_name + property :sort_order + property :is_required + end +end diff --git a/lib/bigcommerce/resources/products/product_review.rb b/lib/bigcommerce/resources/products/product_review.rb new file mode 100644 index 0000000..37a5fce --- /dev/null +++ b/lib/bigcommerce/resources/products/product_review.rb @@ -0,0 +1,22 @@ +# Product Review +# Options associated directly with a product. +# https://developer.bigcommerce.com/api/stores/v2/products/reviews + +module Bigcommerce + class ProductReview < Resource + include Bigcommerce::Request.new 'products/%d/reviews' + + property :id + property :product_id + property :author + property :date_created + property :rating + property :title + property :review + property :status + + def self.all(product_id) + get path.build(product_id) + end + end +end diff --git a/lib/bigcommerce/resources/products/product_rule.rb b/lib/bigcommerce/resources/products/product_rule.rb new file mode 100644 index 0000000..591f119 --- /dev/null +++ b/lib/bigcommerce/resources/products/product_rule.rb @@ -0,0 +1,31 @@ +# Product Rule +# Rules that modify the default behaviour of products. +# https://developer.bigcommerce.com/api/stores/v2/products/rules + +module Bigcommerce + class ProductRule < Resource + include Bigcommerce::SubresourceActions.new uri: 'products/%d/rules/%d' + + property :id + property :count + property :product_id + property :sort_order + property :is_enabled + property :is_stop + property :price_adjuster + property :weight_adjuster + property :is_purchasing_disabled + property :purchasing_disabled_message + property :is_purchasing_hidden + property :image_file + property :conditions + + def self.count(product_id) + get "products/#{product_id}/rules/count" + end + + def self.count_all + get 'products/rules/count' + end + end +end diff --git a/lib/bigcommerce/resources/products/product_video.rb b/lib/bigcommerce/resources/products/product_video.rb new file mode 100644 index 0000000..8541d43 --- /dev/null +++ b/lib/bigcommerce/resources/products/product_video.rb @@ -0,0 +1,24 @@ +# Product Video +# Embedded videos displayed on product listings. +# https://developer.bigcommerce.com/api/stores/v2/products/videos + +module Bigcommerce + class ProductVideo < Resource + include Bigcommerce::SubresourceActions.new uri: 'products/%d/videos/%s' + + property :id + property :product_id + property :count + property :url + property :sort_order + property :name + + def self.count(product_id) + get "products/#{product_id}/videos/count" + end + + def self.count_all + get 'products/videos/count' + end + end +end diff --git a/lib/bigcommerce/resources/products/sku.rb b/lib/bigcommerce/resources/products/sku.rb new file mode 100644 index 0000000..b2ccc9a --- /dev/null +++ b/lib/bigcommerce/resources/products/sku.rb @@ -0,0 +1,29 @@ +# SKU +# Stock Keeping Unit identifiers associated with products. +# https://developer.bigcommerce.com/api/stores/v2/products/skus + +module Bigcommerce + class Sku < Resource + include Bigcommerce::SubresourceActions.new uri: 'products/%d/skus/%d' + + property :id + property :product_id + property :sku + property :cost_price + property :count + property :upc + property :inventory_level + property :intentory_warning_level + property :bin_picking_number + property :options + property :inventory_warning_level + + def self.count_all + get 'products/skus/count' + end + + def self.count(product_id) + get "products/#{product_id}/skus/count" + end + end +end diff --git a/lib/bigcommerce/resources/resource.rb b/lib/bigcommerce/resources/resource.rb new file mode 100644 index 0000000..dd6aecb --- /dev/null +++ b/lib/bigcommerce/resources/resource.rb @@ -0,0 +1,10 @@ +require 'bigcommerce/request' +require 'bigcommerce/resource_actions' +require 'bigcommerce/subresource_actions' + +module Bigcommerce + class Resource < Hashie::Trash + include Hashie::Extensions::MethodAccess + include Hashie::Extensions::IgnoreUndeclared + end +end diff --git a/lib/bigcommerce/resources/shipping/shipping_method.rb b/lib/bigcommerce/resources/shipping/shipping_method.rb new file mode 100644 index 0000000..4a885f3 --- /dev/null +++ b/lib/bigcommerce/resources/shipping/shipping_method.rb @@ -0,0 +1,15 @@ +# Shipping Method +# List of enabled shipping methods. +# https://developer.bigcommerce.com/api/stores/v2/shipping/methods + +module Bigcommerce + class ShippingMethod < Resource + include Bigcommerce::ResourceActions.new( + uri: 'shipping/methods/%d', + disable: [:create, :update, :destroy, :destroy_all]) + + property :id + property :name + property :method_name + end +end diff --git a/lib/bigcommerce/resources/store/store_information.rb b/lib/bigcommerce/resources/store/store_information.rb new file mode 100644 index 0000000..38b70f3 --- /dev/null +++ b/lib/bigcommerce/resources/store/store_information.rb @@ -0,0 +1,37 @@ +# Store Information +# Metadata that describes the store. +# https://developer.bigcommerce.com/api/stores/v2/store_information + +module Bigcommerce + class StoreInfo < Resource + include Bigcommerce::Request.new 'store' + + property :id + property :domain + property :name + property :address + property :phone + property :admin_email + property :order_email + property :language + property :currency + property :currency_symbol + property :decimal_separator + property :thousands_separator + property :decimal_places + property :dimension_decimal_places + property :dimension_decimal_token + property :dimension_thousands_token + property :currency_symbol_location + property :is_price_entered_with_tax + property :active_comparison_modules + property :weight_units + property :dimension_units + property :plan_name + property :logo + + def self.info + get path.build + end + end +end diff --git a/lib/bigcommerce/resources/system/time.rb b/lib/bigcommerce/resources/system/time.rb new file mode 100644 index 0000000..982356e --- /dev/null +++ b/lib/bigcommerce/resources/system/time.rb @@ -0,0 +1,15 @@ +# Time +# Timestamp ping to check the system status. +# https://developer.bigcommerce.com/api/stores/v2/time + +module Bigcommerce + class System < Resource + include Bigcommerce::Request.new 'time' + + property :time + + def self.time + get path.build + end + end +end diff --git a/lib/bigcommerce/resources/tax/tax_class.rb b/lib/bigcommerce/resources/tax/tax_class.rb new file mode 100644 index 0000000..04b5962 --- /dev/null +++ b/lib/bigcommerce/resources/tax/tax_class.rb @@ -0,0 +1,15 @@ +# Tax Class +# Tax classes are used to apply different tax rates for specific types +# of products and orders. +# https://developer.bigcommerce.com/api/stores/v2/tax_classes + +module Bigcommerce + class TaxClass < Resource + include Bigcommerce::ResourceActions.new( + uri: 'tax_classes/%d', + disable: [:create, :update, :destroy, :destroy_all]) + + property :id + property :name + end +end diff --git a/lib/bigcommerce/resources/webhooks/webhook.rb b/lib/bigcommerce/resources/webhooks/webhook.rb new file mode 100644 index 0000000..9b062b1 --- /dev/null +++ b/lib/bigcommerce/resources/webhooks/webhook.rb @@ -0,0 +1,22 @@ +# Webhook +# Register and manage webhooks that connect events from a store to +# external URLs. +# https://developer.bigcommerce.com/api/stores/v2/webhooks + +module Bigcommerce + class Webhook < Resource + include Bigcommerce::ResourceActions.new( + uri: 'hooks/%d', + disable: [:destroy_all]) + + property :id + property :client_id + property :store_hash + property :scope + property :destination + property :headers + property :is_active + property :created_at + property :update_at + end +end diff --git a/lib/bigcommerce/subresource_actions.rb b/lib/bigcommerce/subresource_actions.rb new file mode 100644 index 0000000..e4e33a0 --- /dev/null +++ b/lib/bigcommerce/subresource_actions.rb @@ -0,0 +1,43 @@ +module Bigcommerce + class SubresourceActions < ResourceActions + def included(base) + base.send(:include, Request.new(options[:uri])) + base.extend(ClassMethods) + options[:disable_methods] ||= [] + methods = ClassMethods.public_instance_methods & options[:disable_methods] + methods.each { |name| base.send(:remove_method, name) } + end + + module ClassMethods + def all(parent_id, params = {}) + fail ArgumentError if parent_id.nil? + get path.build(parent_id), params + end + + def find(parent_id, resource_id) + fail ArgumentError if [parent_id, resource_id].any?(&:nil?) + get path.build([parent_id, resource_id]) + end + + def create(parent_id, params) + fail ArgumentError if parent_id.nil? + post path.build(parent_id), params + end + + def update(parent_id, resource_id, params) + fail ArgumentError if [parent_id, resource_id].any?(&:nil?) + put path.build([parent_id, resource_id]), params + end + + def destroy(parent_id, resource_id) + fail ArgumentError if [parent_id, resource_id].any?(&:nil?) + delete path.build([parent_id, resource_id]) + end + + def destroy_all(parent_id) + fail ArgumentError if parent_id.nil? + delete path.build(parent_id) + end + end + end +end diff --git a/lib/bigcommerce/version.rb b/lib/bigcommerce/version.rb index b2b06d3..817ede0 100644 --- a/lib/bigcommerce/version.rb +++ b/lib/bigcommerce/version.rb @@ -1,6 +1,3 @@ module Bigcommerce - major = 0 - minor = 10 - patch = 0 - VERSION = [major, minor, patch].join('.') unless defined? Bigcommerce::VERSION + VERSION = '1.0.0.beta' end diff --git a/spec/big_commerce_spec.rb b/spec/big_commerce_spec.rb deleted file mode 100644 index f2027d1..0000000 --- a/spec/big_commerce_spec.rb +++ /dev/null @@ -1,9 +0,0 @@ -require 'spec_helper' - -describe "BigCommerce" do - describe "require 'big_commerce'" do - it "should raise exception when required" do - lambda { (require 'big_commerce').should raise(RuntimeError) } - end - end -end diff --git a/spec/bigcommerce/bigcommerce_spec.rb b/spec/bigcommerce/bigcommerce_spec.rb new file mode 100644 index 0000000..3d71f7a --- /dev/null +++ b/spec/bigcommerce/bigcommerce_spec.rb @@ -0,0 +1,76 @@ +require 'spec_helper' + +describe Bigcommerce do + let(:middleware) do + api.instance_variable_get('@builder').instance_variable_get('@handlers') + end + + it 'should return a faraday object when configured' do + Bigcommerce.configure do |config| + config.url = 'http://foobar.com' + config.auth = 'legacy' + config.api_key = '214789175' + config.username = 'admin' + end + expect(Bigcommerce.api).to be_a_kind_of(Faraday::Connection) + end + + describe '.build_connection' do + context 'when using legacy' do + let(:api) do + Bigcommerce.configure do |config| + config.url = 'http://foobar.com' + config.auth = 'legacy' + config.api_key = '214789175' + config.username = 'admin' + end + end + + it 'should have the correct auth middleware' do + expect(middleware).to include(Faraday::Request::BasicAuthentication) + end + end + + context 'when not using legacy' do + let(:api) do + Bigcommerce.configure do |config| + config.access_token = 'jksdgkjbhksjdb' + config.client_id = 'negskjgdjkbg' + end + end + + it 'should have the correct auth middleware' do + expect(middleware).to include(Bigcommerce::Middleware::Auth) + end + end + end + + describe 'multiple configurations' do + it 'should use the configuration for the most recently defined' do + Bigcommerce.configure do |config| + config.access_token = 'jksdgkjbhksjdb' + config.client_id = 'negskjgdjkbg' + end + + Bigcommerce.configure do |config| + config.url = 'http://foobar.com' + config.auth = 'legacy' + config.api_key = '214789175' + config.username = 'admin' + end + + expect(Bigcommerce.api.instance_variable_get('@builder') + .instance_variable_get('@handlers')) + .to include(Faraday::Request::BasicAuthentication) + + Bigcommerce.configure do |config| + config.access_token = 'jksdgkjbhksjdb' + config.client_id = 'negskjgdjkbg' + end + + expect(Bigcommerce.api.instance_variable_get('@builder') + .instance_variable_get('@handlers')) + .to include(Bigcommerce::Middleware::Auth) + end + end +end diff --git a/spec/bigcommerce/unit/actions_spec.rb b/spec/bigcommerce/unit/actions_spec.rb new file mode 100644 index 0000000..adbab89 --- /dev/null +++ b/spec/bigcommerce/unit/actions_spec.rb @@ -0,0 +1,151 @@ +require 'spec_helper' + +describe Bigcommerce::ResourceActions do + before do + module Bigcommerce + class DummyClass + include ResourceActions.new(uri: 'http://foo.bar/%d') + end + end + @klass = Bigcommerce::DummyClass + end + + let(:params) do + { page: 1 } + end + + it 'should have options' do + mod = Bigcommerce::ResourceActions.new( + uri: 'http://foo.bar', + disable: [:find,:all] + ) + options = { + uri: 'http://foo.bar', + disable: [:find,:all] + } + expect(mod._options).to eq options + end + + describe '.all' do + it 'should make a get request to the correct route with query params' do + expect(@klass).to receive(:get).with('http://foo.bar', page: 1) + @klass.all(params) + end + + it 'should make a get request to the correct route' do + expect(@klass).to receive(:get).with('http://foo.bar', {}) + params.delete(:params) + @klass.all + end + end + + describe '.find' do + it 'should make a get request to the correct route' do + expect(@klass).to receive(:get).with('http://foo.bar/1') + @klass.find(1) + end + end + + describe '.create' do + it 'should make a post request to the correct route with params' do + expect(@klass).to receive(:post).with('http://foo.bar', page: 1) + @klass.create(params) + end + end + + describe '.update' do + it 'should make a put request to the correct route with params' do + expect(@klass).to receive(:put).with('http://foo.bar/1', page: 1) + @klass.update(1, params) + end + end + + describe '.destroy' do + it 'should make a delete request to the correct route with params' do + expect(@klass).to receive(:delete).with('http://foo.bar/1') + @klass.destroy(1) + end + end + + describe '.destroy_all' do + it 'should make a delete request to the correct route with params' do + expect(@klass).to receive(:delete).with('http://foo.bar') + @klass.destroy_all + end + end +end + +describe Bigcommerce::SubresourceActions do + before do + module Bigcommerce + class DummyClass + include SubresourceActions.new(uri: 'http://foo.bar/%d/%d') + end + end + @klass = Bigcommerce::DummyClass + end + + let(:params) do + { page: 1 } + end + + it 'should have options' do + mod = Bigcommerce::SubresourceActions.new( + uri: 'http://foo.bar', + disable: [:find,:all] + ) + options = { + uri: 'http://foo.bar', + disable: [:find,:all] + } + expect(mod._options).to eq options + end + + describe '.all' do + it 'should make a get request to the correct route with query params' do + expect(@klass).to receive(:get).with('http://foo.bar/1', page: 1) + @klass.all(1, params) + end + + it 'should make a get request to the correct route' do + expect(@klass).to receive(:get).with('http://foo.bar/1', {}) + params.delete(:params) + @klass.all(1) + end + end + + describe '.find' do + it 'should make a get request to the correct route' do + expect(@klass).to receive(:get).with('http://foo.bar/1/2') + @klass.find(1,2) + end + end + + describe '.create' do + it 'should make a post request to the correct route with params' do + expect(@klass).to receive(:post).with('http://foo.bar/1', page: 1) + @klass.create(1, params) + end + end + + describe '.update' do + it 'should make a put request to the correct route with params' do + expect(@klass).to receive(:put).with('http://foo.bar/1/2', page: 1) + @klass.update(1, 2, params) + end + end + + describe '.destroy' do + it 'should make a delete request to the correct route with params' do + expect(@klass).to receive(:delete).with('http://foo.bar/1/2') + @klass.destroy(1, 2) + end + end + + describe '.destroy_all' do + it 'should make a delete request to the correct route with params' do + expect(@klass).to receive(:delete).with('http://foo.bar/1') + @klass.destroy_all(1) + end + end +end diff --git a/spec/bigcommerce/unit/exception_spec.rb b/spec/bigcommerce/unit/exception_spec.rb new file mode 100644 index 0000000..ed1272a --- /dev/null +++ b/spec/bigcommerce/unit/exception_spec.rb @@ -0,0 +1,53 @@ +require 'spec_helper' + +describe Bigcommerce::HttpErrors do + let(:dummy_class) { Class.new { extend Bigcommerce::HttpErrors } } + + it '::ERRORS is not nil' do + expect(Bigcommerce::HttpErrors::ERRORS).not_to be_nil + end + + context 'invalid response status' do + it 'should throw an exception' do + code = 404 + expect { dummy_class.throw_http_exception!(code) }.to raise_exception + end + + it 'should have a valid error' do + codes = Bigcommerce::HttpErrors::ERRORS.keys + codes.each do |code| + expect { dummy_class.throw_http_exception!(code) }.to raise_exception + end + end + + it 'should allow you to pass in an error message when throwing exception' do + code = 404 + env = double + allow(env).to receive(:body) { {} } + allow(env).to receive(:[]) { {} } + expect do + dummy_class.throw_http_exception!(code, env) + end.to raise_exception(Bigcommerce::HttpErrors::ERRORS[code]) + end + + it 'should parse out a retry-after header if present' do + code = 429 + env = double + allow(env).to receive(:body) { "{\"time\":1426184190}" } + allow(env).to receive(:[]).with(:response_headers).and_return('X-Retry-After' => 1) + begin + dummy_class.throw_http_exception!(code, env) + rescue Bigcommerce::TooManyRequests => e + expect(e.response_headers[:retry_after]).to eq 1 + end + end + end + + context 'valid response status' do + it 'should not throw an exception' do + code = 200 + env = double + expect { dummy_class.throw_http_exception!(code, env) }.to_not raise_exception + end + end +end diff --git a/spec/bigcommerce/unit/middleware/auth_spec.rb b/spec/bigcommerce/unit/middleware/auth_spec.rb new file mode 100644 index 0000000..c056a32 --- /dev/null +++ b/spec/bigcommerce/unit/middleware/auth_spec.rb @@ -0,0 +1,18 @@ +require 'spec_helper' + +describe Bigcommerce::Middleware::Auth do + it 'should set the correct headers' do + app = double + options = { + client_id: 'client_id', + access_token: 'access_token' + } + @api = Bigcommerce::Middleware::Auth.new(app, options) + expect(app).to receive(:call).with( + request_headers: { + 'X-Auth-Client' => 'client_id', + 'X-Auth-Token' => 'access_token' + }) + @api.call(request_headers: {}) + end +end diff --git a/spec/bigcommerce/unit/middleware/http_exception_spec.rb b/spec/bigcommerce/unit/middleware/http_exception_spec.rb new file mode 100644 index 0000000..3c254f4 --- /dev/null +++ b/spec/bigcommerce/unit/middleware/http_exception_spec.rb @@ -0,0 +1,40 @@ +require 'spec_helper' + +describe Bigcommerce::Middleware::HttpException do + before(:each) { @e = Bigcommerce::Middleware::HttpException.new } + + it 'should check for an error on all responses' do + env = { + status: '200', + body: 'Valid' + } + expect(@e).to receive(:throw_http_exception!).with(200, env) + @e.on_complete env + end + + context 'when valid response' do + let(:env) do + { + status: '200', + body: 'Valid' + } + end + + it 'should return its argument if no errors' do + expect(@e.on_complete(env)).to eq env + end + end + + context 'when invalid response' do + let(:env) do + { + status: '404', + body: 'Error' + } + end + + it 'should throw an exception' do + expect { @e.on_complete(env) }.to raise_exception + end + end +end diff --git a/spec/bigcommerce/unit/request_spec.rb b/spec/bigcommerce/unit/request_spec.rb new file mode 100644 index 0000000..3702a0f --- /dev/null +++ b/spec/bigcommerce/unit/request_spec.rb @@ -0,0 +1,180 @@ +require 'spec_helper' + +describe Bigcommerce::Request do + before do + module Bigcommerce + class DummyClass + include Request.new 'foo/%d' + end + end + @klass = Bigcommerce::DummyClass + end + + describe '.path' do + it 'should have a path method to expose the path_builder' do + expect(@klass.path).to be_kind_of Bigcommerce::PathBuilder + end + end + + describe 'ClassMethods' do + before do + double Bigcommerce.api + end + + let(:json) { "{\"body\":[{\"time\":1426184190},{\"time\":1426184190}]}" } + + describe '.get' do + it 'should call raw_request and build_response_object' do + allow(@klass).to receive(:raw_request) { json } + expect(@klass).to receive(:raw_request).with(:get, @klass.path, {}) + expect(@klass).to receive(:build_response_object).with(json) + @klass.get(@klass.path, {}) + end + end + + describe '.delete' do + it 'should call raw_request' do + response = double + allow(response).to receive(:body) { '' } + allow(@klass).to receive(:raw_request) { response } + expect(@klass).to receive(:raw_request).with(:delete, @klass.path) + @klass.delete(@klass.path) + end + end + + describe '.post' do + it 'should call raw_request and build_response_object' do + allow(@klass).to receive(:raw_request) { json } + expect(@klass).to receive(:raw_request).with(:post, @klass.path, {}) + expect(@klass).to receive(:build_response_object).with(json) + @klass.post(@klass.path, {}) + end + end + + describe '.put' do + it 'should call raw_request and build_response_object' do + allow(@klass).to receive(:raw_request) { json } + expect(@klass).to receive(:raw_request).with(:put, @klass.path, {}) + expect(@klass).to receive(:build_response_object).with(json) + @klass.put(@klass.path, {}) + end + end + + describe '.raw_request' do + before do + Bigcommerce.configure do |config| + config.client_id = 'sdbgksjbg4' + config.access_token = 'jkdgbdsgbg' + config.store_hash = 'sdgjnsdjg' + end + @api = Bigcommerce.api + end + + it 'send its method to Bigcommerce.api' do + response = double + allow(@api).to receive(:get) { response } + allow(response).to receive(:headers) { '' } + expect(@api).to receive(:get).with('path/1', nil) + expect(response).to receive(:headers) + @klass.raw_request(:get, 'path/1') + end + end + + describe 'private methods' do + describe '.build_response_object' do + before do + module Bigcommerce + class DummyClass + include Request.new 'foo/%d' + def initialize(params) + @params = params + end + end + end + @klass_with_init = Bigcommerce::DummyClass + end + + describe 'json array' do + let(:json) { "[{\"time\":1426184190},{\"time\":1426184190}]" } + + it 'should build an array of objects' do + response = double + allow(response).to receive(:body) { json } + objs = @klass_with_init.send(:build_response_object, response) + expect(objs).to be_kind_of Array + objs.each do |obj| + expect(obj).to be_kind_of Bigcommerce::DummyClass + end + end + end + describe 'json object' do + let(:json) { "{\"time\":1426184190}" } + it 'should build an object' do + response = double + allow(response).to receive(:body) { json } + objs = @klass_with_init.send(:build_response_object, response) + expect(objs).to be_kind_of Bigcommerce::DummyClass + end + end + end + + describe '.parse' do + describe 'empty string' do + let(:json) { "" } + + it 'should return an array' do + expect(@klass.send(:parse, json)).to be_kind_of Array + end + end + + describe 'valid json' do + let(:json) { "{\"time\":1426184190}" } + + it 'should symbolize keys' do + expect(@klass.send(:parse, json)).to eq({time:1426184190}) + end + + it 'should return a hash' do + expect(@klass.send(:parse, json)).to be_kind_of Hash + end + end + end + end + end +end + +describe Bigcommerce::PathBuilder do + let(:uri) { 'bar/%d' } + before do + @path_builder = Bigcommerce::PathBuilder.new uri + end + + describe '.to_s' do + it 'should return uri' do + expect(@path_builder.to_s).to eq uri + end + end + + describe '.build' do + context 'hash of keys' do + let(:keys) { 1 } + it 'should build a formed path' do + expect(@path_builder.build keys).to eq 'bar/1' + end + end + + context 'integer keys' do + let(:keys) { 1 } + it 'should build a formed path' do + expect(@path_builder.build keys).to eq 'bar/1' + end + end + + context 'integer keys' do + let(:keys) { nil } + it 'should build a formed path' do + expect(@path_builder.build keys).to eq 'bar' + end + end + end +end diff --git a/spec/bigcommerce/unit/resources/content/blog_post_spec.rb b/spec/bigcommerce/unit/resources/content/blog_post_spec.rb new file mode 100644 index 0000000..2c66fdb --- /dev/null +++ b/spec/bigcommerce/unit/resources/content/blog_post_spec.rb @@ -0,0 +1,12 @@ +require 'spec_helper' + +describe Bigcommerce::BlogPost do + before(:each) { @blog_post = Bigcommerce::BlogPost } + + describe '.count' do + it 'should hit the correct path' do + expect(@blog_post).to receive(:get).with('blog/posts/count') + @blog_post.count + end + end +end diff --git a/spec/bigcommerce/unit/resources/content/blog_tag_spec.rb b/spec/bigcommerce/unit/resources/content/blog_tag_spec.rb new file mode 100644 index 0000000..c1714ec --- /dev/null +++ b/spec/bigcommerce/unit/resources/content/blog_tag_spec.rb @@ -0,0 +1,12 @@ +require 'spec_helper' + +describe Bigcommerce::BlogTag do + before(:each) { @blog_tag = Bigcommerce::BlogTag } + + describe '.all' do + it 'should hit the correct path' do + expect(@blog_tag).to receive(:get).with(@blog_tag.path.build) + @blog_tag.all + end + end +end diff --git a/spec/bigcommerce/unit/resources/content/redirect_spec.rb b/spec/bigcommerce/unit/resources/content/redirect_spec.rb new file mode 100644 index 0000000..aca0436 --- /dev/null +++ b/spec/bigcommerce/unit/resources/content/redirect_spec.rb @@ -0,0 +1,12 @@ +require 'spec_helper' + +describe Bigcommerce::Redirect do + before(:each) { @redirect = Bigcommerce::Redirect } + + describe '.count' do + it 'should hit the correct path' do + expect(@redirect).to receive(:get).with('redirects/count') + @redirect.count + end + end +end diff --git a/spec/bigcommerce/unit/resources/customers/customer_address_spec.rb b/spec/bigcommerce/unit/resources/customers/customer_address_spec.rb new file mode 100644 index 0000000..352beca --- /dev/null +++ b/spec/bigcommerce/unit/resources/customers/customer_address_spec.rb @@ -0,0 +1,21 @@ +require 'spec_helper' + +describe Bigcommerce::CustomerAddress do + before(:each) { @address = Bigcommerce::CustomerAddress } + + let(:params) { 1 } + + describe '.count' do + it 'should hit the correct path' do + expect(@address).to receive(:get).with('customers/1/addresses/count') + @address.count params + end + end + + describe '.count_all' do + it 'should hit the correct path' do + expect(@address).to receive(:get).with('customers/addresses/count') + @address.count_all + end + end +end diff --git a/spec/bigcommerce/unit/resources/customers/customer_group_spec.rb b/spec/bigcommerce/unit/resources/customers/customer_group_spec.rb new file mode 100644 index 0000000..1c22b5d --- /dev/null +++ b/spec/bigcommerce/unit/resources/customers/customer_group_spec.rb @@ -0,0 +1,12 @@ +require 'spec_helper' + +describe Bigcommerce::CustomerGroup do + before(:each) { @group = Bigcommerce::CustomerGroup } + + describe '.count' do + it 'should hit the correct path' do + expect(@group).to receive(:get).with('customer_groups/count') + @group.count + end + end +end diff --git a/spec/bigcommerce/unit/resources/customers/customer_spec.rb b/spec/bigcommerce/unit/resources/customers/customer_spec.rb new file mode 100644 index 0000000..02d34f5 --- /dev/null +++ b/spec/bigcommerce/unit/resources/customers/customer_spec.rb @@ -0,0 +1,12 @@ +require 'spec_helper' + +describe Bigcommerce::Customer do + before(:each) { @customer = Bigcommerce::Customer } + + describe '.count' do + it 'should hit the correct path' do + expect(@customer).to receive(:get).with('customers/count') + @customer.count + end + end +end diff --git a/spec/bigcommerce/unit/resources/geography/country_spec.rb b/spec/bigcommerce/unit/resources/geography/country_spec.rb new file mode 100644 index 0000000..b06edab --- /dev/null +++ b/spec/bigcommerce/unit/resources/geography/country_spec.rb @@ -0,0 +1,12 @@ +require 'spec_helper' + +describe Bigcommerce::Country do + before(:each) { @country = Bigcommerce::Country } + + describe '.count' do + it 'should hit the correct path' do + expect(@country).to receive(:get).with('countries/count') + @country.count + end + end +end diff --git a/spec/bigcommerce/unit/resources/geography/state_spec.rb b/spec/bigcommerce/unit/resources/geography/state_spec.rb new file mode 100644 index 0000000..7769e9c --- /dev/null +++ b/spec/bigcommerce/unit/resources/geography/state_spec.rb @@ -0,0 +1,21 @@ +require 'spec_helper' + +describe Bigcommerce::State do + before(:each) { @state = Bigcommerce::State } + + let(:params) { 226 } + + describe '.count' do + it 'should hit the correct path' do + expect(@state).to receive(:get).with('countries/226/states/count') + @state.count params + end + end + + describe '.count_all' do + it 'should hit the correct path' do + expect(@state).to receive(:get).with('countries/states/count') + @state.count_all + end + end +end diff --git a/spec/bigcommerce/unit/resources/marketing/coupon_spec.rb b/spec/bigcommerce/unit/resources/marketing/coupon_spec.rb new file mode 100644 index 0000000..e2d9974 --- /dev/null +++ b/spec/bigcommerce/unit/resources/marketing/coupon_spec.rb @@ -0,0 +1,12 @@ +require 'spec_helper' + +describe Bigcommerce::Coupon do + before(:each) { @coupon = Bigcommerce::Coupon } + + describe '.count' do + it 'should hit the correct path' do + expect(@coupon).to receive(:get).with('coupons/count') + @coupon.count + end + end +end diff --git a/spec/bigcommerce/unit/resources/orders/order_product_spec.rb b/spec/bigcommerce/unit/resources/orders/order_product_spec.rb new file mode 100644 index 0000000..bb7a7d1 --- /dev/null +++ b/spec/bigcommerce/unit/resources/orders/order_product_spec.rb @@ -0,0 +1,21 @@ +require 'spec_helper' + +describe Bigcommerce::OrderProduct do + before(:each) { @order_product = Bigcommerce::OrderProduct } + + let(:params) { 1 } + + describe '.count' do + it 'should hit the correct path' do + expect(@order_product).to receive(:get).with('orders/1/products/count') + @order_product.count params + end + end + + describe '.count_all' do + it 'should hit the correct path' do + expect(@order_product).to receive(:get).with('orders/products/count') + @order_product.count_all + end + end +end diff --git a/spec/bigcommerce/unit/resources/orders/order_shipping_address_spec.rb b/spec/bigcommerce/unit/resources/orders/order_shipping_address_spec.rb new file mode 100644 index 0000000..2bdc700 --- /dev/null +++ b/spec/bigcommerce/unit/resources/orders/order_shipping_address_spec.rb @@ -0,0 +1,21 @@ +require 'spec_helper' + +describe Bigcommerce::OrderShippingAddress do + before(:each) { @shipping_address = Bigcommerce::OrderShippingAddress } + + let(:params) { 1 } + + describe '.count' do + it 'should hit the correct path' do + expect(@shipping_address).to receive(:get).with('orders/1/shipping_addresses/count') + @shipping_address.count params + end + end + + describe '.count_all' do + it 'should hit the correct path' do + expect(@shipping_address).to receive(:get).with('orders/shipping_addresses/count') + @shipping_address.count_all + end + end +end diff --git a/spec/bigcommerce/unit/resources/orders/order_spec.rb b/spec/bigcommerce/unit/resources/orders/order_spec.rb new file mode 100644 index 0000000..f983f3f --- /dev/null +++ b/spec/bigcommerce/unit/resources/orders/order_spec.rb @@ -0,0 +1,13 @@ +require 'spec_helper' + +describe Bigcommerce::Order do + before(:each) { @order = Bigcommerce::Order } + + describe '.count' do + it 'should hit the correct path and should allow params' do + params = { page: 1 } + expect(@order).to receive(:get).with('orders/count', params) + @order.count params + end + end +end diff --git a/spec/bigcommerce/unit/resources/orders/shipment_spec.rb b/spec/bigcommerce/unit/resources/orders/shipment_spec.rb new file mode 100644 index 0000000..ef9539a --- /dev/null +++ b/spec/bigcommerce/unit/resources/orders/shipment_spec.rb @@ -0,0 +1,21 @@ +require 'spec_helper' + +describe Bigcommerce::Shipment do + before(:each) { @shipment = Bigcommerce::Shipment } + + let(:params) { 1 } + + describe '.count' do + it 'hit the correct path' do + expect(@shipment).to receive(:get).with('orders/1/shipments/count') + @shipment.count params + end + end + + describe '.count_all' do + it 'hit the correct path' do + expect(@shipment).to receive(:get).with('orders/shipments/count') + @shipment.count_all + end + end +end diff --git a/spec/bigcommerce/unit/resources/payments/payment_method_spec.rb b/spec/bigcommerce/unit/resources/payments/payment_method_spec.rb new file mode 100644 index 0000000..88e127c --- /dev/null +++ b/spec/bigcommerce/unit/resources/payments/payment_method_spec.rb @@ -0,0 +1,23 @@ +require 'spec_helper' + +describe Bigcommerce::PaymentMethod do + before(:each) { @payment_method = Bigcommerce::PaymentMethod } + + let(:params) do + { + page: 1 + } + end + + describe '.all' do + it 'should hit the correct path without params' do + expect(@payment_method).to receive(:get).with('payments/methods', {}) + @payment_method.all + end + + it 'should hit the correct path with params' do + expect(@payment_method).to receive(:get).with('payments/methods', params) + @payment_method.all params + end + end +end diff --git a/spec/bigcommerce/unit/resources/products/brand_spec.rb b/spec/bigcommerce/unit/resources/products/brand_spec.rb new file mode 100644 index 0000000..5fa9926 --- /dev/null +++ b/spec/bigcommerce/unit/resources/products/brand_spec.rb @@ -0,0 +1,12 @@ +require 'spec_helper' + +describe Bigcommerce::Brand do + before(:each) { @brand = Bigcommerce::Brand } + + describe '.count' do + it 'should hit the correct path' do + expect(@brand).to receive(:get).with('brands/count') + @brand.count + end + end +end diff --git a/spec/bigcommerce/unit/resources/products/bulk_pricing_rule_spec.rb b/spec/bigcommerce/unit/resources/products/bulk_pricing_rule_spec.rb new file mode 100644 index 0000000..f85a2eb --- /dev/null +++ b/spec/bigcommerce/unit/resources/products/bulk_pricing_rule_spec.rb @@ -0,0 +1,21 @@ +require 'spec_helper' + +describe Bigcommerce::BulkPricingRule do + before(:each) { @bulk_pricing_rule = Bigcommerce::BulkPricingRule } + + let(:params) { 1 } + + describe '.count' do + it 'should hit the correct path' do + expect(@bulk_pricing_rule).to receive(:get).with('products/1/discount_rules/count') + @bulk_pricing_rule.count params + end + end + + describe '.count_all' do + it 'should hit the correct path' do + expect(@bulk_pricing_rule).to receive(:get).with('products/discount_rules/count') + @bulk_pricing_rule.count_all + end + end +end diff --git a/spec/bigcommerce/unit/resources/products/category_spec.rb b/spec/bigcommerce/unit/resources/products/category_spec.rb new file mode 100644 index 0000000..b8898b0 --- /dev/null +++ b/spec/bigcommerce/unit/resources/products/category_spec.rb @@ -0,0 +1,12 @@ +require 'spec_helper' + +describe Bigcommerce::Category do + before(:each) { @category = Bigcommerce::Category } + + describe '.count' do + it 'should hit the correct path' do + expect(@category).to receive(:get).with('categories/count') + @category.count + end + end +end diff --git a/spec/bigcommerce/unit/resources/products/configurable_field_spec.rb b/spec/bigcommerce/unit/resources/products/configurable_field_spec.rb new file mode 100644 index 0000000..973b0cc --- /dev/null +++ b/spec/bigcommerce/unit/resources/products/configurable_field_spec.rb @@ -0,0 +1,21 @@ +require 'spec_helper' + +describe Bigcommerce::ConfigurableField do + before(:each) { @configurable_field = Bigcommerce::ConfigurableField } + + let(:params) { 1 } + + describe '.count' do + it 'should hit the correct path' do + expect(@configurable_field).to receive(:get).with('products/1/configurable_fields/count') + @configurable_field.count params + end + end + + describe '.count_all' do + it 'should hit the correct path' do + expect(@configurable_field).to receive(:get).with('products/configurable_fields/count') + @configurable_field.count_all + end + end +end diff --git a/spec/bigcommerce/unit/resources/products/custom_field_spec.rb b/spec/bigcommerce/unit/resources/products/custom_field_spec.rb new file mode 100644 index 0000000..14c3743 --- /dev/null +++ b/spec/bigcommerce/unit/resources/products/custom_field_spec.rb @@ -0,0 +1,21 @@ +require 'spec_helper' + +describe Bigcommerce::CustomField do + before(:each) { @custom_field = Bigcommerce::CustomField } + + let(:params) { 1 } + + describe '.count' do + it 'should hit the correct path' do + expect(@custom_field).to receive(:get).with('products/1/custom_fields/count') + @custom_field.count params + end + end + + describe '.count_all' do + it 'should hit the correct path' do + expect(@custom_field).to receive(:get).with('products/custom_fields/count') + @custom_field.count_all + end + end +end diff --git a/spec/bigcommerce/unit/resources/products/google_product_search_mapping_spec.rb b/spec/bigcommerce/unit/resources/products/google_product_search_mapping_spec.rb new file mode 100644 index 0000000..2e084c2 --- /dev/null +++ b/spec/bigcommerce/unit/resources/products/google_product_search_mapping_spec.rb @@ -0,0 +1,14 @@ +require 'spec_helper' + +describe Bigcommerce::GoogleProductSearchMapping do + before(:each) { @mapping = Bigcommerce::GoogleProductSearchMapping } + + let(:params) { 1 } + + describe '.all' do + it 'should hit the correct path' do + expect(@mapping).to receive(:get).with('products/1/googleproductsearch') + @mapping.all params + end + end +end diff --git a/spec/bigcommerce/unit/resources/products/option_set_spec.rb b/spec/bigcommerce/unit/resources/products/option_set_spec.rb new file mode 100644 index 0000000..8a18f83 --- /dev/null +++ b/spec/bigcommerce/unit/resources/products/option_set_spec.rb @@ -0,0 +1,12 @@ +require 'spec_helper' + +describe Bigcommerce::OptionSet do + before(:each) { @option_set = Bigcommerce::OptionSet } + + describe '.count' do + it 'should hit the correct path' do + expect(@option_set).to receive(:get).with('option_sets/count') + @option_set.count + end + end +end diff --git a/spec/bigcommerce/unit/resources/products/option_spec.rb b/spec/bigcommerce/unit/resources/products/option_spec.rb new file mode 100644 index 0000000..bbbec8c --- /dev/null +++ b/spec/bigcommerce/unit/resources/products/option_spec.rb @@ -0,0 +1,12 @@ +require 'spec_helper' + +describe Bigcommerce::Option do + before(:each) { @option = Bigcommerce::Option } + + describe '.count' do + it 'should hit the correct path' do + expect(@option).to receive(:get).with('options/count') + @option.count + end + end +end diff --git a/spec/bigcommerce/unit/resources/products/product_image_spec.rb b/spec/bigcommerce/unit/resources/products/product_image_spec.rb new file mode 100644 index 0000000..0b9aaae --- /dev/null +++ b/spec/bigcommerce/unit/resources/products/product_image_spec.rb @@ -0,0 +1,21 @@ +require 'spec_helper' + +describe Bigcommerce::ProductImage do + before(:each) { @image = Bigcommerce::ProductImage } + + let(:params) { 1 } + + describe '.count' do + it 'should hit the correct path' do + expect(@image).to receive(:get).with('products/1/images/count') + @image.count params + end + end + + describe '.count_all' do + it 'should hit the correct path' do + expect(@image).to receive(:get).with('products/images/count') + @image.count_all + end + end +end diff --git a/spec/bigcommerce/unit/resources/products/product_review_spec.rb b/spec/bigcommerce/unit/resources/products/product_review_spec.rb new file mode 100644 index 0000000..5e405fd --- /dev/null +++ b/spec/bigcommerce/unit/resources/products/product_review_spec.rb @@ -0,0 +1,14 @@ +require 'spec_helper' + +describe Bigcommerce::ProductReview do + before(:each) { @product_review = Bigcommerce::ProductReview } + + let(:params) { 1 } + + describe '.all' do + it 'should hit the correct path' do + expect(@product_review).to receive(:get).with('products/1/reviews') + @product_review.all params + end + end +end diff --git a/spec/bigcommerce/unit/resources/products/product_rule_spec.rb b/spec/bigcommerce/unit/resources/products/product_rule_spec.rb new file mode 100644 index 0000000..06725d1 --- /dev/null +++ b/spec/bigcommerce/unit/resources/products/product_rule_spec.rb @@ -0,0 +1,21 @@ +require 'spec_helper' + +describe Bigcommerce::ProductRule do + before(:each) { @rule = Bigcommerce::ProductRule } + + let(:params) { 1 } + + describe '.count' do + it 'should hit the correct path' do + expect(@rule).to receive(:get).with('products/1/rules/count') + @rule.count params + end + end + + describe '.count_all' do + it 'should hit the correct path' do + expect(@rule).to receive(:get).with('products/rules/count') + @rule.count_all + end + end +end diff --git a/spec/bigcommerce/unit/resources/products/product_spec.rb b/spec/bigcommerce/unit/resources/products/product_spec.rb new file mode 100644 index 0000000..112841e --- /dev/null +++ b/spec/bigcommerce/unit/resources/products/product_spec.rb @@ -0,0 +1,13 @@ +require 'spec_helper' + +describe Bigcommerce::Product do + before(:each) { @product = Bigcommerce::Product } + + describe '.count' do + it 'should hit the correct path with params' do + params = { page: 1 } + expect(@product).to receive(:get).with('products/count', params) + @product.count params + end + end +end diff --git a/spec/bigcommerce/unit/resources/products/product_video_spec.rb b/spec/bigcommerce/unit/resources/products/product_video_spec.rb new file mode 100644 index 0000000..4c4da0f --- /dev/null +++ b/spec/bigcommerce/unit/resources/products/product_video_spec.rb @@ -0,0 +1,21 @@ +require 'spec_helper' + +describe Bigcommerce::ProductVideo do + before(:each) { @video = Bigcommerce::ProductVideo } + + let(:params) { 1 } + + describe '.count' do + it '.count should hit the correct path' do + expect(@video).to receive(:get).with('products/1/videos/count') + @video.count params + end + end + + describe '.count_all' do + it '.count should hit the correct path' do + expect(@video).to receive(:get).with('products/videos/count') + @video.count_all + end + end +end diff --git a/spec/bigcommerce/unit/resources/products/sku_spec.rb b/spec/bigcommerce/unit/resources/products/sku_spec.rb new file mode 100644 index 0000000..156a4d5 --- /dev/null +++ b/spec/bigcommerce/unit/resources/products/sku_spec.rb @@ -0,0 +1,21 @@ +require 'spec_helper' + +describe Bigcommerce::Sku do + before(:each) { @sku = Bigcommerce::Sku } + + let(:params) { 1 } + + describe '.count' do + it 'should hit the correct path' do + expect(@sku).to receive(:get).with('products/1/skus/count') + @sku.count params + end + end + + describe '.count_all' do + it 'should hit the correct path' do + expect(@sku).to receive(:get).with('products/skus/count') + @sku.count_all + end + end +end diff --git a/spec/bigcommerce/unit/resources/resource_spec.rb b/spec/bigcommerce/unit/resources/resource_spec.rb new file mode 100644 index 0000000..9746939 --- /dev/null +++ b/spec/bigcommerce/unit/resources/resource_spec.rb @@ -0,0 +1,4 @@ +require 'spec_helper' + +describe Bigcommerce::Resource do +end diff --git a/spec/bigcommerce/unit/resources/store_info/store_information_spec.rb b/spec/bigcommerce/unit/resources/store_info/store_information_spec.rb new file mode 100644 index 0000000..c8eaf23 --- /dev/null +++ b/spec/bigcommerce/unit/resources/store_info/store_information_spec.rb @@ -0,0 +1,12 @@ +require 'spec_helper' + +describe Bigcommerce::StoreInfo do + before(:each) { @store_info = Bigcommerce::StoreInfo } + + describe '.info' do + it 'should hit the correct path' do + expect(@store_info).to receive(:get).with(@store_info.path.build) + @store_info.info + end + end +end diff --git a/spec/bigcommerce/unit/resources/system/time_spec.rb b/spec/bigcommerce/unit/resources/system/time_spec.rb new file mode 100644 index 0000000..756e511 --- /dev/null +++ b/spec/bigcommerce/unit/resources/system/time_spec.rb @@ -0,0 +1,12 @@ +require 'spec_helper' + +describe Bigcommerce::System do + before(:each) { @system = Bigcommerce::System } + + describe '.time' do + it 'should hit the correct path' do + expect(@system).to receive(:get).with(@system.path.build) + @system.time + end + end +end diff --git a/spec/bigcommerce/unit/version_spec.rb b/spec/bigcommerce/unit/version_spec.rb new file mode 100644 index 0000000..73b74c9 --- /dev/null +++ b/spec/bigcommerce/unit/version_spec.rb @@ -0,0 +1,7 @@ +require 'spec_helper' + +describe 'Bigcommerce::VERSION' do + it 'is not nil' do + expect(Bigcommerce::VERSION).not_to be_nil + end +end diff --git a/spec/fixtures/api/v2/orders/filters_orders_by_date.yml b/spec/fixtures/api/v2/orders/filters_orders_by_date.yml deleted file mode 100644 index 3756e2b..0000000 --- a/spec/fixtures/api/v2/orders/filters_orders_by_date.yml +++ /dev/null @@ -1,47 +0,0 @@ ---- -http_interactions: -- request: - method: get - uri: https://:@store-vnh06c71.mybigcommerce.com/api/v2/orders.json?min_date_created=Fri,%2001%20Mar%202013%2000:00:00%20%2B0000 - body: - encoding: US-ASCII - string: '' - headers: - Accept: - - application/json - Accept-Encoding: - - gzip, deflate - Content-Type: - - application/json - User-Agent: - - Ruby - response: - status: - code: 200 - message: OK - headers: - Date: - - Mon, 22 Apr 2013 10:18:49 GMT - Server: - - Apache - X-Bc-Apilimit-Remaining: - - '19996' - X-Bc-Store-Version: - - 7.5.19 - Last-Modified: - - Sun, 24 Mar 2013 23:07:53 GMT - X-Powered-By: - - PleskLin - Transfer-Encoding: - - chunked - Content-Type: - - application/json - body: - encoding: US-ASCII - string: ! '[{"id":100,"customer_id":1,"date_created":"Sun, 24 Mar 2013 23:07:53 - +0000","date_modified":"Sun, 24 Mar 2013 23:07:53 +0000","date_shipped":"","status_id":11,"status":"Awaiting - Fulfillment","subtotal_ex_tax":"158.9500","subtotal_inc_tax":"158.9500","subtotal_tax":"0.0000","base_shipping_cost":"0.0000","shipping_cost_ex_tax":"0.0000","shipping_cost_inc_tax":"0.0000","shipping_cost_tax":"0.0000","shipping_cost_tax_class_id":2,"base_handling_cost":"0.0000","handling_cost_ex_tax":"0.0000","handling_cost_inc_tax":"0.0000","handling_cost_tax":"0.0000","handling_cost_tax_class_id":2,"base_wrapping_cost":"0.0000","wrapping_cost_ex_tax":"0.0000","wrapping_cost_inc_tax":"0.0000","wrapping_cost_tax":"0.0000","wrapping_cost_tax_class_id":3,"total_ex_tax":"158.9500","total_inc_tax":"158.9500","total_tax":"0.0000","items_total":3,"items_shipped":0,"payment_method":"","payment_provider_id":null,"payment_status":"","refunded_amount":"0.0000","order_is_digital":false,"store_credit_amount":"0.0000","gift_certificate_amount":"0.0000","ip_address":"101.164.35.146","geoip_country":"","geoip_country_iso2":"","currency_id":1,"currency_code":"USD","currency_exchange_rate":"1.0000000000","default_currency_id":1,"default_currency_code":"USD","staff_notes":"","customer_message":"","discount_amount":"0.0000","coupon_discount":"0.0000","shipping_address_count":1,"is_deleted":false,"billing_address":{"first_name":"","last_name":"","company":"","street_1":"","street_2":"","city":"","state":"Florida","zip":"94041","country":"United - States","country_iso2":"US","phone":"","email":"test.customer@foobar.xyz.com"},"products":{"url":"https:\/\/store-vnh06c71.mybigcommerce.com\/api\/v2\/orders\/100\/products.json","resource":"\/orders\/100\/products"},"shipping_addresses":{"url":"https:\/\/store-vnh06c71.mybigcommerce.com\/api\/v2\/orders\/100\/shippingaddresses.json","resource":"\/orders\/100\/shippingaddresses"},"coupons":{"url":"https:\/\/store-vnh06c71.mybigcommerce.com\/api\/v2\/orders\/100\/coupons.json","resource":"\/orders\/100\/coupons"}}]' - http_version: - recorded_at: Mon, 22 Apr 2013 10:18:49 GMT -recorded_with: VCR 2.4.0 diff --git a/spec/fixtures/api/v2/orders/gets_the_orders_collection.yml b/spec/fixtures/api/v2/orders/gets_the_orders_collection.yml deleted file mode 100644 index 4e75ccd..0000000 --- a/spec/fixtures/api/v2/orders/gets_the_orders_collection.yml +++ /dev/null @@ -1,47 +0,0 @@ ---- -http_interactions: -- request: - method: get - uri: https://:@store-vnh06c71.mybigcommerce.com/api/v2/orders.json - body: - encoding: US-ASCII - string: '' - headers: - Accept: - - application/json - Accept-Encoding: - - gzip, deflate - Content-Type: - - application/json - User-Agent: - - Ruby - response: - status: - code: 200 - message: OK - headers: - Date: - - Mon, 22 Apr 2013 10:18:47 GMT - Server: - - Apache - X-Bc-Apilimit-Remaining: - - '19997' - X-Bc-Store-Version: - - 7.5.19 - Last-Modified: - - Sun, 24 Mar 2013 23:07:53 GMT - X-Powered-By: - - PleskLin - Transfer-Encoding: - - chunked - Content-Type: - - application/json - body: - encoding: US-ASCII - string: ! '[{"id":100,"customer_id":1,"date_created":"Sun, 24 Mar 2013 23:07:53 - +0000","date_modified":"Sun, 24 Mar 2013 23:07:53 +0000","date_shipped":"","status_id":11,"status":"Awaiting - Fulfillment","subtotal_ex_tax":"158.9500","subtotal_inc_tax":"158.9500","subtotal_tax":"0.0000","base_shipping_cost":"0.0000","shipping_cost_ex_tax":"0.0000","shipping_cost_inc_tax":"0.0000","shipping_cost_tax":"0.0000","shipping_cost_tax_class_id":2,"base_handling_cost":"0.0000","handling_cost_ex_tax":"0.0000","handling_cost_inc_tax":"0.0000","handling_cost_tax":"0.0000","handling_cost_tax_class_id":2,"base_wrapping_cost":"0.0000","wrapping_cost_ex_tax":"0.0000","wrapping_cost_inc_tax":"0.0000","wrapping_cost_tax":"0.0000","wrapping_cost_tax_class_id":3,"total_ex_tax":"158.9500","total_inc_tax":"158.9500","total_tax":"0.0000","items_total":3,"items_shipped":0,"payment_method":"","payment_provider_id":null,"payment_status":"","refunded_amount":"0.0000","order_is_digital":false,"store_credit_amount":"0.0000","gift_certificate_amount":"0.0000","ip_address":"101.164.35.146","geoip_country":"","geoip_country_iso2":"","currency_id":1,"currency_code":"USD","currency_exchange_rate":"1.0000000000","default_currency_id":1,"default_currency_code":"USD","staff_notes":"","customer_message":"","discount_amount":"0.0000","coupon_discount":"0.0000","shipping_address_count":1,"is_deleted":false,"billing_address":{"first_name":"","last_name":"","company":"","street_1":"","street_2":"","city":"","state":"Florida","zip":"94041","country":"United - States","country_iso2":"US","phone":"","email":"test.customer@foobar.xyz.com"},"products":{"url":"https:\/\/store-vnh06c71.mybigcommerce.com\/api\/v2\/orders\/100\/products.json","resource":"\/orders\/100\/products"},"shipping_addresses":{"url":"https:\/\/store-vnh06c71.mybigcommerce.com\/api\/v2\/orders\/100\/shippingaddresses.json","resource":"\/orders\/100\/shippingaddresses"},"coupons":{"url":"https:\/\/store-vnh06c71.mybigcommerce.com\/api\/v2\/orders\/100\/coupons.json","resource":"\/orders\/100\/coupons"}}]' - http_version: - recorded_at: Mon, 22 Apr 2013 10:18:47 GMT -recorded_with: VCR 2.4.0 diff --git a/spec/fixtures/brands.json b/spec/fixtures/brands.json deleted file mode 100644 index 7ba632e..0000000 --- a/spec/fixtures/brands.json +++ /dev/null @@ -1,9 +0,0 @@ -[{ - "id": 10, - "name": "Xmen", - "page_title": "X men brand", - "meta_keywords": null, - "meta_description": null, - "image_file": "t/apirmzk0a__43675.jpg", - "search_keywords": "xmen, awesomeness" -}] \ No newline at end of file diff --git a/spec/fixtures/categories.json b/spec/fixtures/categories.json deleted file mode 100644 index 019c0d3..0000000 --- a/spec/fixtures/categories.json +++ /dev/null @@ -1,20 +0,0 @@ -[ - { - "id": 1, - "parent_id": 0, - "name": "Shop Mac", - "description": "", - "sort_order": 0, - "page_title": "", - "meta_keywords": "", - "meta_description": "", - "layout_file": "category.html", - "parent_category_list": [ - 1 - ], - "image_file": "", - "is_visible": true, - "search_keywords": "", - "url": "/shop-mac/" - } -] \ No newline at end of file diff --git a/spec/fixtures/countries.json b/spec/fixtures/countries.json deleted file mode 100644 index f6154e1..0000000 --- a/spec/fixtures/countries.json +++ /dev/null @@ -1,10 +0,0 @@ -[{ - "id": 226, - "country": "United States", - "country_iso2": "US", - "country_iso3": "USA", - "states": { - "url": "https://store-bwvr466.mybigcommerce.com/api/v2/countries/226/states.json", - "resource": "/countries/226/states" - } - }] \ No newline at end of file diff --git a/spec/fixtures/order.json b/spec/fixtures/order.json deleted file mode 100644 index a1c68e0..0000000 --- a/spec/fixtures/order.json +++ /dev/null @@ -1 +0,0 @@ -[{"id":100,"customer_id":1,"date_created":"Fri, 02 Mar 2012 21:36:24 +0000","date_modified":"Mon, 12 Mar 2012 21:40:16 +0000","date_shipped":"Fri, 02 Mar 2012 21:36:56 +0000","status_id":11,"status":"Awaiting Fulfillment","subtotal_ex_tax":"0.0100","subtotal_inc_tax":"0.0100","subtotal_tax":"0.0000","base_shipping_cost":"0.0000","shipping_cost_ex_tax":"0.0000","shipping_cost_inc_tax":"0.0000","shipping_cost_tax":"0.0000","shipping_cost_tax_class_id":2,"base_handling_cost":"0.0000","handling_cost_ex_tax":"0.0000","handling_cost_inc_tax":"0.0000","handling_cost_tax":"0.0000","handling_cost_tax_class_id":2,"base_wrapping_cost":"0.0000","wrapping_cost_ex_tax":"0.0000","wrapping_cost_inc_tax":"0.0000","wrapping_cost_tax":"0.0000","wrapping_cost_tax_class_id":3,"total_ex_tax":"0.0100","total_inc_tax":"0.0100","total_tax":"0.0000","items_total":1,"items_shipped":0,"payment_method":"Pay in Store","payment_provider_id":null,"payment_status":"","refunded_amount":"0.0000","order_is_digital":true,"store_credit_amount":"0.0000","gift_certificate_amount":"0.0000","ip_address":"127.0.0.1","geoip_country":"United States","geoip_country_iso2":"US","currency_id":1,"currency_code":"USD","currency_exchange_rate":"1.0000000000","default_currency_id":1,"default_currency_code":"USD","staff_notes":"","customer_message":"","discount_amount":"0.0000","coupon_discount":"0.0000","shipping_address_count":0,"is_deleted":false,"billing_address":{"first_name":"Bugs","last_name":"Bunny","company":"","street_1":"1 Main Street","street_2":"","city":"Walla Walla","state":"WA","zip":"99362","country":"United States","country_iso2":"US","phone":"5555556789","email":"bug@bunny.com"},"products":{"url":"https:\/\/store-12345.mybigcommerce.com\/api\/v2\/orders\/100\/products.json","resource":"\/orders\/100\/products"},"shipping_addresses":{"url":"https:\/\/store-12345.mybigcommerce.com\/api\/v2\/orders\/100\/shippingaddresses.json","resource":"\/orders\/100\/shippingaddresses"},"coupons":{"url":"https:\/\/store-12345.mybigcommerce.com\/api\/v2\/orders\/100\/coupons.json","resource":"\/orders\/100\/coupons"}}] \ No newline at end of file diff --git a/spec/fixtures/time.json b/spec/fixtures/time.json deleted file mode 100644 index ebdc7e4..0000000 --- a/spec/fixtures/time.json +++ /dev/null @@ -1 +0,0 @@ -{"time":1331667176} \ No newline at end of file diff --git a/spec/integration/orders_spec.rb b/spec/integration/orders_spec.rb deleted file mode 100644 index f3d53c7..0000000 --- a/spec/integration/orders_spec.rb +++ /dev/null @@ -1,18 +0,0 @@ -require 'spec_helper' - -describe "/api/v2/orders" do - include_context "integration" - - it "gets the orders collection", :vcr do - orders = api.orders - orders.should be_a_kind_of(Enumerable) - orders.size.should be > 0 - end - - it "filters orders by date", :vcr do - orders = api.orders_by_date('2013-03-01') - orders.should be_a_kind_of(Enumerable) - orders.size.should be > 0 - end - -end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 4e20999..aef67f0 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,27 +1,11 @@ -begin - require 'coveralls' - Coveralls.wear! -rescue LoadError => e - raise e -end +require 'coveralls' +Coveralls.wear! -require 'bigcommerce' -require 'date' -require 'vcr' -require 'webmock/rspec' - -# Requires supporting ruby files with custom matchers and macros, etc, -# in spec/support/ and its subdirectories. -Dir[File.dirname(__FILE__) + "/support/**/*.rb"].each {|f| require f } +SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter[ + Coveralls::SimpleCov::Formatter, + SimpleCov::Formatter::HTMLFormatter +] +SimpleCov.start { add_filter '/spec/' } -VCR.configure do |c| - c.cassette_library_dir = 'spec/fixtures' - c.hook_into :webmock - c.configure_rspec_metadata! - c.filter_sensitive_data('') { ENV['API_USER'] } - c.filter_sensitive_data('') { ENV['API_PASS'] } -end - -RSpec.configure do |c| - c.treat_symbols_as_metadata_keys_with_true_values = true -end +require 'rspec' +require 'bigcommerce' diff --git a/spec/support/integration_context.rb b/spec/support/integration_context.rb deleted file mode 100644 index 8e42a80..0000000 --- a/spec/support/integration_context.rb +++ /dev/null @@ -1,13 +0,0 @@ -shared_context "integration" do - let :api do - ENV['API_URL'] = ENV['API_URL'] || 'https://store-vnh06c71.mybigcommerce.com' - ENV['API_USER'] = ENV['API_USER'] || 'apiuser' - ENV['API_PASS'] = ENV['API_PASS'] || '123456' - - Bigcommerce::Api.new({ - :store_url => ENV['API_URL'], - :username => ENV['API_USER'], - :api_key => ENV['API_PASS'] - }) - end -end \ No newline at end of file diff --git a/spec/support/mock_api_context.rb b/spec/support/mock_api_context.rb deleted file mode 100644 index 7e16b5b..0000000 --- a/spec/support/mock_api_context.rb +++ /dev/null @@ -1,10 +0,0 @@ -shared_context "mock api" do - let :api do - connection = double(Bigcommerce::Connection) - api = Bigcommerce::Api.new - api.instance_eval do - @connection = connection - end - api - end -end diff --git a/spec/unit/api_request_spec.rb b/spec/unit/api_request_spec.rb deleted file mode 100644 index ed4e121..0000000 --- a/spec/unit/api_request_spec.rb +++ /dev/null @@ -1,34 +0,0 @@ -describe "API request delegation" do - include_context "mock api" - - it "requests a resource" do - api.connection.should_receive(:get).once.with("/time") - api.time - end - - it "requests a resource by id" do - api.connection.should_receive(:get).once.with("/products/333", {}) - api.product(333) - end - - it "requests a compound resource by ids" do - api.connection.should_receive(:get).once.with("/orders/999/products/333", {}) - api.orders_product(999, 333) - end - - it "requests a resource with pagination" do - api.connection.should_receive(:get).once.with("/orders", {:page => 2}) - api.orders(:page => 2) - end - - it "requests a resource with limit" do - api.connection.should_receive(:get).once.with("/categories", {:limit => 10}) - api.categories(:limit => 10) - end - - it "request a resource with pagination and limit" do - api.connection.should_receive(:get).once.with("/customers", {:limit => 10, :page => 2}) - api.customers(:limit => 10, :page => 2) - end - -end diff --git a/spec/unit/api_spec.rb b/spec/unit/api_spec.rb deleted file mode 100644 index 0770782..0000000 --- a/spec/unit/api_spec.rb +++ /dev/null @@ -1,49 +0,0 @@ -require 'spec_helper' - -describe Bigcommerce::Api do - include_context "mock api" - - describe "orders_by_date" do - it "should accept a valid Date object" do - date = DateTime.now - parsed_date = described_class.new.to_rfc2822(date) - api.connection.should_receive(:get).once.with("/orders", - {:min_date_created => parsed_date}) - api.orders_by_date(date) - end - - it "should parse a valid date string" do - date = described_class.new.to_rfc2822(DateTime.parse('2012-1-1')) - api.connection.should_receive(:get).once.with("/orders", - {:min_date_created => date}) - api.orders_by_date('2012-1-1') - end - end - - describe "#create-orders-shipments" do - it "should accept an order id parameter" do - api.connection.should_receive(:post).once.with("/orders/123/shipments", {}) - api.create_orders_shipments(123) - end - - it "should accept an order id parameter and an options hash" do - options = Hash[*('A'..'Z').to_a.flatten] - api.connection.should_receive(:post).once.with("/orders/123/shipments", options) - api.create_orders_shipments(123, options) - end - end - - describe "#get-options-value" do - it "should accept an option id parameter" do - api.connection.should_receive(:get).once.with("/options/123/values", {}) - api.options_value(123) - end - - it "should accept an option id parameter and an options hash" do - options = Hash[*('A'..'Z').to_a.flatten] - api.connection.should_receive(:get).once.with("/options/123/values", options) - api.options_value(123, options) - end - end - -end diff --git a/spec/unit/connection_spec.rb b/spec/unit/connection_spec.rb deleted file mode 100644 index 6c81c17..0000000 --- a/spec/unit/connection_spec.rb +++ /dev/null @@ -1,23 +0,0 @@ -require 'spec_helper' - -shared_examples_for "request method accepting optional params and headers" do - it "sends request with no params" do - connection.should_receive(:request).once.with(http_method, path, {}, {}) - connection.send(http_method, path) - end - - it "sends request with params" do - connection.should_receive(:request).once.with(http_method, path, {:page => 3}, {}) - connection.send(http_method, path, {:page => 3}) - end - - it "sends request with headers" do - connection.should_receive(:request).once.with(http_method, "/orders", {}, {'Some-Header' => 'abc'}) - connection.send(http_method, path, {}, {'Some-Header' => 'abc'}) - end - - it "sends request with params and headers" do - connection.should_receive(:request).once.with(http_method, "/orders", {:page => 6}, {'Some-Header' => 'abc'}) - connection.send(http_method, path, {:page => 6}, {'Some-Header' => 'abc'}) - end -end diff --git a/spec/unit/date_time_spec.rb b/spec/unit/date_time_spec.rb deleted file mode 100644 index 9f50c14..0000000 --- a/spec/unit/date_time_spec.rb +++ /dev/null @@ -1,31 +0,0 @@ -require 'spec_helper' - -describe Bigcommerce::Api do - - let(:api) do - Bigcommerce::Api.new({ - :store_url => "https://store-12345.mybigcommerce.com", - :username => "test", :api_key => "12345" - }) - end - - let(:rfc2822_datetime) { "Tue, 13 Mar 2012 12:45:26 +0000" } - let(:rfc2822_date) { "Mon, 12 Mar 2012 00:00:00 +0000" } - - describe "RFC 2822 DateTime format" do - - it "converts raw date times to RFC 2822 format" do - api.to_rfc2822(DateTime.parse('2012-03-13 12:45:26 +0000')).should eql rfc2822_datetime - end - - it "converts textual date times to RFC 2822 format" do - api.to_rfc2822(DateTime.parse('12th March 2012')).should eql rfc2822_date - end - - it "converts ISO 8601 dates to RFC 2822 format" do - api.to_rfc2822(DateTime.parse('2012-03-12')).should eql rfc2822_date - end - - end - -end diff --git a/spec/unit/version_spec.rb b/spec/unit/version_spec.rb deleted file mode 100644 index 4cc5e1b..0000000 --- a/spec/unit/version_spec.rb +++ /dev/null @@ -1,13 +0,0 @@ -require 'spec_helper' - -describe Bigcommerce do - describe 'VERSION' do - it "should have a version number set" do - expect(Bigcommerce::VERSION).to_not be_nil - end - - it "should use a semantic version format" do - expect(Bigcommerce::VERSION).to match(/\d+\.\d+\.\d+(rc\d?)?/) - end - end -end