From 695ca1d55390dc027588204c5bd89486cdc8d778 Mon Sep 17 00:00:00 2001 From: Patryk Tomczyk <13100280+patzick@users.noreply.github.com> Date: Thu, 31 Oct 2024 17:19:36 +0100 Subject: [PATCH] chore: remove deprecated api client package (#1409) --- .changeset/eighty-emus-dance.md | 2 +- .github/dependabot.yml | 2 - packages/api-client-old/CHANGELOG.md | 178 ------- packages/api-client-old/README.md | 25 - packages/api-client-old/build.config.ts | 18 - packages/api-client-old/eslint.config.mjs | 3 - packages/api-client-old/package.json | 57 -- packages/api-client-old/src/apiService.ts | 154 ------ packages/api-client-old/src/endpoints.spec.ts | 288 ---------- packages/api-client-old/src/endpoints.ts | 451 ---------------- .../api-client-old/src/helpers/context.ts | 9 - .../src/helpers/queryParamsBuilder.spec.ts | 20 - .../src/helpers/queryParamsBuilder.ts | 16 - packages/api-client-old/src/index.ts | 47 -- .../src/interceptors/apiInterceptors.spec.ts | 302 ----------- .../src/interceptors/errorInterceptor.ts | 101 ---- .../api-client-old/src/interceptors/index.ts | 2 - .../src/interceptors/responseInterceptor.ts | 18 - .../CartServiceTests/addCartItems.spec.ts | 42 -- .../CartServiceTests/addProductToCart.spec.ts | 127 ----- .../CartServiceTests/addPromotionCode.spec.ts | 58 --- .../changeCartItemQuantity.spec.ts | 101 ---- .../CartServiceTests/clearCart.spec.ts | 30 -- .../services/CartServiceTests/getCart.spec.ts | 50 -- .../CartServiceTests/removeCartItem.spec.ts | 54 -- .../getCategories.spec.ts | 27 - .../CategoryServiceTests/getCategory.spec.ts | 34 -- .../CheckoutServiceTests/cancelOrder.spec.ts | 28 - .../changeOrderPaymentMethod.spec.ts | 32 -- .../CheckoutServiceTests/createOrder.spec.ts | 53 -- .../getOrderDetails.spec.ts | 49 -- .../getStoreOrderPaymentUrl.spec.ts | 133 ----- .../getAvailableCountries.spec.ts | 28 - .../getAvailableCurrencies.spec.ts | 23 - .../getAvailableLanguages.spec.ts | 24 - .../getAvailablePaymentMethods.spec.ts | 26 - .../getAvailableSalutations.spec.ts | 24 - .../getAvailableShippingMethods.spec.ts | 24 - .../getPaymentMethodDetails.spec.ts | 43 -- .../getSessionContext.spec.ts | 24 - .../getShippingMethodDetails.spec.ts | 43 -- .../getUserCountry.spec.ts | 38 -- .../getUserSalutation.spec.ts | 37 -- .../setCurrentBillingAddress.spec.ts | 62 --- .../setCurrentCountry.spec.ts | 62 --- .../setCurrentCurrency.spec.ts | 63 --- .../setCurrentLanguage.spec.ts | 63 --- .../setCurrentPaymentMethod.spec.ts | 63 --- .../setCurrentShippingAddress.spec.ts | 62 --- .../setCurrentShippingMethod.spec.ts | 63 --- .../confirmAccountRegistration.spec.ts | 70 --- .../confirmPasswordReset.spec.ts | 88 ---- .../createCustomerAddress.spec.ts | 39 -- .../deleteCustomerAddress.spec.ts | 40 -- .../CustomerServiceTests/getCustomer.spec.ts | 50 -- .../getCustomerAddress.spec.ts | 40 -- .../getCustomerAddresses.spec.ts | 24 - .../getCustomerOrders.spec.ts | 56 -- .../isNewsletterSubscriber.spec.ts | 29 -- .../CustomerServiceTests/login.spec.ts | 83 --- .../CustomerServiceTests/logout.spec.ts | 24 - .../CustomerServiceTests/register.spec.ts | 63 --- .../resetPassword.spec.ts | 86 --- .../setDefaultCustomerBillingAddress.spec.ts | 39 -- .../setDefaultCustomerPaymentMethod.spec.ts | 39 -- .../setDefaultCustomerShippingAddress.spec.ts | 39 -- .../updateCustomerAddress.spec.ts | 41 -- .../CustomerServiceTests/updateEmail.spec.ts | 58 --- .../updatePassword.spec.ts | 77 --- .../updateProfile.spec.ts | 37 -- .../getDocumentDownload.spec.ts | 29 -- .../newsletterSubscribe.spec.ts | 38 -- .../newsletterUnubscribe.spec.ts | 31 -- .../FormServiceTests/sendContactForm.spec.ts | 44 -- .../getStoreNavigation.spec.ts | 37 -- .../newsletterConfirmation.spec.ts | 30 -- .../getOrderDownloads.spec.ts | 29 -- .../PageServiceTests/getCmsPage.spec.ts | 44 -- .../PageServiceTests/getLandingPage.spec.ts | 33 -- .../PageServiceTests/getSeoUrl.spec.ts | 29 -- .../PageServiceTests/getSeoUrls.spec.ts | 58 --- .../PageServiceTests/getSwCmsPage.spec.ts | 23 - .../PluginServiceTests/invokePost.spec.ts | 50 -- .../addProductReview.spec.ts | 48 -- .../getCategoryProducts.spec.ts | 44 -- .../ProductServiceTests/getProduct.spec.ts | 29 -- .../getProductCrossSelling.spec.ts | 29 -- .../getProductReviews.spec.ts | 29 -- .../getProductVariantForOptions.spec.ts | 48 -- .../ProductServiceTests/getProducts.spec.ts | 60 --- .../SearchServiceTests/searchProducts.spec.ts | 43 -- .../searchSuggestedProducts.spec.ts | 49 -- .../SitemapServiceTests/getSitemap.spec.ts | 24 - .../addWishlistProduct.spec.ts | 28 - .../getWishlistProducts.spec.ts | 32 -- .../mergeWishlistProducts.spec.ts | 31 -- .../removeWishlistProduct.spec.ts | 28 - .../src/services/cartService.ts | 196 ------- .../src/services/categoryService.ts | 49 -- .../src/services/checkoutService.ts | 158 ------ .../src/services/contextService.ts | 448 ---------------- .../src/services/customerService.ts | 493 ------------------ .../src/services/documentService.ts | 28 - .../src/services/formsService.ts | 122 ----- .../src/services/navigationService.ts | 54 -- .../src/services/newsletterService.ts | 27 - .../src/services/orderService.ts | 29 -- .../src/services/pageService.ts | 132 ----- .../src/services/pluginService.ts | 43 -- .../src/services/productService.ts | 169 ------ .../src/services/searchService.ts | 54 -- .../src/services/sitemapService.ts | 16 - .../src/services/wishlistService.ts | 113 ---- packages/api-client-old/src/settings.spec.ts | 156 ------ packages/api-client-old/src/settings.ts | 38 -- packages/api-client-old/tsconfig.json | 12 - packages/api-client-old/types/api-types.ts | 19 - packages/api-client-old/vitest.config.ts | 14 - packages/nuxt3-module/README.md | 2 +- pnpm-lock.yaml | 92 +--- 120 files changed, 5 insertions(+), 7761 deletions(-) delete mode 100644 packages/api-client-old/CHANGELOG.md delete mode 100644 packages/api-client-old/README.md delete mode 100644 packages/api-client-old/build.config.ts delete mode 100644 packages/api-client-old/eslint.config.mjs delete mode 100644 packages/api-client-old/package.json delete mode 100644 packages/api-client-old/src/apiService.ts delete mode 100644 packages/api-client-old/src/endpoints.spec.ts delete mode 100644 packages/api-client-old/src/endpoints.ts delete mode 100644 packages/api-client-old/src/helpers/context.ts delete mode 100644 packages/api-client-old/src/helpers/queryParamsBuilder.spec.ts delete mode 100644 packages/api-client-old/src/helpers/queryParamsBuilder.ts delete mode 100644 packages/api-client-old/src/index.ts delete mode 100644 packages/api-client-old/src/interceptors/apiInterceptors.spec.ts delete mode 100644 packages/api-client-old/src/interceptors/errorInterceptor.ts delete mode 100644 packages/api-client-old/src/interceptors/index.ts delete mode 100644 packages/api-client-old/src/interceptors/responseInterceptor.ts delete mode 100644 packages/api-client-old/src/services/CartServiceTests/addCartItems.spec.ts delete mode 100644 packages/api-client-old/src/services/CartServiceTests/addProductToCart.spec.ts delete mode 100644 packages/api-client-old/src/services/CartServiceTests/addPromotionCode.spec.ts delete mode 100644 packages/api-client-old/src/services/CartServiceTests/changeCartItemQuantity.spec.ts delete mode 100644 packages/api-client-old/src/services/CartServiceTests/clearCart.spec.ts delete mode 100644 packages/api-client-old/src/services/CartServiceTests/getCart.spec.ts delete mode 100644 packages/api-client-old/src/services/CartServiceTests/removeCartItem.spec.ts delete mode 100644 packages/api-client-old/src/services/CategoryServiceTests/getCategories.spec.ts delete mode 100644 packages/api-client-old/src/services/CategoryServiceTests/getCategory.spec.ts delete mode 100644 packages/api-client-old/src/services/CheckoutServiceTests/cancelOrder.spec.ts delete mode 100644 packages/api-client-old/src/services/CheckoutServiceTests/changeOrderPaymentMethod.spec.ts delete mode 100644 packages/api-client-old/src/services/CheckoutServiceTests/createOrder.spec.ts delete mode 100644 packages/api-client-old/src/services/CheckoutServiceTests/getOrderDetails.spec.ts delete mode 100644 packages/api-client-old/src/services/CheckoutServiceTests/getStoreOrderPaymentUrl.spec.ts delete mode 100644 packages/api-client-old/src/services/ContextServiceTests/getAvailableCountries.spec.ts delete mode 100644 packages/api-client-old/src/services/ContextServiceTests/getAvailableCurrencies.spec.ts delete mode 100644 packages/api-client-old/src/services/ContextServiceTests/getAvailableLanguages.spec.ts delete mode 100644 packages/api-client-old/src/services/ContextServiceTests/getAvailablePaymentMethods.spec.ts delete mode 100644 packages/api-client-old/src/services/ContextServiceTests/getAvailableSalutations.spec.ts delete mode 100644 packages/api-client-old/src/services/ContextServiceTests/getAvailableShippingMethods.spec.ts delete mode 100644 packages/api-client-old/src/services/ContextServiceTests/getPaymentMethodDetails.spec.ts delete mode 100644 packages/api-client-old/src/services/ContextServiceTests/getSessionContext.spec.ts delete mode 100644 packages/api-client-old/src/services/ContextServiceTests/getShippingMethodDetails.spec.ts delete mode 100644 packages/api-client-old/src/services/ContextServiceTests/getUserCountry.spec.ts delete mode 100644 packages/api-client-old/src/services/ContextServiceTests/getUserSalutation.spec.ts delete mode 100644 packages/api-client-old/src/services/ContextServiceTests/setCurrentBillingAddress.spec.ts delete mode 100644 packages/api-client-old/src/services/ContextServiceTests/setCurrentCountry.spec.ts delete mode 100644 packages/api-client-old/src/services/ContextServiceTests/setCurrentCurrency.spec.ts delete mode 100644 packages/api-client-old/src/services/ContextServiceTests/setCurrentLanguage.spec.ts delete mode 100644 packages/api-client-old/src/services/ContextServiceTests/setCurrentPaymentMethod.spec.ts delete mode 100644 packages/api-client-old/src/services/ContextServiceTests/setCurrentShippingAddress.spec.ts delete mode 100644 packages/api-client-old/src/services/ContextServiceTests/setCurrentShippingMethod.spec.ts delete mode 100644 packages/api-client-old/src/services/CustomerServiceTests/confirmAccountRegistration.spec.ts delete mode 100644 packages/api-client-old/src/services/CustomerServiceTests/confirmPasswordReset.spec.ts delete mode 100644 packages/api-client-old/src/services/CustomerServiceTests/createCustomerAddress.spec.ts delete mode 100644 packages/api-client-old/src/services/CustomerServiceTests/deleteCustomerAddress.spec.ts delete mode 100644 packages/api-client-old/src/services/CustomerServiceTests/getCustomer.spec.ts delete mode 100644 packages/api-client-old/src/services/CustomerServiceTests/getCustomerAddress.spec.ts delete mode 100644 packages/api-client-old/src/services/CustomerServiceTests/getCustomerAddresses.spec.ts delete mode 100644 packages/api-client-old/src/services/CustomerServiceTests/getCustomerOrders.spec.ts delete mode 100644 packages/api-client-old/src/services/CustomerServiceTests/isNewsletterSubscriber.spec.ts delete mode 100644 packages/api-client-old/src/services/CustomerServiceTests/login.spec.ts delete mode 100644 packages/api-client-old/src/services/CustomerServiceTests/logout.spec.ts delete mode 100644 packages/api-client-old/src/services/CustomerServiceTests/register.spec.ts delete mode 100644 packages/api-client-old/src/services/CustomerServiceTests/resetPassword.spec.ts delete mode 100644 packages/api-client-old/src/services/CustomerServiceTests/setDefaultCustomerBillingAddress.spec.ts delete mode 100644 packages/api-client-old/src/services/CustomerServiceTests/setDefaultCustomerPaymentMethod.spec.ts delete mode 100644 packages/api-client-old/src/services/CustomerServiceTests/setDefaultCustomerShippingAddress.spec.ts delete mode 100644 packages/api-client-old/src/services/CustomerServiceTests/updateCustomerAddress.spec.ts delete mode 100644 packages/api-client-old/src/services/CustomerServiceTests/updateEmail.spec.ts delete mode 100644 packages/api-client-old/src/services/CustomerServiceTests/updatePassword.spec.ts delete mode 100644 packages/api-client-old/src/services/CustomerServiceTests/updateProfile.spec.ts delete mode 100644 packages/api-client-old/src/services/DocumentServiceTests/getDocumentDownload.spec.ts delete mode 100644 packages/api-client-old/src/services/FormServiceTests/newsletterSubscribe.spec.ts delete mode 100644 packages/api-client-old/src/services/FormServiceTests/newsletterUnubscribe.spec.ts delete mode 100644 packages/api-client-old/src/services/FormServiceTests/sendContactForm.spec.ts delete mode 100644 packages/api-client-old/src/services/NavigationServiceTests/getStoreNavigation.spec.ts delete mode 100644 packages/api-client-old/src/services/NewsletterServiceTests/newsletterConfirmation.spec.ts delete mode 100644 packages/api-client-old/src/services/OrderServiceTests/getOrderDownloads.spec.ts delete mode 100644 packages/api-client-old/src/services/PageServiceTests/getCmsPage.spec.ts delete mode 100644 packages/api-client-old/src/services/PageServiceTests/getLandingPage.spec.ts delete mode 100644 packages/api-client-old/src/services/PageServiceTests/getSeoUrl.spec.ts delete mode 100644 packages/api-client-old/src/services/PageServiceTests/getSeoUrls.spec.ts delete mode 100644 packages/api-client-old/src/services/PageServiceTests/getSwCmsPage.spec.ts delete mode 100644 packages/api-client-old/src/services/PluginServiceTests/invokePost.spec.ts delete mode 100644 packages/api-client-old/src/services/ProductServiceTests/addProductReview.spec.ts delete mode 100644 packages/api-client-old/src/services/ProductServiceTests/getCategoryProducts.spec.ts delete mode 100644 packages/api-client-old/src/services/ProductServiceTests/getProduct.spec.ts delete mode 100644 packages/api-client-old/src/services/ProductServiceTests/getProductCrossSelling.spec.ts delete mode 100644 packages/api-client-old/src/services/ProductServiceTests/getProductReviews.spec.ts delete mode 100644 packages/api-client-old/src/services/ProductServiceTests/getProductVariantForOptions.spec.ts delete mode 100644 packages/api-client-old/src/services/ProductServiceTests/getProducts.spec.ts delete mode 100644 packages/api-client-old/src/services/SearchServiceTests/searchProducts.spec.ts delete mode 100644 packages/api-client-old/src/services/SearchServiceTests/searchSuggestedProducts.spec.ts delete mode 100644 packages/api-client-old/src/services/SitemapServiceTests/getSitemap.spec.ts delete mode 100644 packages/api-client-old/src/services/WishlistServiceTests/addWishlistProduct.spec.ts delete mode 100644 packages/api-client-old/src/services/WishlistServiceTests/getWishlistProducts.spec.ts delete mode 100644 packages/api-client-old/src/services/WishlistServiceTests/mergeWishlistProducts.spec.ts delete mode 100644 packages/api-client-old/src/services/WishlistServiceTests/removeWishlistProduct.spec.ts delete mode 100644 packages/api-client-old/src/services/cartService.ts delete mode 100644 packages/api-client-old/src/services/categoryService.ts delete mode 100644 packages/api-client-old/src/services/checkoutService.ts delete mode 100644 packages/api-client-old/src/services/contextService.ts delete mode 100644 packages/api-client-old/src/services/customerService.ts delete mode 100644 packages/api-client-old/src/services/documentService.ts delete mode 100644 packages/api-client-old/src/services/formsService.ts delete mode 100644 packages/api-client-old/src/services/navigationService.ts delete mode 100644 packages/api-client-old/src/services/newsletterService.ts delete mode 100644 packages/api-client-old/src/services/orderService.ts delete mode 100644 packages/api-client-old/src/services/pageService.ts delete mode 100644 packages/api-client-old/src/services/pluginService.ts delete mode 100644 packages/api-client-old/src/services/productService.ts delete mode 100644 packages/api-client-old/src/services/searchService.ts delete mode 100644 packages/api-client-old/src/services/sitemapService.ts delete mode 100644 packages/api-client-old/src/services/wishlistService.ts delete mode 100644 packages/api-client-old/src/settings.spec.ts delete mode 100644 packages/api-client-old/src/settings.ts delete mode 100644 packages/api-client-old/tsconfig.json delete mode 100644 packages/api-client-old/types/api-types.ts delete mode 100644 packages/api-client-old/vitest.config.ts diff --git a/.changeset/eighty-emus-dance.md b/.changeset/eighty-emus-dance.md index 512248a25..04811ba95 100644 --- a/.changeset/eighty-emus-dance.md +++ b/.changeset/eighty-emus-dance.md @@ -1,5 +1,5 @@ --- -"@shopware-pwa/api-client": patch +"@shopware/api-client": patch --- Updated default schema to version `6.6.6.0` diff --git a/.github/dependabot.yml b/.github/dependabot.yml index f22b3121e..bc29d9b64 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -12,8 +12,6 @@ updates: open-pull-requests-limit: 3 versioning-strategy: "increase" ignore: - # used in old client, not upgrading - - dependency-name: "axios" # not upgrading until we move to new docs - dependency-name: "vitepress-shopware-docs" # until https://github.com/nuxt-modules/i18n/issues/2215 is resolved diff --git a/packages/api-client-old/CHANGELOG.md b/packages/api-client-old/CHANGELOG.md deleted file mode 100644 index ff2d27966..000000000 --- a/packages/api-client-old/CHANGELOG.md +++ /dev/null @@ -1,178 +0,0 @@ -# @shopware-pwa/api-client - -## 1.0.2 - -### Patch Changes - -- [#1089](https://github.com/shopware/frontends/pull/1089) [`db7c93f`](https://github.com/shopware/frontends/commit/db7c93ff8cbb581221c11a492e77068af8faa8d6) Thanks [@mkucmus](https://github.com/mkucmus)! - Migrate eslint config to flat format - -- Updated dependencies [[`db7c93f`](https://github.com/shopware/frontends/commit/db7c93ff8cbb581221c11a492e77068af8faa8d6)]: - - @shopware-pwa/types@1.0.2 - -## 1.0.1 - -### Patch Changes - -- Updated dependencies []: - - @shopware-pwa/types@1.0.1 - -## 1.0.0 - -### Major Changes - -- [#871](https://github.com/shopware/frontends/pull/871) [`1566f7a`](https://github.com/shopware/frontends/commit/1566f7a3962c511b5c72e12a4a5db40c4aa5d198) Thanks [@patzick](https://github.com/patzick)! - Read more about new major release: https://github.com/shopware/frontends/discussions/965 - -### Patch Changes - -- [#931](https://github.com/shopware/frontends/pull/931) [`3cc3d5e`](https://github.com/shopware/frontends/commit/3cc3d5e7b67522f8f7f1d9bed639f18d3e384239) Thanks [@mdanilowicz](https://github.com/mdanilowicz)! - Adjust formsService types - -- Updated dependencies [[`1566f7a`](https://github.com/shopware/frontends/commit/1566f7a3962c511b5c72e12a4a5db40c4aa5d198), [`543a8e1`](https://github.com/shopware/frontends/commit/543a8e1fb3b391a0238f329e0ead30b8322016ec)]: - - @shopware-pwa/types@1.0.0 - -## 0.7.0 - -### Minor Changes - -- [#453](https://github.com/shopware/frontends/pull/453) [`f5adaeba`](https://github.com/shopware/frontends/commit/f5adaeba6dec11422e0c02d92aba8caf56017af5) Thanks [@mdanilowicz](https://github.com/mdanilowicz)! - Add cms endpoint - -- [#435](https://github.com/shopware/frontends/pull/435) [`a4483ed8`](https://github.com/shopware/frontends/commit/a4483ed8bf9370e87aedeb81846fe9d31880b3e0) Thanks [@patzick](https://github.com/patzick)! - Changed types imports to `import type {...} from "..."` - -### Patch Changes - -- Updated dependencies [[`2e80139c`](https://github.com/shopware/frontends/commit/2e80139c6fa0bace77d385cfaffa30c4811f8831), [`43510a10`](https://github.com/shopware/frontends/commit/43510a108d351aca361e460844b2cddd29f889b5)]: - - @shopware-pwa/types@0.6.0 - -## 0.6.0 - -### Minor Changes - -- [`4532b60d`](https://github.com/shopware/frontends/commit/4532b60d449e1b5a45506fafa16eb7d156dc2359) Thanks [@patzick](https://github.com/patzick)! - Add `setCurrentCountry` for changing context countryId - -## 0.5.2 - -### Patch Changes - -- [#303](https://github.com/shopware/frontends/pull/303) [`aeb639a`](https://github.com/shopware/frontends/commit/aeb639a3244f812c275145345618e5bc0045be0d) Thanks [@patzick](https://github.com/patzick)! - Improved linting in packages. Types should be more reliable - -- Updated dependencies [[`aeb639a`](https://github.com/shopware/frontends/commit/aeb639a3244f812c275145345618e5bc0045be0d)]: - - @shopware-pwa/types@0.5.6 - -## 0.5.1 - -### Patch Changes - -- [#270](https://github.com/shopware/frontends/pull/270) [`14d97c5`](https://github.com/shopware/frontends/commit/14d97c5942adf5a49163625b2740d95bc5772689) Thanks [@mdanilowicz](https://github.com/mdanilowicz)! - Change getContextCountryEndpoint request type to POST - -- Updated dependencies [[`8a94e37`](https://github.com/shopware/frontends/commit/8a94e3739a24e5d748ba807852c5e5c2dfbe6cb4)]: - - @shopware-pwa/types@0.5.5 - -## 0.5.0 - -### Minor Changes - -- [#230](https://github.com/shopware/frontends/pull/230) [`d1e07d6`](https://github.com/shopware/frontends/commit/d1e07d6f73135cb742807aba78f1271943d47beb) Thanks [@mdanilowicz](https://github.com/mdanilowicz)! - Add redirectUrl to the contextService - -### Patch Changes - -- [#243](https://github.com/shopware/frontends/pull/243) [`d5f0bcc`](https://github.com/shopware/frontends/commit/d5f0bcc18cb581a48185cb8622d0e0d9b7fea23f) Thanks [@patzick](https://github.com/patzick)! - bump dependencies - -- Updated dependencies [[`e359aa2`](https://github.com/shopware/frontends/commit/e359aa28c9c9c7fb2521be3ebd5b847c855e4d24), [`5bb88e9`](https://github.com/shopware/frontends/commit/5bb88e9f4422141de916b704f13e9ecce9b8f2f2)]: - - @shopware-pwa/types@0.5.4 - -## 0.4.1 - -### Patch Changes - -- updated changelog in readme - -- Updated dependencies []: - - @shopware-pwa/types@0.5.3 - -## 0.4.0 - -### Minor Changes - -- [#187](https://github.com/shopware/frontends/pull/187) [`7fe30878`](https://github.com/shopware/frontends/commit/7fe3087844007d12dc26d9c6817ecd12eb431b9b) Thanks [@mdanilowicz](https://github.com/mdanilowicz)! - getAvailableShippingMethods - use POST method and add search params - -### Patch Changes - -- [#123](https://github.com/shopware/frontends/pull/123) [`0188b36a`](https://github.com/shopware/frontends/commit/0188b36acdf43278163a2fee74ff5b1c1aba55d8) Thanks [@mkucmus](https://github.com/mkucmus)! - Replace NOLINK label by @nolink tag - -- Updated dependencies [[`53f81c32`](https://github.com/shopware/frontends/commit/53f81c32b50c1658ee5758820085580cceea8161), [`47221193`](https://github.com/shopware/frontends/commit/472211939db34c8c81e957bd3e91a765056c088c), [`58932a83`](https://github.com/shopware/frontends/commit/58932a83106f7c415e68c4c1555180ff844ec151), [`a1edcd18`](https://github.com/shopware/frontends/commit/a1edcd18f3665b9ecdc32f7d33902d9c394b4fb6), [`a367dba6`](https://github.com/shopware/frontends/commit/a367dba68ab73f9ed2213236c696718c222565bc)]: - - @shopware-pwa/types@0.5.2 - -## 0.3.1 - -### Patch Changes - -- fixed published packages readme - -- Updated dependencies []: - - @shopware-pwa/types@0.5.1 - -## 0.3.0 - -### Minor Changes - -- [`dab0f839`](https://github.com/shopware/frontends/commit/dab0f839eeebe6bb9999cdd0ec11925d935b08b9) Thanks [@mdanilowicz](https://github.com/mdanilowicz)! - Add document and product media service - -- [#72](https://github.com/shopware/frontends/pull/72) [`e13d3d9a`](https://github.com/shopware/frontends/commit/e13d3d9adde759e97ca7fa9b7a782b7991428679) Thanks [@patzick](https://github.com/patzick)! - Add newsletter confirmation endpoint - -- [#71](https://github.com/shopware/frontends/pull/71) [`e71cc788`](https://github.com/shopware/frontends/commit/e71cc788c375c19ec449b820c0813b83503ef067) Thanks [@patzick](https://github.com/patzick)! - Add sitemap service - -### Patch Changes - -- [`0eaf57e1`](https://github.com/shopware/frontends/commit/0eaf57e17a1d8ee454533c33f7528b72021aed4b) Thanks [@mkucmus](https://github.com/mkucmus)! - JS-Doc improvements - -- Updated dependencies [[`5008dcbf`](https://github.com/shopware/frontends/commit/5008dcbf065fc54a3f51517460e409556f370adf), [`e2718c7d`](https://github.com/shopware/frontends/commit/e2718c7d20fac95c57436166083d6e5f599937c2), [`9c7a0f28`](https://github.com/shopware/frontends/commit/9c7a0f280c20ccbafca0e3063533820e21050bee), [`3a90d299`](https://github.com/shopware/frontends/commit/3a90d299279b451e391a946dafecc857fe1f67fc), [`2f64a718`](https://github.com/shopware/frontends/commit/2f64a71824594ffcc4e5d59f8d5e30cd627893db), [`909ffcde`](https://github.com/shopware/frontends/commit/909ffcde24d5ae873d814027be0920a9e5976c72), [`a15a3083`](https://github.com/shopware/frontends/commit/a15a308359497bb9d483bebe040d717114946ff0), [`d358854c`](https://github.com/shopware/frontends/commit/d358854c632447228e719efdf639c428cf6ba804)]: - - @shopware-pwa/types@0.5.0 - -## 0.2.3 - -### Patch Changes - -- [`680b4b77`](https://github.com/shopware/frontends/commit/680b4b778859f5f2fdf2325ce349f5534d3b965f) Thanks [@patzick](https://github.com/patzick)! - bump dependencies - -- Updated dependencies [[`244d0dca`](https://github.com/shopware/frontends/commit/244d0dcaadf2435e1895675e373c608631e94566)]: - - @shopware-pwa/types@0.4.0 - -## 0.2.2 - -### Patch Changes - -- [`29deb04f`](https://github.com/shopware/frontends/commit/29deb04fd1a871cb28f1fe3af3c007ae21de999f) Thanks [@niklaswolf](https://github.com/niklaswolf)! - adjusted return type of getSeoUrls - -- [`ccf4ed47`](https://github.com/shopware/frontends/commit/ccf4ed47e6bb46d1fcab7c1418a677fe575331b4) Thanks [@patzick](https://github.com/patzick)! - start deploying canary versions - -- Updated dependencies [[`6c045a44`](https://github.com/shopware/frontends/commit/6c045a44242dad42571df6ce82c564e07031d373), [`ccf4ed47`](https://github.com/shopware/frontends/commit/ccf4ed47e6bb46d1fcab7c1418a677fe575331b4), [`39d2d11c`](https://github.com/shopware/frontends/commit/39d2d11c922f5de9eb5d5c25225b6b93edd8ebcb)]: - - @shopware-pwa/types@0.3.0 - -## 0.2.1 - -### Patch Changes - -- Updated dependencies [[`e21d67b`](https://github.com/shopware/frontends/commit/e21d67bc142076e93630139232ea39a07b51ebfb)]: - - @shopware-pwa/types@0.2.0 - -## 0.2.0 - -### Minor Changes - -- [`b3f711c`](https://github.com/shopware/frontends/commit/b3f711ccb230025c0567b0a06a292bf9255a4992) Thanks [@mdanilowicz](https://github.com/mdanilowicz)! - ability to check if user is subscribed to newsletter - -### Patch Changes - -- [`9cd4078`](https://github.com/shopware/frontends/commit/9cd4078433c5644d2153a8a1212b9076a8d37347) Thanks [@mdanilowicz](https://github.com/mdanilowicz)! - Fix setDefaultCustomerPaymentMethod api url and context - -- [`29b677e`](https://github.com/shopware/frontends/commit/29b677e4ff59656f8a457ee4c8ab35e36cd06953) Thanks [@patzick](https://github.com/patzick)! - bump dependencies - -- Updated dependencies []: - - @shopware-pwa/types@0.1.20 - -## 0.1.20 - -### Patch Changes - -- fa7e48f: Added changelog and readme file -- Updated dependencies [fa7e48f] - - @shopware-pwa/types@0.1.20 diff --git a/packages/api-client-old/README.md b/packages/api-client-old/README.md deleted file mode 100644 index a9743c1fd..000000000 --- a/packages/api-client-old/README.md +++ /dev/null @@ -1,25 +0,0 @@ -# shopware/frontends - api-client - -> [!WARNING] -> Deprecated. This package is deprecated. Use The new [API client](https://www.npmjs.com/package/@shopware/api-client) package instead. - -Welcome to `@shopware-pwa/api-client` package. - -For getting started documentation visit [https://frontends.shopware.com/](https://frontends.shopware.com/) - -Documentation specific for this package: [api-client](https://frontends.shopware.com/packages/api-client.html) - - - -## Changelog - -Full changelog for stable version is available [here](https://github.com/shopware/frontends/blob/main/packages/api-client-old/CHANGELOG.md) - -### Latest changes: 1.0.2 - -### Patch Changes - -- [#1089](https://github.com/shopware/frontends/pull/1089) [`db7c93f`](https://github.com/shopware/frontends/commit/db7c93ff8cbb581221c11a492e77068af8faa8d6) Thanks [@mkucmus](https://github.com/mkucmus)! - Migrate eslint config to flat format - -- Updated dependencies [[`db7c93f`](https://github.com/shopware/frontends/commit/db7c93ff8cbb581221c11a492e77068af8faa8d6)]: - - @shopware-pwa/types@1.0.2 diff --git a/packages/api-client-old/build.config.ts b/packages/api-client-old/build.config.ts deleted file mode 100644 index a16f4d8b5..000000000 --- a/packages/api-client-old/build.config.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { defineBuildConfig } from "unbuild"; -export default defineBuildConfig({ - entries: ["src/index"], - declaration: true, - externals: [ - "axios", - "@shopware-pwa/types", - "query-string", - "@shopware/api-client", - ], - rollup: { - replace: { - values: { - "process.env.NODE_ENV": `"${process.env.NODE_ENV}"`, - }, - }, - }, -}); diff --git a/packages/api-client-old/eslint.config.mjs b/packages/api-client-old/eslint.config.mjs deleted file mode 100644 index b0b78e3d7..000000000 --- a/packages/api-client-old/eslint.config.mjs +++ /dev/null @@ -1,3 +0,0 @@ -import shopwareConfig from "eslint-config-shopware"; - -export default [...shopwareConfig]; diff --git a/packages/api-client-old/package.json b/packages/api-client-old/package.json deleted file mode 100644 index c50449978..000000000 --- a/packages/api-client-old/package.json +++ /dev/null @@ -1,57 +0,0 @@ -{ - "name": "@shopware-pwa/api-client", - "version": "1.0.2", - "description": "[DEPRECATED] use @shopware/api-client instead", - "author": "Shopware", - "type": "module", - "repository": { - "type": "git", - "url": "git+https://github.com/shopware/frontends.git" - }, - "homepage": "https://frontends.shopware.com/packages/api-client.html", - "keywords": [ - "shopware", - "api", - "client" - ], - "bugs": { - "url": "https://github.com/shopware/frontends/issues" - }, - "license": "MIT", - "module": "./dist/index.mjs", - "types": "./dist/index.d.ts", - "files": [ - "dist" - ], - "exports": { - ".": { - "import": { - "types": "./dist/index.d.mts", - "default": "./dist/index.mjs" - } - } - }, - "scripts": { - "build": "export NODE_ENV=production && unbuild && pnpm build:types", - "build:types": "tsc ./src/*.ts --declaration --allowJs --emitDeclarationOnly --outDir ./temp --skipLibCheck", - "dev": "export NODE_ENV=development && unbuild --stub", - "lint": "eslint src/**/*.ts* --fix --max-warnings=0 && pnpm run typecheck", - "typecheck": "tsc --noEmit", - "test": "vitest run" - }, - "devDependencies": { - "@faker-js/faker": "9.0.3", - "@shopware/api-client": "workspace:*", - "@vitest/coverage-v8": "2.1.3", - "eslint-config-shopware": "workspace:*", - "happy-dom": "15.7.4", - "tsconfig": "workspace:*", - "unbuild": "2.0.0", - "vitest": "2.1.3" - }, - "dependencies": { - "@shopware-pwa/types": "workspace:*", - "axios": "0.28.0", - "query-string": "9.1.0" - } -} diff --git a/packages/api-client-old/src/apiService.ts b/packages/api-client-old/src/apiService.ts deleted file mode 100644 index 9fa93a824..000000000 --- a/packages/api-client-old/src/apiService.ts +++ /dev/null @@ -1,154 +0,0 @@ -import axios, { AxiosInstance, AxiosResponse, AxiosRequestConfig } from "axios"; -import { createResponseInterceptor, errorInterceptor } from "./interceptors"; -import { ClientSettings, defaultConfig } from "./settings"; -import { getQueryString } from "./helpers/queryParamsBuilder"; - -/** - * @public - */ -export interface ConfigChangedArgs { - config: ClientSettings; -} - -/** - * @public - */ -export interface ShopwareApiInstance { - onConfigChange: (fn: (context: ConfigChangedArgs) => void) => void; - config: ClientSettings; - setup: (config?: ClientSettings) => void; - update: (config?: ClientSettings) => void; - - invoke: { - post: AxiosInstance["post"]; - get: AxiosInstance["get"]; - put: AxiosInstance["put"]; - patch: AxiosInstance["patch"]; - delete: AxiosInstance["delete"]; - }; - defaults: AxiosInstance["defaults"]; - /** - * We expose axios instance for advanced use. You might cause some side effects, use with caution. - */ - _axiosInstance: AxiosInstance; -} - -/** - * Internal method for creating new instance, exported only for tests, not exported by package - */ -export function _createInstance(initialConfig: ClientSettings = {}) { - const callbackMethods: ((context: ConfigChangedArgs) => void)[] = []; - let clientConfig: ClientSettings = {}; - const apiService: AxiosInstance = axios.create(); - - function reloadConfiguration() { - apiService.defaults.baseURL = clientConfig.endpoint; - if (clientConfig.timeout) { - apiService.defaults.timeout = - (typeof clientConfig.timeout === "number" && clientConfig.timeout) || - (typeof clientConfig.timeout === "string" && - parseInt(clientConfig.timeout)) || - 0; - } - apiService.defaults.headers.common["sw-include-seo-urls"] = "true"; - apiService.defaults.headers.common["sw-access-key"] = - clientConfig.accessToken as string; - // convert SearchCriteria into query string - apiService.defaults.paramsSerializer = getQueryString; - if (clientConfig.contextToken) { - apiService.defaults.headers.common["sw-context-token"] = - clientConfig.contextToken; - } else { - delete apiService.defaults.headers.common["sw-context-token"]; - } - if (clientConfig.languageId) { - apiService.defaults.headers.common["sw-language-id"] = - clientConfig.languageId; - } else { - delete apiService.defaults.headers.common["sw-language-id"]; - } - } - - function onConfigChange(fn: (context: ConfigChangedArgs) => void): void { - callbackMethods.push(fn); - } - - const setup = function (config: ClientSettings = {}): void { - clientConfig = Object.assign(clientConfig, defaultConfig, config); - reloadConfiguration(); - }; - setup(initialConfig); - - const update = function ( - config: ClientSettings, - responseConfig?: AxiosResponse["config"], - ): void { - clientConfig = Object.assign(clientConfig, config); - if ( - process.env.NODE_ENV !== "production" && - !callbackMethods.length && - responseConfig - ) { - console.warn( - `[shopware-6-api] After calling API method ${responseConfig.url} there is no "onConfigChange" listener. See https://shopware-pwa-docs.vuestorefront.io/landing/fundamentals/security.html#context-awareness`, - ); - } - callbackMethods.forEach((fn) => fn({ config: clientConfig })); - reloadConfiguration(); - }; - - const invoke = { - post: apiService.post, - put: apiService.put, - get: apiService.get, - patch: apiService.patch, - delete: apiService.delete, - }; - - apiService.interceptors.response.use( - createResponseInterceptor(update), - errorInterceptor, - ); - - return { - onConfigChange, - config: clientConfig, - setup, - update, - invoke, - defaults: apiService.defaults, - _axiosInstance: apiService, - }; -} - -/** - * - * @public - */ -export function createInstance( - initialConfig: ClientSettings = {}, -): ShopwareApiInstance { - const { - onConfigChange, - config, - setup, - update, - invoke, - defaults, - _axiosInstance, - } = _createInstance(initialConfig); - - return { - onConfigChange, - config, - setup, - update: (config: ClientSettings = {}): void => { - update(config); - }, - invoke, - defaults, - _axiosInstance, - }; -} - -export const defaultInstance = createInstance(); diff --git a/packages/api-client-old/src/endpoints.spec.ts b/packages/api-client-old/src/endpoints.spec.ts deleted file mode 100644 index d1932182a..000000000 --- a/packages/api-client-old/src/endpoints.spec.ts +++ /dev/null @@ -1,288 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { - getProductEndpoint, - getProductDetailsEndpoint, - getCategoryEndpoint, - getCategoryDetailsEndpoint, - getCustomerAddressEndpoint, - getCustomerEndpoint, - getCustomerLoginEndpoint, - getCustomerLogoutEndpoint, - getCustomerOrderEndpoint, - getCheckoutCartEndpoint, - getCheckoutCartLineItemEndpoint, - getCheckoutOrderEndpoint, - getContextCurrencyEndpoint, - getContextLanguageEndpoint, - getContextCountryEndpoint, - getContextPaymentMethodEndpoint, - getContextShippingMethodEndpoint, - getContextSalutationEndpoint, - getNewsletterSubscribeEndpoint, - getNewsletterUnsubscribeEndpoint, - getStoreNewsletterSubscribeEndpoint, - getStoreNewsletterConfirmEndpoint, - getStoreNewsletterUnsubscribeEndpoint, - getStoreNavigationEndpoint, - handlePaymentEndpoint, - getContactFormEndpoint, - getConfirmPasswordResetEndpoint, - getProductReviewsEndpoint, - getLandingPageDetailsEndpoint, - getProductListingEndpoint, - getNewsletterRecipientEndpoint, - getDocumentDownloadEndpoint, - getOrderDownloadsEndpoint, - getSitemapEndpoint, -} from "../src/endpoints"; - -const sampleProductId = "eea0f69ec02d44f7a4224272b3d99478"; -const sampleCategoryId = "03dfd5badd3d43bd8a345ef660761e09"; - -describe("endpoints", () => { - describe("getProductEndpoint", () => { - it("should return Shopware product endpoint", async () => { - const result = getProductEndpoint(); - expect(result).toEqual("/store-api/product"); - }); - }); - - describe("getProductReviewsEndpoint", () => { - it("should return Shopware product review endpoint", async () => { - const result = getProductReviewsEndpoint(sampleProductId); - expect(result).toEqual( - "/store-api/product/" + sampleProductId + "/reviews", - ); - }); - }); - - describe("getProductDetailsEndpoint", () => { - it("should return Shopware product details endpoint", async () => { - const result = getProductDetailsEndpoint(sampleProductId); - expect(result).toEqual("/store-api/product/" + sampleProductId); - }); - }); - - describe("getCategoryEndpoint", () => { - it("should return Shopware category endpoint", async () => { - const result = getCategoryEndpoint(); - expect(result).toEqual("/store-api/category"); - }); - }); - - describe("getCategoryDetailsEndpoint", () => { - it("should return Shopware category details endpoint", async () => { - const result = getCategoryDetailsEndpoint(sampleCategoryId); - expect(result).toEqual("/store-api/category/" + sampleCategoryId); - }); - }); - - describe("getCustomerAddressEndpoint", () => { - it("should return Shopware address endpoint", async () => { - const result = getCustomerAddressEndpoint(); - expect(result).toEqual("/store-api/account/list-address"); - }); - }); - - describe("getCustomerEndpoint", () => { - it("should return Shopware customer endpoint", async () => { - const result = getCustomerEndpoint(); - expect(result).toEqual("/store-api/account/customer"); - }); - }); - - describe("getCustomerLoginEndpoint", () => { - it("should return Shopware customer login endpoint", async () => { - const result = getCustomerLoginEndpoint(); - expect(result).toEqual("/store-api/account/login"); - }); - }); - - describe("getCustomerLogoutEndpoint", () => { - it("should return Shopware customer logout endpoint", async () => { - const result = getCustomerLogoutEndpoint(); - expect(result).toEqual("/store-api/account/logout"); - }); - }); - - describe("getCustomerOrderEndpoint", () => { - it("should return Shopware customer order endpoint", async () => { - const result = getCustomerOrderEndpoint(); - expect(result).toEqual("/store-api/order"); - }); - }); - - describe("getCheckoutCartEndpoint", () => { - it("should return Shopware checkout-cart endpoint", async () => { - const result = getCheckoutCartEndpoint(); - expect(result).toEqual("/store-api/checkout/cart"); - }); - }); - - describe("getCheckoutCartLineItemEndpoint", () => { - it("should return Shopware checkout-cart-lineItem endpoint", async () => { - const result = getCheckoutCartLineItemEndpoint(); - expect(result).toEqual("/store-api/checkout/cart/line-item"); - }); - }); - - describe("getCheckoutOrderEndpoint", () => { - it("should return Shopware checkout-order endpoint", async () => { - const result = getCheckoutOrderEndpoint(); - expect(result).toEqual("/store-api/checkout/order"); - }); - }); - - describe("getContextCurrencyEndpoint", () => { - it("should return Shopware currency endpoint", async () => { - const result = getContextCurrencyEndpoint(); - expect(result).toEqual("/store-api/currency"); - }); - }); - - describe("getContextLanguageEndpoint", () => { - it("should return Shopware language endpoint", async () => { - const result = getContextLanguageEndpoint(); - expect(result).toEqual("/store-api/language"); - }); - }); - - describe("getContextCountryEndpoint", () => { - it("should return Shopware country endpoint", async () => { - const result = getContextCountryEndpoint(); - expect(result).toEqual("/store-api/country"); - }); - }); - - describe("getContextPaymentMethodEndpoint", () => { - it("should return Shopware payment method endpoint", async () => { - const result = getContextPaymentMethodEndpoint(); - expect(result).toEqual("/store-api/payment-method"); - }); - }); - describe("getContextShippingMethodEndpoint", () => { - it("should return Shopware shipping method endpoint", async () => { - const result = getContextShippingMethodEndpoint(); - expect(result).toEqual("/store-api/shipping-method"); - }); - }); - - describe("getContextSalutationEndpoint", () => { - it("should return Shopware salutation endpoint", async () => { - const result = getContextSalutationEndpoint(); - expect(result).toEqual("/store-api/salutation"); - }); - }); - - describe("getNewsletterSubscribeEndpoint", () => { - it("should return Shopware newsletter subscribe endpoint", async () => { - const result = getNewsletterSubscribeEndpoint(); - expect(result).toEqual("/newsletter/subscribe"); - }); - }); - - describe("getNewsletterUnsubscribeEndpoint", () => { - it("should return Shopware newsletter unsubscribe endpoint", async () => { - const result = getNewsletterUnsubscribeEndpoint(); - expect(result).toEqual("/newsletter/unsubscribe"); - }); - }); - - describe("getNewsletterRecipientEnpoint", () => { - it("should return Shopware newsletter recipient endpoint", async () => { - const result = getNewsletterRecipientEndpoint(); - expect(result).toEqual("/store-api/account/newsletter-recipient"); - }); - }); - - describe("getStoreNavigationEndpoint", () => { - it("should return store navigation endpoint", async () => { - const result = getStoreNavigationEndpoint( - "footer-navigation", - "footer-navigation", - ); - expect(result).toEqual( - "/store-api/navigation/footer-navigation/footer-navigation", - ); - }); - }); - - describe("handlePaymentEndpoint", () => { - it("should return handle payment method url endpoint", async () => { - const result = handlePaymentEndpoint(); - expect(result).toEqual(`/store-api/handle-payment`); - }); - }); - - describe("getContactFormEndpoint", () => { - it("should return contact form url endpoint", async () => { - const result = getContactFormEndpoint(); - expect(result).toEqual(`/store-api/contact-form`); - }); - }); - - describe("getStoreNewsletterSubscribeEndpoint", () => { - it("should return Shopware newsletter subscribe URL endpoint", async () => { - const result = getStoreNewsletterSubscribeEndpoint(); - expect(result).toEqual("/store-api/newsletter/subscribe"); - }); - }); - - describe("getStoreNewsletterConfirmEndpoint", () => { - it("should return Shopware newsletter confirm URL endpoint", async () => { - const result = getStoreNewsletterConfirmEndpoint(); - expect(result).toEqual("/store-api/newsletter/confirm"); - }); - }); - - describe("getStoreNewsletterUnsubscribeEndpoint", () => { - it("should return Shopware newsletter unsubscribe URL endpoint", async () => { - const result = getStoreNewsletterUnsubscribeEndpoint(); - expect(result).toEqual("/store-api/newsletter/unsubscribe"); - }); - }); - - describe("getConfirmPasswordResetEndpoint", () => { - it("should return correct endpoint for reset password confirmation action", () => { - const result = getConfirmPasswordResetEndpoint(); - expect(result).toBe("/store-api/account/recovery-password-confirm"); - }); - }); - - describe("getLandingPageDetailsEndpoint", () => { - it("should return correct endpoint for getting landing page", () => { - const landingPageId = "test"; - const result = getLandingPageDetailsEndpoint(landingPageId); - expect(result).toBe(`/store-api/landing-page/${landingPageId}`); - }); - }); - - describe("getProductListingEndpoint", () => { - it("should return product listing endpoint", () => { - const categoryId = "test"; - const result = getProductListingEndpoint(categoryId); - expect(result).toBe(`/store-api/product-listing/${categoryId}`); - }); - }); - - describe("getDocumentDownloadEndpoint", () => { - it("should return document download endpoint", () => { - const result = getDocumentDownloadEndpoint("123", "345"); - expect(result).toBe(`/store-api/document/download/123/345`); - }); - }); - - describe("getOrderDownloadsEndpoint", () => { - it("should return order download endpoint", () => { - const result = getOrderDownloadsEndpoint("123", "345"); - expect(result).toBe(`/store-api/order/download/123/345`); - }); - }); - - describe("getSitemapEndpoint", () => { - it("should return Shopware sitemap endpoint", async () => { - const result = getSitemapEndpoint(); - expect(result).toEqual("/store-api/sitemap"); - }); - }); -}); diff --git a/packages/api-client-old/src/endpoints.ts b/packages/api-client-old/src/endpoints.ts deleted file mode 100644 index 09aadba46..000000000 --- a/packages/api-client-old/src/endpoints.ts +++ /dev/null @@ -1,451 +0,0 @@ -// category - -/** - * @nolink - * @category Endpoints - * @public - */ -export const getCategoryEndpoint = () => `/store-api/category`; - -/** - * @nolink - * @category Endpoints - * @public - */ -export const getCategoryDetailsEndpoint = (categoryId: string) => - `/store-api/category/${categoryId}`; - -// landing-page -/** - * @nolink - * @category Endpoints - * @public - */ -export const getLandingPageDetailsEndpoint = (landingPageId: string) => - `/store-api/landing-page/${landingPageId}`; - -// product-listing - -/** - * @nolink - * @category Endpoints - * @public - */ -export const getProductListingEndpoint = (categoryId: string) => - `/store-api/product-listing/${categoryId}`; - -// product - -/** - * @nolink - * @category Endpoints - * @public - */ -export const getProductEndpoint = () => `/store-api/product`; - -/** - * @nolink - * @category Endpoints - * @public - */ -export const getProductDetailsEndpoint = (productId: string) => - `/store-api/product/${productId}`; - -/** - * @nolink - * @category Endpoints - * @public - */ -export const getProductCrossSellingEndpoint = (productId: string) => - `/store-api/product/${productId}/cross-selling`; - -// product-reviews - -/** - * @nolink - * @category Endpoints - * @public - */ -export const getProductReviewsEndpoint = (productId: string) => - `/store-api/product/${productId}/reviews`; - -// search - -/** - * @nolink - * @category Endpoints - * @public - */ -export const getSuggestSearchEndpoint = () => `/store-api/search-suggest`; - -/** - * @nolink - * @category Endpoints - * @public - */ -export const getSearchEndpoint = () => `/store-api/search`; - -// customer -/** - * @nolink - * @category Endpoints - * @public - */ -export const getCustomerAddAddressEndpoint = () => `/store-api/account/address`; - -/** - * @nolink - * @category Endpoints - * @public - */ -export const getCustomerAddressEndpoint = (addressId?: string) => - addressId - ? `/store-api/account/address/${addressId}` - : "/store-api/account/list-address"; - -const getCustomerDefaultAddressEndpoint = (type: string, addressId: string) => - `/store-api/account/address/default-${type}/${addressId}`; - -/** - * @nolink - * @category Endpoints - * @public - */ -export const getCustomerDefaultBillingAddressEndpoint = (addressId: string) => - getCustomerDefaultAddressEndpoint("billing", addressId); - -/** - * @nolink - * @category Endpoints - * @public - */ -export const getCustomerDefaultShippingAddressEndpoint = (addressId: string) => - getCustomerDefaultAddressEndpoint("shipping", addressId); - -/** - * @nolink - * @category Endpoints - * @public - */ -export const getCustomerEndpoint = () => `/store-api/account/customer`; -/** - * @nolink - * @category Endpoints - * @public - */ -export const getCustomerRegisterEndpoint = () => `/store-api/account/register`; -/** - * @nolink - * @category Endpoints - * @public - */ -export const getCustomerDetailsUpdateEndpoint = () => - `/store-api/account/change-profile`; - -/** - * @nolink - * @category Endpoints - * @public - */ -export const getCustomerLoginEndpoint = () => `/store-api/account/login`; - -/** - * @nolink - * @category Endpoints - * @public - */ -export const getCustomerLogoutEndpoint = () => `/store-api/account/logout`; - -/** - * @nolink - * @category Endpoints - * @public - */ -export const getCustomerOrderEndpoint = () => `/store-api/order`; - -/** - * @nolink - * @category Endpoints - * @public - */ -export const getCustomerUpdateEmailEndpoint = () => - `/store-api/account/change-email`; - -/** - * @nolink - * @category Endpoints - * @public - */ -export const getCustomerUpdatePasswordEndpoint = () => - `/store-api/account/change-password`; - -/** - * @nolink - * @category Endpoints - * @public - */ -export const getCustomerResetPasswordEndpoint = () => - `/store-api/account/recovery-password`; - -/** - * @nolink - * @category Endpoints - * @public - */ -export const getConfirmPasswordResetEndpoint = () => - `/store-api/account/recovery-password-confirm`; - -/** - * @nolink - * @category Endpoints - * @public - */ -export const getCustomerAccountConfirmEndpoint = () => - `/store-api/account/register-confirm`; - -/** - * @nolink - * @category Endpoints - * @public - */ -export const getCustomerUpdatePaymentMethodEndpoint = ( - paymentMethodId: string, -) => `/store-api/account/change-payment-method/${paymentMethodId}`; - -// checkout - -/** - * @nolink - * @category Endpoints - * @public - */ -export const getCheckoutCartEndpoint = () => `/store-api/checkout/cart`; - -/** - * @nolink - * @category Endpoints - * @public - */ -export const getCheckoutCartLineItemEndpoint = () => - `/store-api/checkout/cart/line-item`; - -/** - * @nolink - * @category Endpoints - * @public - */ -export const getCheckoutOrderEndpoint = () => `/store-api/checkout/order`; - -/** - * @nolink - * @category Endpoints - * @public - */ -export const getCancelOrderEndpoint = () => `/store-api/order/state/cancel`; - -/** - * @nolink - * @category Endpoints - * @public - */ -export const getChangeOrderPaymentMethodEndpoint = () => - `/store-api/order/payment`; - -// context - -/** - * @nolink - * @category Endpoints - * @public - */ -export const getContextEndpoint = () => `/store-api/context`; - -/** - * @nolink - * @category Endpoints - * @public - */ -export const getContextCurrencyEndpoint = () => `/store-api/currency`; - -/** - * @nolink - * @category Endpoints - * @public - */ -export const getContextLanguageEndpoint = () => `/store-api/language`; - -/** - * @nolink - * @category Endpoints - * @public - */ -export const getContextCountryEndpoint = () => `/store-api/country`; - -/** - * @nolink - * @category Endpoints - * @public - */ -export const getContextPaymentMethodEndpoint = () => - `/store-api/payment-method`; - -/** - * @nolink - * @category Endpoints - * @public - */ -export const getContextShippingMethodEndpoint = () => - `/store-api/shipping-method`; - -/** - * @nolink - * @category Endpoints - * @public - */ -export const getContextSalutationEndpoint = () => `/store-api/salutation`; - -// newsletter - -/** - * @nolink - * @category Endpoints - * @public - */ -export const getNewsletterSubscribeEndpoint = () => `/newsletter/subscribe`; // replace with `/store-api/v4/newsletter/subscribe`, consider using `/store-api/v4/newsletter/confirm` - -/** - * @nolink - * @category Endpoints - * @public - */ -export const getNewsletterUnsubscribeEndpoint = () => `/newsletter/unsubscribe`; // replace with `/store-api/v4/newsletter/unsubscribe` - -/** - * @nolink - * @category Endpoints - * @public - */ -export const getNewsletterRecipientEndpoint = () => - `/store-api/account/newsletter-recipient`; - -/** - * @nolink - * @category Endpoints - * @public - */ -export const getPageResolverEndpoint = () => `/store-api/pwa/page`; - -/** - * @nolink - * @category Endpoints - * @public - */ -export const getSeoUrlEndpoint = () => "/store-api/seo-url"; - -/** - * @nolink - * @category Endpoints - * @public - */ -export const getStoreNavigationEndpoint = ( - requestActiveId: string, - requestRootId: string, -) => `/store-api/navigation/${requestActiveId}/${requestRootId}`; - -/** - * @nolink - * @category Endpoints - * @public - */ -export const getContactFormEndpoint = () => `/store-api/contact-form`; -/** - * @nolink - * @category Endpoints - * @public - */ -export const handlePaymentEndpoint = () => `/store-api/handle-payment`; - -/** - * @nolink - * @category Endpoints - * @public - */ -export const getStoreNewsletterSubscribeEndpoint = () => - `/store-api/newsletter/subscribe`; - -/** - * @nolink - * @category Endpoints - * @public - */ -export const getStoreNewsletterConfirmEndpoint = () => - `/store-api/newsletter/confirm`; - -/** - * @nolink - * @category Endpoints - * @public - */ -export const getStoreNewsletterUnsubscribeEndpoint = () => - `/store-api/newsletter/unsubscribe`; - -/** - * @nolink - * @category Endpoints - * @public - */ -export const getGetWishlistProductsEndpoint = () => - `/store-api/customer/wishlist`; -/** - * @nolink - * @category Endpoints - * @public - */ -export const getAddWishlistProductEndpoint = (productId: string) => - `/store-api/customer/wishlist/add/${productId}`; -/** - * @nolink - * @category Endpoints - * @public - */ -export const getRemoveWishlistProductEndpoint = (productId: string) => - `/store-api/customer/wishlist/delete/${productId}`; -/** - * @nolink - * @category Endpoints - * @public - */ -export const getMergeWishlistProductsEndpoint = () => - `/store-api/customer/wishlist/merge`; -/** - * @nolink - * @nolink - * @category Endpoints - * @public - */ -export const getDocumentDownloadEndpoint = ( - documentId: string, - deepLinkCode: string, -) => `/store-api/document/download/${documentId}/${deepLinkCode}`; -/** - * @nolink - * @category Endpoints - * @public - */ -export const getOrderDownloadsEndpoint = ( - orderId: string, - downloadId: string, -) => `/store-api/order/download/${orderId}/${downloadId}`; -/** - * @public - */ -export const getSitemapEndpoint = () => `/store-api/sitemap`; - -/** - * @nolink - * @category Endpoints - * @public - * @param {string} pageId - * @returns {string} - */ -export const getCmsEndpoint = (pageId: string) => `/store-api/cms/${pageId}`; diff --git a/packages/api-client-old/src/helpers/context.ts b/packages/api-client-old/src/helpers/context.ts deleted file mode 100644 index 6b76e6ab7..000000000 --- a/packages/api-client-old/src/helpers/context.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { AxiosResponse } from "axios"; - -export function extractContextToken(response: AxiosResponse) { - return ( - response.data["sw-context-token"] || - response.data["contextToken"] || - response.headers["sw-context-token"] - ); -} diff --git a/packages/api-client-old/src/helpers/queryParamsBuilder.spec.ts b/packages/api-client-old/src/helpers/queryParamsBuilder.spec.ts deleted file mode 100644 index 5710e543b..000000000 --- a/packages/api-client-old/src/helpers/queryParamsBuilder.spec.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { getQueryString } from "../../src/helpers/queryParamsBuilder"; -import { describe, expect, it } from "vitest"; - -describe("queryParamsBuilder - getQueryString", () => { - it("should return converted parameters if given params is not in a string type", () => { - const searchCriteria = { - page: 1, - sort: "-name", - }; - - const result = getQueryString(searchCriteria); - expect(result).toStrictEqual("page=1&sort=-name"); - }); - it("should return given string as it is", () => { - const searchCriteria = "?page=1"; - - const result = getQueryString(searchCriteria); - expect(result).toStrictEqual("?page=1"); - }); -}); diff --git a/packages/api-client-old/src/helpers/queryParamsBuilder.ts b/packages/api-client-old/src/helpers/queryParamsBuilder.ts deleted file mode 100644 index d48ef7224..000000000 --- a/packages/api-client-old/src/helpers/queryParamsBuilder.ts +++ /dev/null @@ -1,16 +0,0 @@ -import queryString from "query-string"; - -const ARRAY_FORMAT = "separator"; -const ARRAY_FORMAT_SEPARATOR = "|"; -const SKIP_NULL = true; -const SORT = false; - -export const getQueryString = (params: unknown) => - typeof params === "string" - ? params - : queryString.stringify(params as Record, { - arrayFormat: ARRAY_FORMAT, - arrayFormatSeparator: ARRAY_FORMAT_SEPARATOR, - skipNull: SKIP_NULL, - sort: SORT, - }); diff --git a/packages/api-client-old/src/index.ts b/packages/api-client-old/src/index.ts deleted file mode 100644 index ed24457a9..000000000 --- a/packages/api-client-old/src/index.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { defaultInstance, ConfigChangedArgs } from "./apiService"; -import { ClientSettings } from "./settings"; -export type { ClientSettings } from "./settings"; -export { createInstance } from "./apiService"; -export type { ConfigChangedArgs, ShopwareApiInstance } from "./apiService"; - -export * from "./services/categoryService"; -export * from "./services/productService"; -export * from "./services/customerService"; -export * from "./services/contextService"; -export * from "./services/cartService"; -export * from "./services/navigationService"; -export * from "./services/pageService"; -export * from "./services/checkoutService"; -export * from "./services/pluginService"; -export * from "./services/searchService"; -export * from "./services/formsService"; -export * from "./services/wishlistService"; -export * from "./services/documentService"; -export * from "./services/orderService"; -export * from "./services/sitemapService"; -export * from "./services/newsletterService"; -export * from "./endpoints"; - -/** - * @public - */ -export const config: ClientSettings = defaultInstance.config; -/** - * Setup configuration. Merge default values with provided in param. - * This method will override existing config. For config update invoke **update** method. - * @public - */ -export const setup: (config?: ClientSettings) => void = defaultInstance.setup; - -/** - * Update current configuration. This will change only provided values. - * @public - */ -export const update: (config?: ClientSettings) => void = defaultInstance.update; - -/** - * @public - */ -export const onConfigChange: ( - fn: (context: ConfigChangedArgs) => void, -) => void = defaultInstance.onConfigChange; diff --git a/packages/api-client-old/src/interceptors/apiInterceptors.spec.ts b/packages/api-client-old/src/interceptors/apiInterceptors.spec.ts deleted file mode 100644 index 4f74c1c4c..000000000 --- a/packages/api-client-old/src/interceptors/apiInterceptors.spec.ts +++ /dev/null @@ -1,302 +0,0 @@ -import { createResponseInterceptor, errorInterceptor } from "."; -import { faker } from "@faker-js/faker"; -import { ShopwareApiError } from "@shopware-pwa/types"; -import { AxiosHeaders } from "axios"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -describe("apiInterceptors", () => { - beforeEach(() => { - vi.resetAllMocks(); - }); - describe("createResponseInterceptor", () => { - it("should update contextToken after any request", async () => { - const contextToken = faker.string.uuid(); - const updateMethod = vi.fn(); - const responseInterceptor = createResponseInterceptor(updateMethod); - responseInterceptor({ - data: { data: { id: "044a190a54ab4f06803909c3ee8063ef" } }, - headers: { "sw-context-token": contextToken }, - status: 200, - statusText: "OK", - config: { - headers: new AxiosHeaders(), - }, - }); - expect(updateMethod).toHaveBeenCalledWith( - { contextToken }, - { - headers: new AxiosHeaders(), - }, - ); - }); - - it("should get contextToken from response, not header, if there is one", () => { - const contextToken = faker.string.uuid(); - const updateMethod = vi.fn(); - const responseInterceptor = createResponseInterceptor(updateMethod); - responseInterceptor({ - data: { contextToken: "044a190a54ab4f06803909c3ee8063ef" }, - headers: { "sw-context-token": contextToken }, - status: 200, - statusText: "OK", - config: { - headers: new AxiosHeaders(), - }, - }); - expect(updateMethod).toHaveBeenCalledWith( - { - contextToken: "044a190a54ab4f06803909c3ee8063ef", - }, - { - headers: new AxiosHeaders(), - }, - ); - }); - }); - - describe("errorInterceptor", () => { - it("error should have undefined statusCode and message if no data exist in response", async () => { - try { - await errorInterceptor({ response: {} } as ShopwareApiError); - // Fail test if above expression doesn't throw anything. - expect("didn't throw an error").toEqual("should throw an error"); - } catch (e) { - expect(e.statusCode).toEqual(500); - expect(e.messages).toEqual([]); - } - }); - it("should throw an error with no message if errors array is null", async () => { - try { - await errorInterceptor({ - response: { status: 404, data: { errors: null } }, - } as ShopwareApiError); - // Fail test if above expression doesn't throw anything. - expect("didn't throw an error").toEqual("should throw an error"); - } catch (e) { - expect(e.statusCode).toEqual(404); - expect(e.messages).toStrictEqual([]); - } - }); - it("should have error with no message when the error has no detail property", async () => { - try { - await errorInterceptor({ - response: { status: 404, data: null }, - } as ShopwareApiError); - // Fail test if above expression doesn't throw anything. - expect("didn't throw an error").toEqual("should throw an error"); - } catch (e) { - expect(e.statusCode).toEqual(404); - expect(e.messages).toStrictEqual([]); - } - }); - - it("should error message should be an empty string when no error", async () => { - try { - await errorInterceptor({ - response: { - status: 404, - data: { errors: [{ detail: "Resource not found" }] }, - }, - } as ShopwareApiError); - // Fail test if above expression doesn't throw anything. - expect("didn't throw an error").toEqual("should throw an error"); - } catch { - // expect(e.statusCode).toEqual(404); - //expect(e.message).toBe("Resource not found") - } - }); - it("should throw an error from parameters", async () => { - try { - await errorInterceptor({ - response: { - status: 404, - data: { errors: [{ detail: "Resource not found" }] }, - }, - } as ShopwareApiError); - // Fail test if above expression doesn't throw anything. - expect("didn't throw an error").toEqual("should throw an error"); - } catch (e) { - expect(e.statusCode).toEqual(404); - expect(e.messages).toStrictEqual([{ detail: "Resource not found" }]); - } - }); - it("should return object with error message taken from array's first element", async () => { - try { - await errorInterceptor({ - response: { - status: 403, - data: { - errors: [ - { detail: "Customer is not logged in." }, - { detail: "" }, - ], - }, - }, - } as ShopwareApiError); - // Fail test if above expression doesn't throw anything. - expect("didn't throw an error").toEqual("should throw an error"); - } catch (e) { - expect(e.statusCode).toEqual(403); - expect(e.messages).toStrictEqual([ - { detail: "Customer is not logged in." }, - { detail: "" }, - ]); - } - }); - it("should return origin errors array in case of 400", async () => { - try { - await errorInterceptor({ - response: { - status: 400, - data: { - errors: [ - { detail: "Param X is required." }, - { detail: "Param Y should not be blank." }, - ], - }, - }, - } as ShopwareApiError); - // Fail test if above expression doesn't throw anything. - expect("didn't throw an error").toEqual("should throw an error"); - } catch (e) { - expect(e.statusCode).toEqual(400); - expect(e.messages).toStrictEqual([ - { detail: "Param X is required." }, - { detail: "Param Y should not be blank." }, - ]); - } - }); - it("should return empty array in case of 400 and no errors in the content", async () => { - try { - await errorInterceptor({ - response: { status: 400 }, - } as ShopwareApiError); - // Fail test if above expression doesn't throw anything. - expect("didn't throw an error").toEqual("should throw an error"); - } catch (e) { - expect(e.statusCode).toEqual(400); - expect(e.messages).toStrictEqual([]); - } - }); - it("should return general message in case of 500", async () => { - try { - await errorInterceptor({ - response: { - status: 500, - data: { - errors: [ - { detail: "Param X is required." }, - { detail: "Param Y should not be blank." }, - ], - }, - }, - } as ShopwareApiError); - // Fail test if above expression doesn't throw anything. - expect("didn't throw an error").toEqual("should throw an error"); - } catch (e) { - expect(e.statusCode).toEqual(500); - expect(e.messages).toStrictEqual([ - { detail: "Param X is required." }, - { detail: "Param Y should not be blank." }, - ]); - } - }); - it("should recognize the timeout rejection in axios specific case (timeout in config reached)", async () => { - try { - await errorInterceptor({ - message: "timeout of 5ms", - } as ShopwareApiError); - // Fail test if above expression doesn't throw anything. - expect("didn't throw an error").toEqual("should throw an error"); - } catch (e) { - expect(e.statusCode).toEqual(408); - expect(e.messages).toStrictEqual([ - { - code: "", - detail: "timeout of 5ms", - meta: {}, - source: { - pointer: "", - }, - status: "", - title: "", - }, - ]); - } - }); - it("should recognize the Network error rejection in axios specific case (there is no internet connection - offline mode is on)", async () => { - try { - await errorInterceptor({ - message: "Network Error", - } as ShopwareApiError); - // Fail test if above expression doesn't throw anything. - expect("didn't throw an error").toEqual("should throw an error"); - } catch (e) { - expect(e.statusCode).toEqual(0); - expect(e.messages).toStrictEqual([ - { - code: "", - detail: "Network Error", - meta: {}, - source: { - pointer: "", - }, - status: "", - title: "", - }, - ]); - } - }); - it("it should treat all status codes from 4xx group (except 408) as API error coming from an application", async () => { - try { - await errorInterceptor({ - response: { - status: 403, - data: { - errors: [], - }, - }, - } as ShopwareApiError); - } catch (error) { - expect(error).toStrictEqual({ - statusCode: 403, - messages: [], - }); - } - }); - it("should not try to extract API error if it's a 408 timeout", async () => { - try { - await errorInterceptor({ - message: "timeout of 5ms", - } as ShopwareApiError); - } catch (error) { - expect(error).toStrictEqual({ - messages: [ - { - detail: "timeout of 5ms", - status: "", - code: "", - title: "", - meta: {}, - source: { - pointer: "", - }, - }, - ], - statusCode: 408, - }); - } - }); - - it("it should not fail when api is unreachable", async () => { - try { - await errorInterceptor({} as ShopwareApiError); - } catch (error) { - expect(error).toStrictEqual({ - statusCode: 500, - messages: [], - }); - } - }); - }); -}); diff --git a/packages/api-client-old/src/interceptors/errorInterceptor.ts b/packages/api-client-old/src/interceptors/errorInterceptor.ts deleted file mode 100644 index 366624e30..000000000 --- a/packages/api-client-old/src/interceptors/errorInterceptor.ts +++ /dev/null @@ -1,101 +0,0 @@ -import { AxiosError } from "axios"; -import type { - ShopwareError, - ShopwareApiError, - ClientApiError, -} from "@shopware-pwa/types"; - -/** - * Handle all HTTP status codes from 4xx group as an API errors, including 500 (exception for order placement issue) - * 408 timeout error is handled separately - */ -const isApiError = (statusCode: number): boolean => { - if ( - (statusCode != 408 && statusCode.toString().startsWith("4")) || - statusCode == 500 - ) { - return true; - } - return false; -}; -/** - * @param {ShopwareApiError} error - */ -const extractApiErrorStatusCode = (error: ShopwareApiError): number => { - return ( - (error.response && error.response.status) || - guessTheStatusCodeFromTheMessage(error.message) - ); -}; - -/** - * Sometimes the HTTP status code is not available and must be guessed from the message. - * In cases like connection problems, or timeout error comes from intermediate layer (i.e. client) - */ -const guessTheStatusCodeFromTheMessage = (message: string): number => { - // catch the specific timeout rejection from axios - if (typeof message === "string" && message.startsWith("timeout of")) { - return 408; - } - - // offline mode exception - if (typeof message === "string" && message.startsWith("Network Error")) { - return 0; - } - - return 500; -}; - -/** - * Extract error message - * Keep the original errors[] format if 400 Bad Request for validation purposes. - * 400 responses always points to the specific field/param/option, thus should be kept entirely. - * - * @param {ShopwareApiError} error - * @returns {(string|ShopwareError[])} single message if statusCode !== 400, array of native errors otherwise - */ -const extractApiErrorMessage = (error: ShopwareApiError): ShopwareError[] => { - return error.response?.data?.errors || []; -}; - -/** - * Extract message from AxiosError which comes from somewhere else. - * @param {AxiosError} error - * @returns {string} - */ -const extractNotApiErrorMessage = (error: AxiosError): ShopwareError[] => [ - { - detail: error.message, - status: "", - code: "", - title: "", - meta: {}, - source: { - pointer: "", - }, - }, -]; - -/** - * Extracts and create the consistent error object - * Error message depends on: - * 1. type of error (API or other network layer) - * 2. status code - * - * @param {ShopwareApiError} error - * @returns {Promise} - */ -export async function errorInterceptor( - error: ShopwareApiError, -): Promise { - // Any status codes that falls outside the range of 2xx cause this function to trigger - // Do something with response error - const statusCode = extractApiErrorStatusCode(error); - const clientApiError: ClientApiError = { - messages: isApiError(statusCode) - ? extractApiErrorMessage(error) - : extractNotApiErrorMessage(error), - statusCode: statusCode, - }; - return Promise.reject(clientApiError); -} diff --git a/packages/api-client-old/src/interceptors/index.ts b/packages/api-client-old/src/interceptors/index.ts deleted file mode 100644 index ac8b5bfcc..000000000 --- a/packages/api-client-old/src/interceptors/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from "./errorInterceptor"; -export * from "./responseInterceptor"; diff --git a/packages/api-client-old/src/interceptors/responseInterceptor.ts b/packages/api-client-old/src/interceptors/responseInterceptor.ts deleted file mode 100644 index 5cb41b6cc..000000000 --- a/packages/api-client-old/src/interceptors/responseInterceptor.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { AxiosResponse, AxiosRequestConfig } from "axios"; -import { extractContextToken } from "../helpers/context"; -import { ClientSettings } from "../settings"; - -export function createResponseInterceptor( - update: ( - settings: Partial, - responseConfig: AxiosResponse["config"], - ) => void, -) { - return function (response: AxiosResponse) { - const contextToken = extractContextToken(response); - if (contextToken) { - update({ contextToken }, response.config); - } - return response; - }; -} diff --git a/packages/api-client-old/src/services/CartServiceTests/addCartItems.spec.ts b/packages/api-client-old/src/services/CartServiceTests/addCartItems.spec.ts deleted file mode 100644 index f18e1317f..000000000 --- a/packages/api-client-old/src/services/CartServiceTests/addCartItems.spec.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { addCartItems } from "../.."; -import { defaultInstance } from "../../apiService"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../apiService"); -const mockedApiInstance = defaultInstance; - -describe("CartService - addCartItems", () => { - const mockedPost = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - post: mockedPost, - } as any; - }); - - it("should call valid endpoint and return a cart", async () => { - mockedPost.mockResolvedValueOnce({ - data: {}, - }); - - await addCartItems([ - { - type: "product", - }, - { - type: "credit", - }, - ]); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith("/store-api/checkout/cart/line-item", { - items: [ - { - type: "product", - }, - { - type: "credit", - }, - ], - }); - }); -}); diff --git a/packages/api-client-old/src/services/CartServiceTests/addProductToCart.spec.ts b/packages/api-client-old/src/services/CartServiceTests/addProductToCart.spec.ts deleted file mode 100644 index efcf41478..000000000 --- a/packages/api-client-old/src/services/CartServiceTests/addProductToCart.spec.ts +++ /dev/null @@ -1,127 +0,0 @@ -import { addProductToCart } from "../cartService"; -import { defaultInstance } from "../../apiService"; -import { faker } from "@faker-js/faker"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("CartService - addProductToCart", () => { - const mockedPost = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - post: mockedPost, - } as any; - }); - - it("should call valid endpoint and return a cart", async () => { - mockedPost.mockResolvedValueOnce({ - data: { - name: faker.commerce.productName(), - token: faker.string.uuid(), - lineItems: [ - { - id: faker.string.uuid(), - label: faker.commerce.productName(), - quantity: 5, - payload: { - productNumber: faker.string.uuid(), - }, - }, - { - id: "044a190a54ab4f06803909c3ee8063ef", - label: faker.commerce.productName(), - quantity: 5, - payload: { - productNumber: faker.string.uuid(), - }, - }, - ], - }, - }); - - let productId = "044a190a54ab4f06803909c3ee8063ef"; - - const result = await addProductToCart(productId, 1); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith("/store-api/checkout/cart/line-item", { - items: [ - { - quantity: 1, - referencedId: "044a190a54ab4f06803909c3ee8063ef", - type: "product", - id: "044a190a54ab4f06803909c3ee8063ef", - }, - ], - }); - - expect(result.lineItems).toHaveLength(2); - }); - - it("should throw unhandled 400 error when non-existing productID given", async () => { - mockedPost.mockRejectedValueOnce(new Error("400: FRAMEWORK__INVALID_UUID")); - - let productId = "someNonExistingProductId"; - - expect(addProductToCart(productId, 1)).rejects.toThrow( - "400: FRAMEWORK__INVALID_UUID", - ); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith( - "/store-api/checkout/cart/line-item", - - { - items: [ - { - quantity: 1, - referencedId: "someNonExistingProductId", - type: "product", - id: "someNonExistingProductId", - }, - ], - }, - ); - }); - - it("should throw unhandled 404 error when empty productId given", async () => { - mockedPost.mockRejectedValueOnce(new Error("404: Not Found")); - - let productId = ""; - - expect(addProductToCart(productId, 2)).rejects.toThrow("404: Not Found"); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith("/store-api/checkout/cart/line-item", { - items: [ - { - referencedId: "", - type: "product", - quantity: 2, - id: "", - }, - ], - }); - }); - - it("should send quantity 1 on 0 value", async () => { - mockedPost.mockResolvedValueOnce({ - data: { - data: { - name: faker.commerce.productName(), - }, - }, - }); - await addProductToCart("qwe", 0); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith("/store-api/checkout/cart/line-item", { - items: [ - { - quantity: 1, - referencedId: "qwe", - type: "product", - id: "qwe", - }, - ], - }); - }); -}); diff --git a/packages/api-client-old/src/services/CartServiceTests/addPromotionCode.spec.ts b/packages/api-client-old/src/services/CartServiceTests/addPromotionCode.spec.ts deleted file mode 100644 index b581aef53..000000000 --- a/packages/api-client-old/src/services/CartServiceTests/addPromotionCode.spec.ts +++ /dev/null @@ -1,58 +0,0 @@ -import { addPromotionCode } from "../.."; -import { defaultInstance } from "../../apiService"; -import { faker } from "@faker-js/faker"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("CartService - addPromotionCode", () => { - const mockedPost = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - post: mockedPost, - } as any; - }); - - it("should call valid endpoint and return a cart", async () => { - mockedPost.mockResolvedValueOnce({ - data: { - name: faker.string.uuid(), - token: faker.string.uuid(), - price: { - netPrice: 150, - }, - lineItems: { - type: "promotion", - payload: { - code: "3a64e872ca404522a2c5d43ebc751e6b", - }, - }, - }, - }); - - let promotionCode = "3a64e872ca404522a2c5d43ebc751e6b"; - - const result = await addPromotionCode(promotionCode); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith("/store-api/checkout/cart/line-item", { - items: [ - { referencedId: "3a64e872ca404522a2c5d43ebc751e6b", type: "promotion" }, - ], - }); - expect(result.price.netPrice).toEqual(150); - }); - - it("should throw unhandled 404 error when empty promotion code given", async () => { - mockedPost.mockRejectedValueOnce(new Error("404: Not Found")); - - let promotionCode = ""; - - expect(addPromotionCode(promotionCode)).rejects.toThrow("404: Not Found"); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith("/store-api/checkout/cart/line-item", { - items: [{ referencedId: "", type: "promotion" }], - }); - }); -}); diff --git a/packages/api-client-old/src/services/CartServiceTests/changeCartItemQuantity.spec.ts b/packages/api-client-old/src/services/CartServiceTests/changeCartItemQuantity.spec.ts deleted file mode 100644 index a0fb160f0..000000000 --- a/packages/api-client-old/src/services/CartServiceTests/changeCartItemQuantity.spec.ts +++ /dev/null @@ -1,101 +0,0 @@ -import { changeCartItemQuantity } from "../cartService"; -import { defaultInstance } from "../../apiService"; -import { faker } from "@faker-js/faker"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("CartService - changeCartItemQuantity", () => { - const mockedPatch = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - patch: mockedPatch, - } as any; - }); - - it("should call valid endpoint and return cart with no items", async () => { - mockedPatch.mockResolvedValueOnce({ - data: { - name: faker.string.uuid(), - token: faker.string.uuid(), - lineItems: [ - { - id: "geawq90a5dab4206843d0vc3sa8wefdf", - label: faker.commerce.productName(), - quantity: 3, - payload: { - productNumber: faker.string.uuid, - }, - }, - ], - }, - }); - - let lineItemId = "geawq90a5dab4206843d0vc3sa8wefdf"; - - const result = await changeCartItemQuantity(lineItemId, 3); - expect(mockedPatch).toBeCalledTimes(1); - expect(mockedPatch).toBeCalledWith("/store-api/checkout/cart/line-item", { - items: [{ quantity: 3, id: "geawq90a5dab4206843d0vc3sa8wefdf" }], - }); - expect(result.lineItems[0].quantity).toEqual(3); - }); - - it("should throw unhandled 400 error when non-existing lineItemId given", async () => { - mockedPatch.mockRejectedValueOnce( - new Error("400: CHECKOUT__CART_LINEITEM_NOT_FOUND"), - ); - - let lineItemId = "someNonExistingLineItemId"; - - expect(changeCartItemQuantity(lineItemId, 1)).rejects.toThrow( - "400: CHECKOUT__CART_LINEITEM_NOT_FOUND", - ); - expect(mockedPatch).toBeCalledTimes(1); - expect(mockedPatch).toBeCalledWith("/store-api/checkout/cart/line-item", { - items: [ - { - quantity: 1, - id: "someNonExistingLineItemId", - }, - ], - }); - }); - - it("should throw unhandled 400 error when negative quantity given", async () => { - mockedPatch.mockRejectedValueOnce( - new Error("400: CHECKOUT__CART_INVALID_LINEITEM_QUANTITY"), - ); - - let lineItemId = "geawq90a5dab4206843d0vc3sa8wefdf"; - - expect(changeCartItemQuantity(lineItemId, -2)).rejects.toThrow( - "400: CHECKOUT__CART_INVALID_LINEITEM_QUANTITY", - ); - expect(mockedPatch).toBeCalledTimes(1); - expect(mockedPatch).toBeCalledWith("/store-api/checkout/cart/line-item", { - items: [ - { - id: "geawq90a5dab4206843d0vc3sa8wefdf", - quantity: -2, - }, - ], - }); - }); - - it("should call api with default value of quantity", async () => { - mockedPatch.mockResolvedValueOnce({ - data: {}, - }); - - let lineItemId = "geawq90a5dab4206843d0vc3sa8wefdf"; - - await changeCartItemQuantity(lineItemId); - expect(mockedPatch).toBeCalledTimes(1); - expect(mockedPatch).toBeCalledWith("/store-api/checkout/cart/line-item", { - items: [{ quantity: 1, id: "geawq90a5dab4206843d0vc3sa8wefdf" }], - }); - }); -}); diff --git a/packages/api-client-old/src/services/CartServiceTests/clearCart.spec.ts b/packages/api-client-old/src/services/CartServiceTests/clearCart.spec.ts deleted file mode 100644 index 0041c26da..000000000 --- a/packages/api-client-old/src/services/CartServiceTests/clearCart.spec.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { clearCart } from "../cartService"; -import { defaultInstance } from "../../apiService"; -import { faker } from "@faker-js/faker"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("CartService - clearCart", () => { - let contextToken = faker.string.uuid(); - - const mockedPost = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - post: mockedPost, - } as any; - }); - - it("should return a context token", async () => { - mockedPost.mockResolvedValueOnce({ - data: { "sw-context-token": contextToken }, - }); - - const result = await clearCart(); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith("/store-api/checkout/cart"); - expect(result.contextToken).toEqual(contextToken); - }); -}); diff --git a/packages/api-client-old/src/services/CartServiceTests/getCart.spec.ts b/packages/api-client-old/src/services/CartServiceTests/getCart.spec.ts deleted file mode 100644 index b2576b0df..000000000 --- a/packages/api-client-old/src/services/CartServiceTests/getCart.spec.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { getCart } from "../cartService"; -import { defaultInstance } from "../../apiService"; -import { faker } from "@faker-js/faker"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("CartService - getCart", () => { - const mockedGet = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - get: mockedGet, - } as any; - }); - it("should return existing cart object", async () => { - mockedGet.mockResolvedValueOnce({ - data: { - data: { - name: faker.string.uuid(), - token: faker.string.uuid(), - lineItems: [ - { - id: faker.string.uuid(), - label: faker.commerce.productName(), - quantity: 5, - payload: { - productNumber: faker.string.uuid(), - }, - }, - { - id: faker.string.uuid(), - label: faker.commerce.productName(), - quantity: 3, - payload: { - productNumber: faker.string.uuid(), - }, - }, - ], - }, - }, - }); - - const result = await getCart(); - expect(mockedGet).toBeCalledTimes(1); - expect(mockedGet).toBeCalledWith("/store-api/checkout/cart"); - expect(result.lineItems).not.toBeNull(); - }); -}); diff --git a/packages/api-client-old/src/services/CartServiceTests/removeCartItem.spec.ts b/packages/api-client-old/src/services/CartServiceTests/removeCartItem.spec.ts deleted file mode 100644 index e06ce3b3e..000000000 --- a/packages/api-client-old/src/services/CartServiceTests/removeCartItem.spec.ts +++ /dev/null @@ -1,54 +0,0 @@ -import { removeCartItem } from "../cartService"; -import { defaultInstance } from "../../apiService"; -import { faker } from "@faker-js/faker"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("CartService - removeCartItem", () => { - const mockedDelete = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - delete: mockedDelete, - } as any; - }); - - it("should call valid endpoint and return cart without deleted item", async () => { - mockedDelete.mockResolvedValueOnce({ - data: { - data: { - name: faker.string.uuid(), - token: faker.string.uuid(), - lineItems: [], - }, - }, - }); - - let lineItemId = "geawq90a5dab4206843d0vc3sa8wefdf"; - - const result = await removeCartItem(lineItemId); - expect(mockedDelete).toBeCalledTimes(1); - expect(mockedDelete).toBeCalledWith( - "/store-api/checkout/cart/line-item?ids[]=geawq90a5dab4206843d0vc3sa8wefdf", - ); - expect(result.lineItems).toBeUndefined(); - }); - - it("should throw unhandled 400 error when non-existing lineItemId given", async () => { - mockedDelete.mockRejectedValueOnce( - new Error("400: CHECKOUT__CART_LINEITEM_NOT_FOUND"), - ); - - let lineItemId = "someNonExistingLineItemId"; - - expect(removeCartItem(lineItemId)).rejects.toThrow( - "400: CHECKOUT__CART_LINEITEM_NOT_FOUND", - ); - expect(mockedDelete).toBeCalledTimes(1); - expect(mockedDelete).toBeCalledWith( - "/store-api/checkout/cart/line-item?ids[]=someNonExistingLineItemId", - ); - }); -}); diff --git a/packages/api-client-old/src/services/CategoryServiceTests/getCategories.spec.ts b/packages/api-client-old/src/services/CategoryServiceTests/getCategories.spec.ts deleted file mode 100644 index a29bbd955..000000000 --- a/packages/api-client-old/src/services/CategoryServiceTests/getCategories.spec.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { getCategories } from "../categoryService"; -import { defaultInstance } from "../../apiService"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -const consoleWarnSpy = vi.spyOn(console, "warn"); - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("CategoryService - getCategories", () => { - const mockedPost = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - post: mockedPost, - } as any; - consoleWarnSpy.mockImplementation(() => {}); - }); - it("should return array with categories", async () => { - mockedPost.mockResolvedValueOnce({ data: { total: 22 } }); - - const result = await getCategories(); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith("/store-api/category", undefined); - expect(result.total).toEqual(22); - }); -}); diff --git a/packages/api-client-old/src/services/CategoryServiceTests/getCategory.spec.ts b/packages/api-client-old/src/services/CategoryServiceTests/getCategory.spec.ts deleted file mode 100644 index 6d2005c33..000000000 --- a/packages/api-client-old/src/services/CategoryServiceTests/getCategory.spec.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { getCategory } from "../categoryService"; -import { defaultInstance } from "../../apiService"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("CategoryService - getCategory", () => { - const mockedGet = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - get: mockedGet, - } as any; - }); - it("should return chosen category - without associated products by default", async () => { - mockedGet.mockResolvedValueOnce({ - data: { - id: "3a64e872ca404522a2c5d43ebc751e6b", - products: null, - }, - }); - const categoryId = "3a64e872ca404522a2c5d43ebc751e6b"; - const result = await getCategory(categoryId); - expect(mockedGet).toBeCalledTimes(1); - expect(mockedGet).toBeCalledWith( - "/store-api/category/3a64e872ca404522a2c5d43ebc751e6b", - ); - expect(result).toHaveProperty("id"); - expect(result.id).toEqual(categoryId); - expect(result).toHaveProperty("products"); - expect(result.products).toBeNull(); - }); -}); diff --git a/packages/api-client-old/src/services/CheckoutServiceTests/cancelOrder.spec.ts b/packages/api-client-old/src/services/CheckoutServiceTests/cancelOrder.spec.ts deleted file mode 100644 index e3ceabef7..000000000 --- a/packages/api-client-old/src/services/CheckoutServiceTests/cancelOrder.spec.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { cancelOrder } from "../checkoutService"; -import { defaultInstance } from "../../apiService"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("CheckoutService", () => { - const mockedPost = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - post: mockedPost, - } as any; - }); - describe("cancelOrder", () => { - it("should invoke post method to the cancel order endpoint with corresponding orderId parameter", async () => { - mockedPost.mockResolvedValueOnce({}); - - const result = await cancelOrder("some-order-id"); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith("/store-api/order/state/cancel", { - orderId: "some-order-id", - }); - expect(result).toBeUndefined(); - }); - }); -}); diff --git a/packages/api-client-old/src/services/CheckoutServiceTests/changeOrderPaymentMethod.spec.ts b/packages/api-client-old/src/services/CheckoutServiceTests/changeOrderPaymentMethod.spec.ts deleted file mode 100644 index 6b064b707..000000000 --- a/packages/api-client-old/src/services/CheckoutServiceTests/changeOrderPaymentMethod.spec.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { changeOrderPaymentMethod } from "../checkoutService"; -import { defaultInstance } from "../../apiService"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("CheckoutService", () => { - const mockedPost = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - post: mockedPost, - } as any; - }); - describe("changeOrderPaymentMethod", () => { - it("should invoke post method to the appriopriate endpoint with corresponding parameters", async () => { - mockedPost.mockResolvedValueOnce({}); - - const result = await changeOrderPaymentMethod( - "some-order-id", - "some-payment-id", - ); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith("/store-api/order/payment", { - orderId: "some-order-id", - paymentMethodId: "some-payment-id", - }); - expect(result).toBeUndefined(); - }); - }); -}); diff --git a/packages/api-client-old/src/services/CheckoutServiceTests/createOrder.spec.ts b/packages/api-client-old/src/services/CheckoutServiceTests/createOrder.spec.ts deleted file mode 100644 index bddee635b..000000000 --- a/packages/api-client-old/src/services/CheckoutServiceTests/createOrder.spec.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { createOrder } from "../checkoutService"; -import { defaultInstance } from "../../apiService"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("CheckoutService createOrder", () => { - const mockedPost = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - post: mockedPost, - } as any; - }); - describe("createOrder", () => { - it("should return undefined when there is no data property in the response", async () => { - mockedPost.mockResolvedValueOnce({}); - - const result = await createOrder(); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith("/store-api/checkout/order", undefined); - expect(result).toBeUndefined(); - }); - it("should return newly added order object", async () => { - mockedPost.mockResolvedValueOnce({ - data: { - id: "new-order-id", - }, - }); - - const result = await createOrder(); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith("/store-api/checkout/order", undefined); - expect(result).toHaveProperty("id"); - }); - it("should make a post request including provided payload", async () => { - mockedPost.mockResolvedValueOnce({ - data: { - id: "new-order-id", - }, - }); - - await createOrder({ - customerComment: "Please send it packed as a gift", - }); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith("/store-api/checkout/order", { - customerComment: "Please send it packed as a gift", - }); - }); - }); -}); diff --git a/packages/api-client-old/src/services/CheckoutServiceTests/getOrderDetails.spec.ts b/packages/api-client-old/src/services/CheckoutServiceTests/getOrderDetails.spec.ts deleted file mode 100644 index 7ca1fa2c0..000000000 --- a/packages/api-client-old/src/services/CheckoutServiceTests/getOrderDetails.spec.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { getOrderDetails } from "../checkoutService"; -import { defaultInstance } from "../../apiService"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("CheckoutService", () => { - const mockedPost = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - post: mockedPost, - } as any; - }); - describe("getOrderDetails", () => { - it("should invoke post method to the order details endpoint with corresponding orderId parameter - no response", async () => { - mockedPost.mockResolvedValueOnce({}); - - const result = await getOrderDetails("some-order-id"); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith("/store-api/order", { - filter: [{ field: "id", type: "equals", value: "some-order-id" }], - }); - expect(result).toBeUndefined(); - }); - - it("should invoke post method to the order details endpoint with corresponding orderId parameter - proper response", async () => { - mockedPost.mockResolvedValueOnce({ - data: { - orders: { - elements: [ - { - id: "some-order-id", - }, - ], - }, - }, - }); - - const result = await getOrderDetails("some-order-id"); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith("/store-api/order", { - filter: [{ field: "id", type: "equals", value: "some-order-id" }], - }); - expect(result).toStrictEqual({ id: "some-order-id" }); - }); - }); -}); diff --git a/packages/api-client-old/src/services/CheckoutServiceTests/getStoreOrderPaymentUrl.spec.ts b/packages/api-client-old/src/services/CheckoutServiceTests/getStoreOrderPaymentUrl.spec.ts deleted file mode 100644 index 5a8c5c108..000000000 --- a/packages/api-client-old/src/services/CheckoutServiceTests/getStoreOrderPaymentUrl.spec.ts +++ /dev/null @@ -1,133 +0,0 @@ -import { handlePayment } from "../checkoutService"; -import { defaultInstance } from "../../apiService"; -import { describe, expect, it, beforeEach, vi, afterAll } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockApiInstance = defaultInstance; - -describe("CheckoutService - handlePayment", () => { - const mockedGet = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockApiInstance.invoke = { - get: mockedGet, - } as any; - }); - - it("should invoke correct API endpoint with given parameters", async () => { - mockedGet.mockResolvedValueOnce({ data: {} }); - await handlePayment({ - orderId: "cd1a64c7166f42fa88b212b81e611d57", - finishUrl: "https://some.finish.url.com", - errorUrl: "https://some.error.url.com", - }); - expect(mockedGet).toBeCalledTimes(1); - expect(mockedGet).toHaveBeenCalledWith("/store-api/handle-payment", { - params: { - orderId: "cd1a64c7166f42fa88b212b81e611d57", - errorUrl: "https://some.error.url.com", - finishUrl: "https://some.finish.url.com", - paymentDetails: undefined, - }, - }); - }); - - it("should throw an error when data is incorrect", async () => { - mockedGet.mockRejectedValueOnce(new Error("404")); - expect(handlePayment(null as any)).rejects.toThrowError( - "handlePayment method requires orderId", - ); - expect(mockedGet).not.toBeCalled(); - }); - - it("should throw an error when data has missing orderId", async () => { - mockedGet.mockRejectedValueOnce(new Error("404")); - expect(handlePayment({} as any)).rejects.toThrowError( - "handlePayment method requires orderId", - ); - expect(mockedGet).not.toBeCalled(); - }); - - it("should return correct data for orderId", async () => { - mockedGet.mockResolvedValueOnce({ - data: { - redirectResponse: null, - apiAlias: "array_struct", - }, - }); - const result = await handlePayment({ - orderId: "cd1a64c7166f42fa88b212b81e611d57", - }); - expect(result).toEqual({ - redirectResponse: null, - apiAlias: "array_struct", - }); - }); - - describe("WebKit browsers", () => { - const originalUserAgent = navigator.userAgent; - let mockedUserAgent: string; - beforeEach(() => { - mockedUserAgent = "Mozilla/5.0 (WebKit)"; - global.sessionStorage = { - getItem: vi.fn(), - removeItem: vi.fn(), - setItem: vi.fn(), - } as any; - global.navigator = { - userAgent: mockedUserAgent, - } as any; - }); - afterAll(() => { - global.navigator = { - userAgent: originalUserAgent, - } as any; - global.sessionStorage = undefined as any; - }); - - it("should store context token in sessionStorage", async () => { - mockApiInstance.config.contextToken = "mockedContextToken"; - mockedGet.mockResolvedValueOnce({ - data: { - redirectResponse: null, - apiAlias: "array_struct", - }, - }); - await handlePayment({ - orderId: "cd1a64c7166f42fa88b212b81e611d57", - }); - expect(sessionStorage.setItem).toBeCalledWith( - "sw-context-token", - "mockedContextToken", - ); - }); - it("should not fail when sessionStorage does not exist", async () => { - global.sessionStorage = undefined as any; - mockApiInstance.config.contextToken = "someContext"; - mockedGet.mockResolvedValueOnce({ - data: { - redirectResponse: null, - apiAlias: "array_struct", - }, - }); - await handlePayment({ - orderId: "cd1a64c7166f42fa88b212b81e611d57", - }); - expect(sessionStorage).toBeUndefined(); - }); - it("should not fail when navigator does not exist", async () => { - global.navigator = undefined as any; - mockApiInstance.config.contextToken = "someContext"; - mockedGet.mockResolvedValueOnce({ - data: { - redirectResponse: null, - apiAlias: "array_struct", - }, - }); - await handlePayment({ - orderId: "cd1a64c7166f42fa88b212b81e611d57", - }); - expect(navigator).toBeUndefined(); - }); - }); -}); diff --git a/packages/api-client-old/src/services/ContextServiceTests/getAvailableCountries.spec.ts b/packages/api-client-old/src/services/ContextServiceTests/getAvailableCountries.spec.ts deleted file mode 100644 index 328f34eef..000000000 --- a/packages/api-client-old/src/services/ContextServiceTests/getAvailableCountries.spec.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { defaultInstance } from "../../apiService"; -import { getAvailableCountries } from "../contextService"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("ContextService - getAvailableCountries", () => { - const mockedPost = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - post: mockedPost, - } as any; - }); - it("should return array with countries", async () => { - mockedPost.mockResolvedValueOnce({ data: { total: 2 } }); - - const result = await getAvailableCountries(); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith("/store-api/country", { - associations: { - states: {}, - }, - }); - expect(result.total).toEqual(2); - }); -}); diff --git a/packages/api-client-old/src/services/ContextServiceTests/getAvailableCurrencies.spec.ts b/packages/api-client-old/src/services/ContextServiceTests/getAvailableCurrencies.spec.ts deleted file mode 100644 index 8972bddf2..000000000 --- a/packages/api-client-old/src/services/ContextServiceTests/getAvailableCurrencies.spec.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { defaultInstance } from "../../apiService"; -import { getAvailableCurrencies } from "../contextService"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("ContextService - getAvailableCurrencies", () => { - const mockedGet = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - get: mockedGet, - } as any; - }); - it("should return array with currencies", async () => { - mockedGet.mockResolvedValueOnce({ data: [{ iso: "EUR" }] }); - const result = await getAvailableCurrencies(); - expect(mockedGet).toBeCalledTimes(1); - expect(mockedGet).toBeCalledWith("/store-api/currency"); - expect(result).toEqual([{ iso: "EUR" }]); - }); -}); diff --git a/packages/api-client-old/src/services/ContextServiceTests/getAvailableLanguages.spec.ts b/packages/api-client-old/src/services/ContextServiceTests/getAvailableLanguages.spec.ts deleted file mode 100644 index 547355fa1..000000000 --- a/packages/api-client-old/src/services/ContextServiceTests/getAvailableLanguages.spec.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { defaultInstance } from "../../apiService"; -import { getAvailableLanguages } from "../contextService"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("ContextService - getAvailableLanguages", () => { - const mockedGet = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - get: mockedGet, - } as any; - }); - it("should return array with languages", async () => { - mockedGet.mockResolvedValueOnce({ data: [{ id: 2, code: "en" }] }); - - const result = await getAvailableLanguages(); - expect(mockedGet).toBeCalledTimes(1); - expect(mockedGet).toBeCalledWith("/store-api/language"); - expect(result).toEqual([{ id: 2, code: "en" }]); - }); -}); diff --git a/packages/api-client-old/src/services/ContextServiceTests/getAvailablePaymentMethods.spec.ts b/packages/api-client-old/src/services/ContextServiceTests/getAvailablePaymentMethods.spec.ts deleted file mode 100644 index 73bfd3dec..000000000 --- a/packages/api-client-old/src/services/ContextServiceTests/getAvailablePaymentMethods.spec.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { defaultInstance } from "../../apiService"; -import { getAvailablePaymentMethods } from "../contextService"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("ContextService - getAvailablePaymentMethods", () => { - const mockedGet = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - get: mockedGet, - } as any; - }); - it("should return array with payment methods", async () => { - mockedGet.mockResolvedValueOnce({ data: [{ id: 1 }, { id: 2 }] }); - - const result = await getAvailablePaymentMethods(); - expect(mockedGet).toBeCalledTimes(1); - expect(mockedGet).toBeCalledWith("/store-api/payment-method", { - params: {}, - }); - expect(result).toHaveLength(2); - }); -}); diff --git a/packages/api-client-old/src/services/ContextServiceTests/getAvailableSalutations.spec.ts b/packages/api-client-old/src/services/ContextServiceTests/getAvailableSalutations.spec.ts deleted file mode 100644 index cf4c18016..000000000 --- a/packages/api-client-old/src/services/ContextServiceTests/getAvailableSalutations.spec.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { defaultInstance } from "../../apiService"; -import { getAvailableSalutations } from "../contextService"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("ContextService - getAvailableSalutations", () => { - const mockedGet = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - get: mockedGet, - } as any; - }); - it("should return array with available salutations", async () => { - mockedGet.mockResolvedValueOnce({ data: { total: 2 } }); - - const result = await getAvailableSalutations(); - expect(mockedGet).toBeCalledTimes(1); - expect(mockedGet).toBeCalledWith("/store-api/salutation"); - expect(result.total).toEqual(2); - }); -}); diff --git a/packages/api-client-old/src/services/ContextServiceTests/getAvailableShippingMethods.spec.ts b/packages/api-client-old/src/services/ContextServiceTests/getAvailableShippingMethods.spec.ts deleted file mode 100644 index 1d3720cfc..000000000 --- a/packages/api-client-old/src/services/ContextServiceTests/getAvailableShippingMethods.spec.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { defaultInstance } from "../../apiService"; -import { getAvailableShippingMethods } from "../contextService"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("ContextService - getAvailableShippingMethods", () => { - const mockedPost = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - post: mockedPost, - } as any; - }); - it("should return array with shipping methods", async () => { - mockedPost.mockResolvedValueOnce({ data: [{ id: 1 }, { id: 2 }] }); - - const result = await getAvailableShippingMethods(); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith("/store-api/shipping-method", {}); - expect(result).toHaveLength(2); - }); -}); diff --git a/packages/api-client-old/src/services/ContextServiceTests/getPaymentMethodDetails.spec.ts b/packages/api-client-old/src/services/ContextServiceTests/getPaymentMethodDetails.spec.ts deleted file mode 100644 index 4625f60cb..000000000 --- a/packages/api-client-old/src/services/ContextServiceTests/getPaymentMethodDetails.spec.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { defaultInstance } from "../../apiService"; -import { getPaymentMethodDetails } from "../contextService"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("ContextService - getPaymentMethodDetails", () => { - const mockedGet = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - get: mockedGet, - } as any; - }); - it("should return an object of specific payment method details", async () => { - mockedGet.mockResolvedValueOnce({ - data: { - elements: [ - { - id: "paypal", - }, - ], - }, - }); - - const result = await getPaymentMethodDetails("paypal"); - expect(mockedGet).toBeCalledTimes(1); - expect(mockedGet).toBeCalledWith("/store-api/payment-method", { - params: { "filter[id]": "paypal" }, - }); - expect(result).toHaveProperty("id"); - }); - it("should return undefined if the response does not contain specific data", async () => { - mockedGet.mockResolvedValueOnce({ - data: undefined, - }); - - const result = await getPaymentMethodDetails("paypal"); - - expect(result).toBeUndefined(); - }); -}); diff --git a/packages/api-client-old/src/services/ContextServiceTests/getSessionContext.spec.ts b/packages/api-client-old/src/services/ContextServiceTests/getSessionContext.spec.ts deleted file mode 100644 index fb0dadd38..000000000 --- a/packages/api-client-old/src/services/ContextServiceTests/getSessionContext.spec.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { defaultInstance } from "../../apiService"; -import { getSessionContext } from "../contextService"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("ContextService - getSessionContext", () => { - const mockedGet = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - get: mockedGet, - } as any; - }); - it("should return sessionContext", async () => { - mockedGet.mockResolvedValueOnce({ data: { token: "qwerty" } }); - - const result = await getSessionContext(); - expect(mockedGet).toBeCalledTimes(1); - expect(mockedGet).toBeCalledWith("/store-api/context"); - expect(result.token).toEqual("qwerty"); - }); -}); diff --git a/packages/api-client-old/src/services/ContextServiceTests/getShippingMethodDetails.spec.ts b/packages/api-client-old/src/services/ContextServiceTests/getShippingMethodDetails.spec.ts deleted file mode 100644 index eab2304c8..000000000 --- a/packages/api-client-old/src/services/ContextServiceTests/getShippingMethodDetails.spec.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { defaultInstance } from "../../apiService"; -import { getShippingMethodDetails } from "../contextService"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("ContextService - getShippingMethodDetails", () => { - const mockedGet = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - get: mockedGet, - } as any; - }); - it("should return an object of specific shipping method details", async () => { - mockedGet.mockResolvedValueOnce({ - data: { - elements: [ - { - id: "dhl", - }, - ], - }, - }); - - const result = await getShippingMethodDetails("dhl"); - expect(mockedGet).toBeCalledTimes(1); - expect(mockedGet).toBeCalledWith("/store-api/shipping-method", { - params: { "filter[id]": "dhl" }, - }); - expect(result).toHaveProperty("id"); - expect(result.id).toBe("dhl"); - }); - it("should return undefined if the response does not contain specific data", async () => { - mockedGet.mockResolvedValueOnce({ - data: undefined, - }); - - const result = await getShippingMethodDetails("dhl"); - expect(result).toBeUndefined(); - }); -}); diff --git a/packages/api-client-old/src/services/ContextServiceTests/getUserCountry.spec.ts b/packages/api-client-old/src/services/ContextServiceTests/getUserCountry.spec.ts deleted file mode 100644 index 23d90690e..000000000 --- a/packages/api-client-old/src/services/ContextServiceTests/getUserCountry.spec.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { defaultInstance } from "../../apiService"; -import { getUserCountry } from "../contextService"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("ContextService - getUserCountry", () => { - const mockedGet = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - get: mockedGet, - } as any; - }); - it("should return user salutation object", async () => { - mockedGet.mockResolvedValueOnce({ - data: { elements: [{ name: "Poland" }] }, - }); - - const countryId = "123123123"; - const result = await getUserCountry(countryId); - expect(mockedGet).toBeCalledTimes(1); - expect(mockedGet).toBeCalledWith("/store-api/country", { - params: { "filter[id]": countryId }, - }); - expect(result.name).toEqual("Poland"); - }); - it("should not return user salutation object if response does not contain any data", async () => { - mockedGet.mockResolvedValueOnce({ - data: undefined, - }); - - const result = await getUserCountry("12345"); - - expect(result).toBeUndefined(); - }); -}); diff --git a/packages/api-client-old/src/services/ContextServiceTests/getUserSalutation.spec.ts b/packages/api-client-old/src/services/ContextServiceTests/getUserSalutation.spec.ts deleted file mode 100644 index 3b45097e9..000000000 --- a/packages/api-client-old/src/services/ContextServiceTests/getUserSalutation.spec.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { defaultInstance } from "../../apiService"; -import { getUserSalutation } from "../contextService"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("ContextService - getUserCountry", () => { - const mockedGet = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - get: mockedGet, - } as any; - }); - it("should return user salutation object", async () => { - mockedGet.mockResolvedValueOnce({ - data: { elements: [{ displayName: "Mrs." }] }, - }); - - const salutationId = "123123123"; - const result = await getUserSalutation(salutationId); - expect(mockedGet).toBeCalledTimes(1); - expect(mockedGet).toBeCalledWith("/store-api/salutation", { - params: { "filter[id]": salutationId }, - }); - expect(result.displayName).toEqual("Mrs."); - }); - it("should not return user salutation object if the response does not contain any data", async () => { - mockedGet.mockResolvedValueOnce({ - data: undefined, - }); - - const result = await getUserSalutation("12345"); - expect(result).toBeUndefined(); - }); -}); diff --git a/packages/api-client-old/src/services/ContextServiceTests/setCurrentBillingAddress.spec.ts b/packages/api-client-old/src/services/ContextServiceTests/setCurrentBillingAddress.spec.ts deleted file mode 100644 index a363b7eef..000000000 --- a/packages/api-client-old/src/services/ContextServiceTests/setCurrentBillingAddress.spec.ts +++ /dev/null @@ -1,62 +0,0 @@ -import { defaultInstance } from "../../apiService"; -import { setCurrentBillingAddress } from "../contextService"; -import { update } from "../.."; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("ContextService - setCurrentBillingAddress", () => { - const mockedPatch = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - patch: mockedPatch, - } as any; - }); - - describe("with contextToken given", () => { - beforeEach(() => { - update({ contextToken: "NWDdcRTTWoPk4Ngv13z5NDMMsDFRb9W6" }); - }); - - it("should return context token", async () => { - mockedPatch.mockResolvedValueOnce({ - data: { "sw-context-token": "NWDdcRTTWoPk4Ngv13z5NDMMsDFRb9W6" }, - }); - - let newBillingAddressId = "45f96f681f9d4834b29e9e15df3a7149"; - - const result = await setCurrentBillingAddress(newBillingAddressId); - - expect(mockedPatch).toBeCalledTimes(1); - expect(mockedPatch).toBeCalledWith("/store-api/context", { - billingAddressId: "45f96f681f9d4834b29e9e15df3a7149", - }); - - expect(result.contextToken).toEqual("NWDdcRTTWoPk4Ngv13z5NDMMsDFRb9W6"); - }); - }); - - describe("without contextToken given", () => { - beforeEach(() => { - update({ contextToken: undefined }); - }); - - it("should return context token", async () => { - mockedPatch.mockResolvedValueOnce({ - data: { "sw-context-token": "NWDdcRTTWoPk4Ngv13z5NDMMsDFRb9W6" }, - }); - - let newBillingAddressId = "45f96f681f9d4834b29e9e15df3a7149"; - - const result = await setCurrentBillingAddress(newBillingAddressId); - expect(mockedPatch).toBeCalledTimes(1); - expect(mockedPatch).toBeCalledWith("/store-api/context", { - billingAddressId: "45f96f681f9d4834b29e9e15df3a7149", - }); - - expect(result.contextToken).toEqual("NWDdcRTTWoPk4Ngv13z5NDMMsDFRb9W6"); - }); - }); -}); diff --git a/packages/api-client-old/src/services/ContextServiceTests/setCurrentCountry.spec.ts b/packages/api-client-old/src/services/ContextServiceTests/setCurrentCountry.spec.ts deleted file mode 100644 index 5bbb5303a..000000000 --- a/packages/api-client-old/src/services/ContextServiceTests/setCurrentCountry.spec.ts +++ /dev/null @@ -1,62 +0,0 @@ -import { defaultInstance } from "../../apiService"; -import { setCurrentCountry } from "../contextService"; -import { update } from "../.."; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("ContextService - setCurrentCountry", () => { - const newCountryId = "28bbf3f6e79145ba8ffc91c409690ab8"; - const contextToken = "NWDdcRTTWoPk4Ngv13z5NDMMsDFRb9W6"; - - const mockedPatch = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - patch: mockedPatch, - } as any; - }); - - describe("with contextToken given", () => { - beforeEach(() => { - update({ contextToken }); - }); - - it("should return context token", async () => { - mockedPatch.mockResolvedValueOnce({ - data: { "sw-context-token": contextToken }, - }); - - const result = await setCurrentCountry(newCountryId); - - expect(mockedPatch).toBeCalledTimes(1); - expect(mockedPatch).toBeCalledWith("/store-api/context", { - countryId: newCountryId, - }); - - expect(result.contextToken).toEqual(contextToken); - }); - }); - - describe("without contextToken given", () => { - beforeEach(() => { - update({ contextToken: undefined }); - }); - - it("should return context token", async () => { - mockedPatch.mockResolvedValueOnce({ - data: { "sw-context-token": contextToken }, - }); - - const result = await setCurrentCountry(newCountryId); - - expect(mockedPatch).toBeCalledTimes(1); - expect(mockedPatch).toBeCalledWith("/store-api/context", { - countryId: "28bbf3f6e79145ba8ffc91c409690ab8", - }); - - expect(result.contextToken).toEqual(contextToken); - }); - }); -}); diff --git a/packages/api-client-old/src/services/ContextServiceTests/setCurrentCurrency.spec.ts b/packages/api-client-old/src/services/ContextServiceTests/setCurrentCurrency.spec.ts deleted file mode 100644 index db615b092..000000000 --- a/packages/api-client-old/src/services/ContextServiceTests/setCurrentCurrency.spec.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { defaultInstance } from "../../apiService"; -import { setCurrentCurrency } from "../contextService"; -import { update } from "../.."; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("ContextService - setCurrentCurrency", () => { - const mockedPatch = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - patch: mockedPatch, - } as any; - }); - - describe("with contextToken given", () => { - beforeEach(() => { - update({ contextToken: "NWDdcRTTWoPk4Ngv13z5NDMMsDFRb9W6" }); - }); - - it("should return context token", async () => { - mockedPatch.mockResolvedValueOnce({ - data: { "sw-context-token": "NWDdcRTTWoPk4Ngv13z5NDMMsDFRb9W6" }, - }); - - let newCurrencyId = "45f96f681f9d4834b29e9e15df3a7149"; - - const result = await setCurrentCurrency(newCurrencyId); - - expect(mockedPatch).toBeCalledTimes(1); - expect(mockedPatch).toBeCalledWith("/store-api/context", { - currencyId: "45f96f681f9d4834b29e9e15df3a7149", - }); - - expect(result.contextToken).toEqual("NWDdcRTTWoPk4Ngv13z5NDMMsDFRb9W6"); - }); - }); - - describe("without contextToken given", () => { - beforeEach(() => { - update({ contextToken: undefined }); - }); - - it("should return context token", async () => { - mockedPatch.mockResolvedValueOnce({ - data: { "sw-context-token": "NWDdcRTTWoPk4Ngv13z5NDMMsDFRb9W6" }, - }); - - let newCurrencyId = "45f96f681f9d4834b29e9e15df3a7149"; - - const result = await setCurrentCurrency(newCurrencyId); - - expect(mockedPatch).toBeCalledTimes(1); - expect(mockedPatch).toBeCalledWith("/store-api/context", { - currencyId: "45f96f681f9d4834b29e9e15df3a7149", - }); - - expect(result.contextToken).toEqual("NWDdcRTTWoPk4Ngv13z5NDMMsDFRb9W6"); - }); - }); -}); diff --git a/packages/api-client-old/src/services/ContextServiceTests/setCurrentLanguage.spec.ts b/packages/api-client-old/src/services/ContextServiceTests/setCurrentLanguage.spec.ts deleted file mode 100644 index 37965433b..000000000 --- a/packages/api-client-old/src/services/ContextServiceTests/setCurrentLanguage.spec.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { defaultInstance } from "../../apiService"; -import { setCurrentLanguage } from "../contextService"; -import { update } from "../.."; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("ContextService - setCurrentLanguage", () => { - const mockedPatch = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - patch: mockedPatch, - } as any; - }); - - describe("with contextToken given", () => { - beforeEach(() => { - update({ contextToken: "NWDdcRTTWoPk4Ngv13z5NDMMsDFRb9W6" }); - }); - - it("should return context token", async () => { - mockedPatch.mockResolvedValueOnce({ - data: { "sw-context-token": "NWDdcRTTWoPk4Ngv13z5NDMMsDFRb9W6" }, - }); - - let newLanguageId = "45f96f681f9d4834b29e9e15df3a7149"; - - const result = await setCurrentLanguage(newLanguageId); - - expect(mockedPatch).toBeCalledTimes(1); - expect(mockedPatch).toBeCalledWith("/store-api/context", { - languageId: "45f96f681f9d4834b29e9e15df3a7149", - }); - - expect(result.contextToken).toEqual("NWDdcRTTWoPk4Ngv13z5NDMMsDFRb9W6"); - }); - }); - - describe("without contextToken given", () => { - beforeEach(() => { - update({ contextToken: undefined }); - }); - - it("should return context token", async () => { - mockedPatch.mockResolvedValueOnce({ - data: { "sw-context-token": "NWDdcRTTWoPk4Ngv13z5NDMMsDFRb9W6" }, - }); - - let newLanguageId = "45f96f681f9d4834b29e9e15df3a7149"; - - const result = await setCurrentLanguage(newLanguageId); - - expect(mockedPatch).toBeCalledTimes(1); - expect(mockedPatch).toBeCalledWith("/store-api/context", { - languageId: "45f96f681f9d4834b29e9e15df3a7149", - }); - - expect(result.contextToken).toEqual("NWDdcRTTWoPk4Ngv13z5NDMMsDFRb9W6"); - }); - }); -}); diff --git a/packages/api-client-old/src/services/ContextServiceTests/setCurrentPaymentMethod.spec.ts b/packages/api-client-old/src/services/ContextServiceTests/setCurrentPaymentMethod.spec.ts deleted file mode 100644 index 5d3ca8e1b..000000000 --- a/packages/api-client-old/src/services/ContextServiceTests/setCurrentPaymentMethod.spec.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { defaultInstance } from "../../apiService"; -import { setCurrentPaymentMethod } from "../contextService"; -import { update } from "../.."; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("ContextService - setCurrentPaymentMethod", () => { - const mockedPatch = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - patch: mockedPatch, - } as any; - }); - - describe("with contextToken given", () => { - beforeEach(() => { - update({ contextToken: "NWDdcRTTWoPk4Ngv13z5NDMMsDFRb9W6" }); - }); - - it("should return context token", async () => { - mockedPatch.mockResolvedValueOnce({ - data: { "sw-context-token": "NWDdcRTTWoPk4Ngv13z5NDMMsDFRb9W6" }, - }); - - let newPaymentMethodId = "45f96f681f9d4834b29e9e15df3a7149"; - - const result = await setCurrentPaymentMethod(newPaymentMethodId); - - expect(mockedPatch).toBeCalledTimes(1); - expect(mockedPatch).toBeCalledWith("/store-api/context", { - paymentMethodId: "45f96f681f9d4834b29e9e15df3a7149", - }); - - expect(result.contextToken).toEqual("NWDdcRTTWoPk4Ngv13z5NDMMsDFRb9W6"); - }); - }); - - describe("without contextToken given", () => { - beforeEach(() => { - update({ contextToken: undefined }); - }); - - it("should return context token", async () => { - mockedPatch.mockResolvedValueOnce({ - data: { "sw-context-token": "NWDdcRTTWoPk4Ngv13z5NDMMsDFRb9W6" }, - }); - - let newPaymentMethodId = "45f96f681f9d4834b29e9e15df3a7149"; - - const result = await setCurrentPaymentMethod(newPaymentMethodId); - - expect(mockedPatch).toBeCalledTimes(1); - expect(mockedPatch).toBeCalledWith("/store-api/context", { - paymentMethodId: "45f96f681f9d4834b29e9e15df3a7149", - }); - - expect(result.contextToken).toEqual("NWDdcRTTWoPk4Ngv13z5NDMMsDFRb9W6"); - }); - }); -}); diff --git a/packages/api-client-old/src/services/ContextServiceTests/setCurrentShippingAddress.spec.ts b/packages/api-client-old/src/services/ContextServiceTests/setCurrentShippingAddress.spec.ts deleted file mode 100644 index c26430fe1..000000000 --- a/packages/api-client-old/src/services/ContextServiceTests/setCurrentShippingAddress.spec.ts +++ /dev/null @@ -1,62 +0,0 @@ -import { defaultInstance } from "../../apiService"; -import { setCurrentShippingAddress } from "../contextService"; -import { update } from "../.."; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("ContextService - setCurrentShippingAddress", () => { - const mockedPatch = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - patch: mockedPatch, - } as any; - }); - - describe("with contextToken given", () => { - beforeEach(() => { - update({ contextToken: "NWDdcRTTWoPk4Ngv13z5NDMMsDFRb9W6" }); - }); - - it("should return context token", async () => { - mockedPatch.mockResolvedValueOnce({ - data: { "sw-context-token": "NWDdcRTTWoPk4Ngv13z5NDMMsDFRb9W6" }, - }); - - let newShippingAddressId = "45f96f681f9d4834b29e9e15df3a7149"; - - const result = await setCurrentShippingAddress(newShippingAddressId); - - expect(mockedPatch).toBeCalledTimes(1); - expect(mockedPatch).toBeCalledWith("/store-api/context", { - shippingAddressId: "45f96f681f9d4834b29e9e15df3a7149", - }); - - expect(result.contextToken).toEqual("NWDdcRTTWoPk4Ngv13z5NDMMsDFRb9W6"); - }); - }); - - describe("without contextToken given", () => { - beforeEach(() => { - update({ contextToken: undefined }); - }); - - it("should return context token", async () => { - mockedPatch.mockResolvedValueOnce({ - data: { "sw-context-token": "NWDdcRTTWoPk4Ngv13z5NDMMsDFRb9W6" }, - }); - - let newShippingAddressId = "45f96f681f9d4834b29e9e15df3a7149"; - - const result = await setCurrentShippingAddress(newShippingAddressId); - expect(mockedPatch).toBeCalledTimes(1); - expect(mockedPatch).toBeCalledWith("/store-api/context", { - shippingAddressId: "45f96f681f9d4834b29e9e15df3a7149", - }); - - expect(result.contextToken).toEqual("NWDdcRTTWoPk4Ngv13z5NDMMsDFRb9W6"); - }); - }); -}); diff --git a/packages/api-client-old/src/services/ContextServiceTests/setCurrentShippingMethod.spec.ts b/packages/api-client-old/src/services/ContextServiceTests/setCurrentShippingMethod.spec.ts deleted file mode 100644 index 33693d8e9..000000000 --- a/packages/api-client-old/src/services/ContextServiceTests/setCurrentShippingMethod.spec.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { defaultInstance } from "../../apiService"; -import { setCurrentShippingMethod } from "../contextService"; -import { update } from "../.."; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("ContextService - setCurrentShippingMethod", () => { - const mockedPatch = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - patch: mockedPatch, - } as any; - }); - - describe("with contextToken given", () => { - beforeEach(() => { - update({ contextToken: "NWDdcRTTWoPk4Ngv13z5NDMMsDFRb9W6" }); - }); - - it("should return context token", async () => { - mockedPatch.mockResolvedValueOnce({ - data: { "sw-context-token": "NWDdcRTTWoPk4Ngv13z5NDMMsDFRb9W6" }, - }); - - let newShippingMethodId = "45f96f681f9d4834b29e9e15df3a7149"; - - const result = await setCurrentShippingMethod(newShippingMethodId); - - expect(mockedPatch).toBeCalledTimes(1); - expect(mockedPatch).toBeCalledWith("/store-api/context", { - shippingMethodId: "45f96f681f9d4834b29e9e15df3a7149", - }); - - expect(result.contextToken).toEqual("NWDdcRTTWoPk4Ngv13z5NDMMsDFRb9W6"); - }); - }); - - describe("without contextToken given", () => { - beforeEach(() => { - update({ contextToken: undefined }); - }); - - it("should return context token", async () => { - mockedPatch.mockResolvedValueOnce({ - data: { "sw-context-token": "NWDdcRTTWoPk4Ngv13z5NDMMsDFRb9W6" }, - }); - - let newShippingMethodId = "45f96f681f9d4834b29e9e15df3a7149"; - - const result = await setCurrentShippingMethod(newShippingMethodId); - - expect(mockedPatch).toBeCalledTimes(1); - expect(mockedPatch).toBeCalledWith("/store-api/context", { - shippingMethodId: "45f96f681f9d4834b29e9e15df3a7149", - }); - - expect(result.contextToken).toEqual("NWDdcRTTWoPk4Ngv13z5NDMMsDFRb9W6"); - }); - }); -}); diff --git a/packages/api-client-old/src/services/CustomerServiceTests/confirmAccountRegistration.spec.ts b/packages/api-client-old/src/services/CustomerServiceTests/confirmAccountRegistration.spec.ts deleted file mode 100644 index 0b454206b..000000000 --- a/packages/api-client-old/src/services/CustomerServiceTests/confirmAccountRegistration.spec.ts +++ /dev/null @@ -1,70 +0,0 @@ -import { getCustomerAccountConfirmEndpoint } from "../../endpoints"; -import { defaultInstance } from "../../apiService"; -import { faker } from "@faker-js/faker"; -import { confirmAccountRegistration } from "../customerService"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -const exampleHash = faker.internet.mac(); -const exampleEm = faker.internet.mac(); - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("CustomerService - confirmAccountRegistration", () => { - const mockedPost = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - post: mockedPost, - } as any; - }); - - it("rejects the promise if provided hash or em does not match", async () => { - mockedPost.mockRejectedValueOnce(new Error("400 - invalid hash or em")); - expect( - confirmAccountRegistration({ - hash: exampleHash, - em: exampleEm, - }), - ).rejects.toThrow("400 - invalid hash or em"); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith(getCustomerAccountConfirmEndpoint(), { - hash: exampleHash, - em: exampleEm, - }); - }); - - it("returns customer data if successfully confirmed", async () => { - mockedPost.mockResolvedValueOnce({ - data: { - id: "customer-id", - }, - }); - - const result = await confirmAccountRegistration({ - hash: exampleHash, - em: exampleEm, - }); - expect(result).toStrictEqual({ - id: "customer-id", - }); - }); - - it("should invoke post method with given parameters", async () => { - mockedPost.mockResolvedValueOnce({ - data: { - id: "customer-id", - }, - }); - - await confirmAccountRegistration({ - hash: exampleHash, - em: exampleEm, - }); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith(getCustomerAccountConfirmEndpoint(), { - em: exampleEm, - hash: exampleHash, - }); - }); -}); diff --git a/packages/api-client-old/src/services/CustomerServiceTests/confirmPasswordReset.spec.ts b/packages/api-client-old/src/services/CustomerServiceTests/confirmPasswordReset.spec.ts deleted file mode 100644 index 5e54c13f5..000000000 --- a/packages/api-client-old/src/services/CustomerServiceTests/confirmPasswordReset.spec.ts +++ /dev/null @@ -1,88 +0,0 @@ -import { getConfirmPasswordResetEndpoint } from "../../endpoints"; -import { defaultInstance } from "../../apiService"; -import { faker } from "@faker-js/faker"; -import { confirmPasswordReset } from "../customerService"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -const exampleHash = faker.internet.mac(); -const examplePassword = faker.internet.password(); - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("CustomerService - confirmPasswordReset", () => { - const mockedPost = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - post: mockedPost, - } as any; - }); - - it("rejects the promise if the email do not mach any in Sales Channel", async () => { - mockedPost.mockRejectedValueOnce(new Error("400 - invalid email address")); - expect( - confirmPasswordReset({ - hash: exampleHash, - newPassword: examplePassword, - newPasswordConfirm: examplePassword, - }), - ).rejects.toThrow("400 - invalid email"); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith(getConfirmPasswordResetEndpoint(), { - hash: exampleHash, - newPassword: examplePassword, - newPasswordConfirm: examplePassword, - }); - }); - - it("returns no data if successfully updated", async () => { - mockedPost.mockResolvedValueOnce(null); - - const resultWithFullParams = await confirmPasswordReset({ - hash: exampleHash, - newPassword: examplePassword, - newPasswordConfirm: examplePassword, - }); - expect(resultWithFullParams).toBeFalsy(); - - const resultWithEmptyUrl = await confirmPasswordReset({ - hash: exampleHash, - newPassword: examplePassword, - newPasswordConfirm: examplePassword, - storefrontUrl: "", - }); - expect(resultWithEmptyUrl).toBeFalsy(); - - const resultWithoutUrl = await confirmPasswordReset({ - hash: exampleHash, - newPassword: examplePassword, - newPasswordConfirm: examplePassword, - }); - expect(resultWithoutUrl).toBeFalsy(); - - expect(mockedPost).toBeCalledTimes(3); - expect(mockedPost).toBeCalledWith(getConfirmPasswordResetEndpoint(), { - hash: exampleHash, - newPassword: examplePassword, - newPasswordConfirm: examplePassword, - }); - }); - - it("should set newPasswordConfirm from newPassword", async () => { - await confirmPasswordReset({ - hash: exampleHash, - newPassword: examplePassword, - }); - expect(mockedPost).toBeCalledWith(getConfirmPasswordResetEndpoint(), { - hash: exampleHash, - newPassword: examplePassword, - newPasswordConfirm: examplePassword, - }); - }); - - it("should not invoke post method if params are not provided", async () => { - await confirmPasswordReset(null as any); - expect(mockedPost).not.toBeCalled(); - }); -}); diff --git a/packages/api-client-old/src/services/CustomerServiceTests/createCustomerAddress.spec.ts b/packages/api-client-old/src/services/CustomerServiceTests/createCustomerAddress.spec.ts deleted file mode 100644 index 4bc875df2..000000000 --- a/packages/api-client-old/src/services/CustomerServiceTests/createCustomerAddress.spec.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { faker } from "@faker-js/faker"; -import { createCustomerAddress } from "../customerService"; -import { defaultInstance } from "../../apiService"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("CustomerService - createCustomerAddress", () => { - const newAddressData = { - countryId: faker.string.uuid(), - salutationId: faker.string.uuid(), - firstName: faker.person.firstName(), - lastName: faker.person.lastName(), - zipcode: faker.location.zipCode(), - city: faker.location.city(), - street: faker.location.street(), - }; - const mockedPost = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - post: mockedPost, - } as any; - }); - - it("should return created address id", async () => { - mockedPost.mockResolvedValueOnce({ - data: "2bbb89dfa4664bc581e80b37eaa80fb7", - }); - const result = await createCustomerAddress(newAddressData); - expect(result).toEqual("2bbb89dfa4664bc581e80b37eaa80fb7"); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith( - "/store-api/account/address", - newAddressData, - ); - }); -}); diff --git a/packages/api-client-old/src/services/CustomerServiceTests/deleteCustomerAddress.spec.ts b/packages/api-client-old/src/services/CustomerServiceTests/deleteCustomerAddress.spec.ts deleted file mode 100644 index 15049e3aa..000000000 --- a/packages/api-client-old/src/services/CustomerServiceTests/deleteCustomerAddress.spec.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { getCustomerAddressEndpoint } from "../../endpoints"; -import { defaultInstance } from "../../apiService"; -import { deleteCustomerAddress } from "../customerService"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("CustomerService - deleteCustomerAddress", () => { - const mockedDelete = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - delete: mockedDelete, - } as any; - }); - - it("rejects the promise if the address does not exist", async () => { - mockedDelete.mockRejectedValueOnce( - new Error("400 - customer's address not found"), - ); - expect( - deleteCustomerAddress("2bbb89dfa4664bc681e80b37eaa80fb7"), - ).rejects.toThrow("400 - customer's address not found"); - expect(mockedDelete).toBeCalledTimes(1); - expect(mockedDelete).toBeCalledWith( - getCustomerAddressEndpoint("2bbb89dfa4664bc681e80b37eaa80fb7"), - ); - }); - - it("returns no data if successfully deleted", async () => { - mockedDelete.mockResolvedValue(null); - - await deleteCustomerAddress("2bbb89dfa4664bc681e80b37eaa80fb7"); - expect(mockedDelete).toBeCalledTimes(1); - expect(mockedDelete).toBeCalledWith( - getCustomerAddressEndpoint("2bbb89dfa4664bc681e80b37eaa80fb7"), - ); - }); -}); diff --git a/packages/api-client-old/src/services/CustomerServiceTests/getCustomer.spec.ts b/packages/api-client-old/src/services/CustomerServiceTests/getCustomer.spec.ts deleted file mode 100644 index 2678a0cf0..000000000 --- a/packages/api-client-old/src/services/CustomerServiceTests/getCustomer.spec.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { getCustomer } from "../customerService"; -import { defaultInstance } from "../../apiService"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("CustomerService - getCustomer", () => { - const mockedPost = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - post: mockedPost, - } as any; - }); - - it("should return current customer's data - using correct token", async () => { - mockedPost.mockResolvedValueOnce({ - data: { id: "c370eb5cd1df4d4dbcc78f055b693e79" }, - }); - const result: any = await getCustomer(); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith("/store-api/account/customer", {}); - expect(result).not.toBeNull(); - expect(result.id).toEqual("c370eb5cd1df4d4dbcc78f055b693e79"); - }); - - it("should return null when user not logged in", async () => { - mockedPost.mockRejectedValueOnce({ - statusCode: 403, - }); - const result = await getCustomer(); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith("/store-api/account/customer", {}); - expect(result).toBeNull(); - }); - - it("should throw an error on status code different than 403", async () => { - mockedPost.mockRejectedValueOnce({ - response: { - status: 401, - }, - }); - await expect(getCustomer()).rejects.toThrowError( - "Unexpected getCustomerResponse.", - ); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith("/store-api/account/customer", {}); - }); -}); diff --git a/packages/api-client-old/src/services/CustomerServiceTests/getCustomerAddress.spec.ts b/packages/api-client-old/src/services/CustomerServiceTests/getCustomerAddress.spec.ts deleted file mode 100644 index 9137c5095..000000000 --- a/packages/api-client-old/src/services/CustomerServiceTests/getCustomerAddress.spec.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { getCustomerAddress } from "../customerService"; -import { getCustomerAddressEndpoint } from "../../endpoints"; -import { defaultInstance } from "../../apiService"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("CustomerService - getCustomerAddress", () => { - const mockedGet = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - get: mockedGet, - } as any; - }); - - it("should return address object", async () => { - mockedGet.mockResolvedValueOnce({ - data: { data: { id: "2bbb89dfa4664bc681e80b37eaa80fb7" } }, - }); - const result = await getCustomerAddress("2bbb89dfa4664bc681e80b37eaa80fb7"); - expect(result.id).toEqual("2bbb89dfa4664bc681e80b37eaa80fb7"); - expect(mockedGet).toBeCalledTimes(1); - expect(mockedGet).toBeCalledWith( - getCustomerAddressEndpoint("2bbb89dfa4664bc681e80b37eaa80fb7"), - ); - }); - - it("rejects the promise if the customerId is incorrect", async () => { - mockedGet.mockRejectedValueOnce( - new Error("400 - such addressId does not exist"), - ); - expect(getCustomerAddress("wrong-id")).rejects.toThrow( - "400 - such addressId does not exist", - ); - expect(mockedGet).toBeCalledTimes(1); - expect(mockedGet).toBeCalledWith(getCustomerAddressEndpoint("wrong-id")); - }); -}); diff --git a/packages/api-client-old/src/services/CustomerServiceTests/getCustomerAddresses.spec.ts b/packages/api-client-old/src/services/CustomerServiceTests/getCustomerAddresses.spec.ts deleted file mode 100644 index 9d281b4e2..000000000 --- a/packages/api-client-old/src/services/CustomerServiceTests/getCustomerAddresses.spec.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { getCustomerAddresses } from "../customerService"; -import { defaultInstance } from "../../apiService"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("CustomerService - getCustomerAddresses", () => { - const mockedPost = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - post: mockedPost, - } as any; - }); - - it("should return object of addresses", async () => { - mockedPost.mockResolvedValueOnce({ data: { data: {} } }); - const result = await getCustomerAddresses(); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith(`/store-api/account/list-address`, {}); - expect(result).toMatchObject({}); - }); -}); diff --git a/packages/api-client-old/src/services/CustomerServiceTests/getCustomerOrders.spec.ts b/packages/api-client-old/src/services/CustomerServiceTests/getCustomerOrders.spec.ts deleted file mode 100644 index d37f49e91..000000000 --- a/packages/api-client-old/src/services/CustomerServiceTests/getCustomerOrders.spec.ts +++ /dev/null @@ -1,56 +0,0 @@ -import { getCustomerOrders } from "../customerService"; -import { defaultInstance } from "../../apiService"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("CustomerService - getCustomerOrders", () => { - const mockedPost = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - post: mockedPost, - } as any; - }); - - it("should return empty array if no elements are in the response", async () => { - mockedPost.mockResolvedValueOnce({ - data: { - elements: null, - }, - }); - const result = await getCustomerOrders(); - expect(result).toBeUndefined(); - }); - - it("should return array of orders", async () => { - mockedPost.mockResolvedValueOnce({ - data: { - orders: { - elements: [ - { - orderNumber: "1234", - }, - { - orderNumber: "4321", - }, - ], - }, - }, - }); - const result = await getCustomerOrders(); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith("/store-api/order", {}); - expect(result).toMatchObject({ - elements: [ - { - orderNumber: "1234", - }, - { - orderNumber: "4321", - }, - ], - }); - }); -}); diff --git a/packages/api-client-old/src/services/CustomerServiceTests/isNewsletterSubscriber.spec.ts b/packages/api-client-old/src/services/CustomerServiceTests/isNewsletterSubscriber.spec.ts deleted file mode 100644 index 71ffef6e2..000000000 --- a/packages/api-client-old/src/services/CustomerServiceTests/isNewsletterSubscriber.spec.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { defaultInstance } from "../../apiService"; -import { isNewsletterSubscriber } from "../customerService"; -import { getNewsletterRecipientEndpoint } from "../../endpoints"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("CustomerService - isNewsletterSubscriber", () => { - const mockedPost = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - post: mockedPost, - } as any; - }); - - it("returns no data if successfully updated", async () => { - mockedPost.mockResolvedValueOnce({ - status: "undefined", - apiAlias: "account_newsletter_recipient", - }); - const result = await isNewsletterSubscriber(); - - expect(result).toBeFalsy(); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith(getNewsletterRecipientEndpoint()); - }); -}); diff --git a/packages/api-client-old/src/services/CustomerServiceTests/login.spec.ts b/packages/api-client-old/src/services/CustomerServiceTests/login.spec.ts deleted file mode 100644 index 82f7ff5b2..000000000 --- a/packages/api-client-old/src/services/CustomerServiceTests/login.spec.ts +++ /dev/null @@ -1,83 +0,0 @@ -import { login } from "../customerService"; -import { getCustomerLoginEndpoint } from "../../endpoints"; -import { defaultInstance } from "../../apiService"; -import { faker } from "@faker-js/faker"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -const credentials = { - username: faker.internet.email(), - password: faker.internet.password(8), -}; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("CustomerService - login", () => { - const mockedPost = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - post: mockedPost, - } as any; - }); - it("should invoke a POST request with given parameters", async () => { - mockedPost.mockResolvedValueOnce({ data: {} } as any); - - await login(undefined); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith(getCustomerLoginEndpoint(), { - username: undefined, - password: undefined, - }); - }); - it("should return context token in new format if old does not exist", async () => { - mockedPost.mockResolvedValueOnce({ - data: { contextToken: "RmzTExFStSBW5GhPmQNicSK6bhUQhqXi" }, - }); - - const result = await login({ - username: credentials.username, - password: credentials.password, - }); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith(getCustomerLoginEndpoint(), { - username: credentials.username, - password: credentials.password, - }); - - expect(result.contextToken).toEqual("RmzTExFStSBW5GhPmQNicSK6bhUQhqXi"); - }); - it("should return context token", async () => { - mockedPost.mockResolvedValueOnce({ - data: { "sw-context-token": "RmzTExFStSBW5GhPmQNicSK6bhUQhqXi" }, - }); - - const result = await login({ - username: credentials.username, - password: credentials.password, - }); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith(getCustomerLoginEndpoint(), { - username: credentials.username, - password: credentials.password, - }); - - expect(result.contextToken).toEqual("RmzTExFStSBW5GhPmQNicSK6bhUQhqXi"); - }); - it("should throws unhandled rejection - 401", async () => { - mockedPost.mockRejectedValue(new Error()); - - expect( - login({ - username: credentials.username, - password: "wrong-password-123456", - }), - ).rejects.toThrow(); - - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith(getCustomerLoginEndpoint(), { - username: credentials.username, - password: "wrong-password-123456", - }); - }); -}); diff --git a/packages/api-client-old/src/services/CustomerServiceTests/logout.spec.ts b/packages/api-client-old/src/services/CustomerServiceTests/logout.spec.ts deleted file mode 100644 index f126abd31..000000000 --- a/packages/api-client-old/src/services/CustomerServiceTests/logout.spec.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { logout } from "../customerService"; -import { getCustomerLogoutEndpoint } from "../../endpoints"; -import { defaultInstance } from "../../apiService"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("CustomerService - logout", () => { - const mockedPost = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - post: mockedPost, - } as any; - }); - - it("should log out the customer", async () => { - mockedPost.mockResolvedValueOnce({ data: null }); - await logout(); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith(getCustomerLogoutEndpoint()); - }); -}); diff --git a/packages/api-client-old/src/services/CustomerServiceTests/register.spec.ts b/packages/api-client-old/src/services/CustomerServiceTests/register.spec.ts deleted file mode 100644 index 3ddd81612..000000000 --- a/packages/api-client-old/src/services/CustomerServiceTests/register.spec.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { faker } from "@faker-js/faker"; -import { register } from "../customerService"; -import { getCustomerRegisterEndpoint } from "../../endpoints"; -import { defaultInstance } from "../../apiService"; -import type { CustomerRegistrationParams } from "@shopware-pwa/types"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -let customerData: CustomerRegistrationParams; - -describe("CustomerService - register", () => { - const mockedPost = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - post: mockedPost, - } as any; - customerData = { - salutationId: faker.string.uuid(), - firstName: faker.person.firstName(), - lastName: faker.person.lastName(), - password: faker.internet.password(8), - email: faker.internet.email(), - billingAddress: { - countryId: faker.string.uuid(), - street: faker.location.street(), - zipcode: faker.location.zipCode(), - city: faker.location.city(), - phoneNumber: faker.phone.number(), - }, - }; - }); - - it("should register the new customer with basic data provided", async () => { - const customerId = faker.string.uuid(); - mockedPost.mockResolvedValueOnce({ data: customerId }); - const result = await register(customerData); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith( - getCustomerRegisterEndpoint(), - customerData, - ); - expect(result).toBe(customerId); - }); - - it("should never register a customer without billing address", async () => { - const customerDataNew: any = { - ...customerData, - billingAddress: undefined, - }; - - mockedPost.mockRejectedValueOnce(new Error("400")); - - expect(register(customerDataNew)).rejects.toThrowError("400"); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith( - getCustomerRegisterEndpoint(), - customerDataNew, - ); - }); -}); diff --git a/packages/api-client-old/src/services/CustomerServiceTests/resetPassword.spec.ts b/packages/api-client-old/src/services/CustomerServiceTests/resetPassword.spec.ts deleted file mode 100644 index 7d0d20b45..000000000 --- a/packages/api-client-old/src/services/CustomerServiceTests/resetPassword.spec.ts +++ /dev/null @@ -1,86 +0,0 @@ -import { getCustomerResetPasswordEndpoint } from "../../endpoints"; -import { defaultInstance } from "../../apiService"; -import { faker } from "@faker-js/faker"; -import { resetPassword } from "../customerService"; -import { defaultConfig } from "../../settings"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -const DEFAULT_ENDPOINT = "https://shopware-2.vuestorefront.io"; -const email = faker.internet.email("John", "Doe"); -const credentials = { - email: email, - storefrontUrl: defaultConfig.endpoint ?? DEFAULT_ENDPOINT, -}; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("CustomerService - resetPassword", () => { - const mockedPost = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - post: mockedPost, - } as any; - }); - - it("rejects the promise if the email do not mach any in Sales Channel", async () => { - mockedPost.mockRejectedValueOnce(new Error("400 - invalid email address")); - expect( - resetPassword({ - email: credentials.email, - storefrontUrl: credentials.storefrontUrl, - }), - ).rejects.toThrow("400 - invalid email"); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith(getCustomerResetPasswordEndpoint(), { - email: credentials.email, - storefrontUrl: credentials.storefrontUrl, - }); - }); - - it("returns no data if successfully updated", async () => { - mockedPost.mockResolvedValueOnce(null); - - const resultWithFullParams = await resetPassword({ - email: credentials.email, - storefrontUrl: credentials.storefrontUrl, - }); - expect(resultWithFullParams).toBeFalsy(); - - const resultWithEmptyUrl = await resetPassword({ - email: credentials.email, - storefrontUrl: "", - }); - expect(resultWithEmptyUrl).toBeFalsy(); - - const resultWithoutUrl = await resetPassword({ - email: credentials.email, - }); - expect(resultWithoutUrl).toBeFalsy(); - - expect(mockedPost).toBeCalledTimes(3); - expect(mockedPost).toBeCalledWith(getCustomerResetPasswordEndpoint(), { - email: credentials.email, - storefrontUrl: credentials.storefrontUrl, - }); - }); - - it("should set storefrontUrl from config if not provided with params ", async () => { - await resetPassword({ - email: credentials.email, - }); - expect(mockedPost).toBeCalledWith("/store-api/account/recovery-password", { - email: credentials.email, - storefrontUrl: credentials.storefrontUrl, - }); - }); - - it("should invokde post method with null if params are not provided", async () => { - await resetPassword(null as any); - expect(mockedPost).toBeCalledWith( - "/store-api/account/recovery-password", - null, - ); - }); -}); diff --git a/packages/api-client-old/src/services/CustomerServiceTests/setDefaultCustomerBillingAddress.spec.ts b/packages/api-client-old/src/services/CustomerServiceTests/setDefaultCustomerBillingAddress.spec.ts deleted file mode 100644 index f9604934b..000000000 --- a/packages/api-client-old/src/services/CustomerServiceTests/setDefaultCustomerBillingAddress.spec.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { defaultInstance } from "../../apiService"; -import { setDefaultCustomerBillingAddress } from "../customerService"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("CustomerService - updateDefaultCustomerBillingAddress", () => { - const mockedPatch = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - patch: mockedPatch, - } as any; - }); - - it("rejects the promise if provided addressId does not exist", async () => { - mockedPatch.mockRejectedValueOnce( - new Error("400 - address does not exist"), - ); - expect(setDefaultCustomerBillingAddress("1234")).rejects.toThrow( - "400 - address does not exist", - ); - expect(mockedPatch).toBeCalledTimes(1); - expect(mockedPatch).toBeCalledWith( - "/store-api/account/address/default-billing/1234", - ); - }); - - it("returns no data if successfully set", async () => { - mockedPatch.mockResolvedValueOnce({ data: "12345" }); - const result = await setDefaultCustomerBillingAddress("12345"); - expect(result).toBe("12345"); - expect(mockedPatch).toBeCalledTimes(1); - expect(mockedPatch).toBeCalledWith( - "/store-api/account/address/default-billing/12345", - ); - }); -}); diff --git a/packages/api-client-old/src/services/CustomerServiceTests/setDefaultCustomerPaymentMethod.spec.ts b/packages/api-client-old/src/services/CustomerServiceTests/setDefaultCustomerPaymentMethod.spec.ts deleted file mode 100644 index a04faaaba..000000000 --- a/packages/api-client-old/src/services/CustomerServiceTests/setDefaultCustomerPaymentMethod.spec.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { defaultInstance } from "../../apiService"; -import { setDefaultCustomerPaymentMethod } from "../customerService"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("CustomerService - setDefaultCustomerPaymentMethod", () => { - const mockedPost = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - post: mockedPost, - } as any; - }); - - it("rejects the promise if provided payment method ID does not exist", async () => { - mockedPost.mockRejectedValueOnce( - new Error("400 - payment method does not exist"), - ); - expect(setDefaultCustomerPaymentMethod("1234")).rejects.toThrow( - "400 - payment method does not exist", - ); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith( - "/store-api/account/change-payment-method/1234", - ); - }); - - it("returns some data if successfully set", async () => { - mockedPost.mockResolvedValueOnce({ data: {} }); - const result = await setDefaultCustomerPaymentMethod("12345"); - expect(result).toStrictEqual({}); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith( - "/store-api/account/change-payment-method/12345", - ); - }); -}); diff --git a/packages/api-client-old/src/services/CustomerServiceTests/setDefaultCustomerShippingAddress.spec.ts b/packages/api-client-old/src/services/CustomerServiceTests/setDefaultCustomerShippingAddress.spec.ts deleted file mode 100644 index 716a66e59..000000000 --- a/packages/api-client-old/src/services/CustomerServiceTests/setDefaultCustomerShippingAddress.spec.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { defaultInstance } from "../../apiService"; -import { setDefaultCustomerShippingAddress } from "../customerService"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("CustomerService - setDefaultCustomerShippingAddress", () => { - const mockedPatch = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - patch: mockedPatch, - } as any; - }); - - it("rejects the promise if provided addressId does not exist", async () => { - mockedPatch.mockRejectedValueOnce( - new Error("400 - address does not exist"), - ); - expect(setDefaultCustomerShippingAddress("1234")).rejects.toThrow( - "400 - address does not exist", - ); - expect(mockedPatch).toBeCalledTimes(1); - expect(mockedPatch).toBeCalledWith( - "/store-api/account/address/default-shipping/1234", - ); - }); - - it("returns no data if successfully set", async () => { - mockedPatch.mockResolvedValueOnce({ data: "12345" }); - const result = await setDefaultCustomerShippingAddress("12345"); - expect(result).toBe("12345"); - expect(mockedPatch).toBeCalledTimes(1); - expect(mockedPatch).toBeCalledWith( - "/store-api/account/address/default-shipping/12345", - ); - }); -}); diff --git a/packages/api-client-old/src/services/CustomerServiceTests/updateCustomerAddress.spec.ts b/packages/api-client-old/src/services/CustomerServiceTests/updateCustomerAddress.spec.ts deleted file mode 100644 index 4a5d43f82..000000000 --- a/packages/api-client-old/src/services/CustomerServiceTests/updateCustomerAddress.spec.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { faker } from "@faker-js/faker"; -import { updateCustomerAddress } from "../customerService"; -import { defaultInstance } from "../../apiService"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("CustomerService - updateCustomerAddress", () => { - const newAddressData = { - id: "some-address-id", - countryId: faker.string.uuid(), - salutationId: faker.string.uuid(), - firstName: faker.person.firstName(), - lastName: faker.person.lastName(), - zipcode: faker.location.zipCode(), - city: faker.location.city(), - street: faker.location.street(), - }; - const mockedPatch = vi.fn(); - - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - patch: mockedPatch, - } as any; - }); - - it("should return created address id", async () => { - mockedPatch.mockResolvedValueOnce({ - data: "2bbb89dfa4664bc581e80b37eaa80fb7", - }); - const result = await updateCustomerAddress(newAddressData); - expect(result).toEqual("2bbb89dfa4664bc581e80b37eaa80fb7"); - expect(mockedPatch).toBeCalledTimes(1); - expect(mockedPatch).toBeCalledWith( - "/store-api/account/address/some-address-id", - newAddressData, - ); - }); -}); diff --git a/packages/api-client-old/src/services/CustomerServiceTests/updateEmail.spec.ts b/packages/api-client-old/src/services/CustomerServiceTests/updateEmail.spec.ts deleted file mode 100644 index 5715fd040..000000000 --- a/packages/api-client-old/src/services/CustomerServiceTests/updateEmail.spec.ts +++ /dev/null @@ -1,58 +0,0 @@ -import { getCustomerUpdateEmailEndpoint } from "../../endpoints"; -import { defaultInstance } from "../../apiService"; -import { faker } from "@faker-js/faker"; -import { updateEmail } from "../customerService"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -const credentials = { - email: faker.internet.email(), - password: faker.internet.password(8), -}; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("CustomerService - updateEmail", () => { - const mockedPost = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - post: mockedPost, - } as any; - }); - - it("rejects the promise if the email confirmation is wrong", async () => { - mockedPost.mockRejectedValueOnce( - new Error("400 - email confirmation is wrong"), - ); - const differentEmail = faker.internet.email(); - expect( - updateEmail({ - email: credentials.email, - emailConfirmation: differentEmail, - password: credentials.password, - }), - ).rejects.toThrow("400 - email confirmation is wrong"); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith(getCustomerUpdateEmailEndpoint(), { - email: credentials.email, - emailConfirmation: differentEmail, - password: credentials.password, - }); - }); - - it("returns no data if successfully updated", async () => { - mockedPost.mockResolvedValueOnce(null); - await updateEmail({ - email: credentials.email, - emailConfirmation: credentials.email, - password: credentials.password, - }); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith(getCustomerUpdateEmailEndpoint(), { - email: credentials.email, - emailConfirmation: credentials.email, - password: credentials.password, - }); - }); -}); diff --git a/packages/api-client-old/src/services/CustomerServiceTests/updatePassword.spec.ts b/packages/api-client-old/src/services/CustomerServiceTests/updatePassword.spec.ts deleted file mode 100644 index f67c56bef..000000000 --- a/packages/api-client-old/src/services/CustomerServiceTests/updatePassword.spec.ts +++ /dev/null @@ -1,77 +0,0 @@ -import { getCustomerUpdatePasswordEndpoint } from "../../endpoints"; -import { defaultInstance } from "../../apiService"; -import { faker } from "@faker-js/faker"; -import { updatePassword } from "../customerService"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -const newPassword = faker.internet.password(8); -const credentials = { - password: faker.internet.password(8), - newPassword: newPassword, - newPasswordConfirm: newPassword, -}; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("CustomerService - updatePassword", () => { - const mockedPost = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - post: mockedPost, - } as any; - }); - - it("rejects the promise if the password is to short", async () => { - mockedPost.mockRejectedValueOnce(new Error("400 - password too short")); - expect( - updatePassword({ - password: credentials.password, - newPassword: "!23", - newPasswordConfirm: "!23", - }), - ).rejects.toThrow("400 - password too short"); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith(getCustomerUpdatePasswordEndpoint(), { - password: credentials.password, - newPassword: "!23", - newPasswordConfirm: "!23", - }); - }); - - it("rejects the promise if the passwordConfirmation does not match", async () => { - mockedPost.mockRejectedValueOnce( - new Error("400 - new password confirmation does not match"), - ); - expect( - updatePassword({ - password: credentials.password, - newPassword: credentials.newPassword, - newPasswordConfirm: `${credentials.newPassword}_123`, - }), - ).rejects.toThrow("400 - new password confirmation does not match"); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith(getCustomerUpdatePasswordEndpoint(), { - password: credentials.password, - newPassword: credentials.newPassword, - newPasswordConfirm: `${credentials.newPassword}_123`, - }); - }); - - it("returns no data if successfully updated", async () => { - mockedPost.mockResolvedValueOnce(null); - const result = await updatePassword({ - password: credentials.password, - newPassword: credentials.newPassword, - newPasswordConfirm: credentials.newPassword, - }); - expect(result).toBeFalsy(); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith(getCustomerUpdatePasswordEndpoint(), { - password: credentials.password, - newPassword: credentials.newPassword, - newPasswordConfirm: credentials.newPassword, - }); - }); -}); diff --git a/packages/api-client-old/src/services/CustomerServiceTests/updateProfile.spec.ts b/packages/api-client-old/src/services/CustomerServiceTests/updateProfile.spec.ts deleted file mode 100644 index eec036e5a..000000000 --- a/packages/api-client-old/src/services/CustomerServiceTests/updateProfile.spec.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { faker } from "@faker-js/faker"; -import { defaultInstance } from "../../apiService"; -import { updateProfile } from "../customerService"; -import { getCustomerDetailsUpdateEndpoint } from "../../endpoints"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -const customerData = { - salutationId: faker.string.uuid(), - firstName: faker.person.firstName(), - lastName: faker.person.lastName(), - title: "d", -}; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("CustomerService - updateProfile", () => { - const mockedPost = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - post: mockedPost, - } as any; - }); - - it("returns no data if successfully updated", async () => { - mockedPost.mockResolvedValueOnce(null); - const result = await updateProfile(customerData); - - expect(result).toBeFalsy(); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith( - getCustomerDetailsUpdateEndpoint(), - customerData, - ); - }); -}); diff --git a/packages/api-client-old/src/services/DocumentServiceTests/getDocumentDownload.spec.ts b/packages/api-client-old/src/services/DocumentServiceTests/getDocumentDownload.spec.ts deleted file mode 100644 index 0a945f536..000000000 --- a/packages/api-client-old/src/services/DocumentServiceTests/getDocumentDownload.spec.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { getDocumentDownload } from "../documentService"; -import { defaultInstance } from "../../apiService"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("DocumentService - getDocumentDownload", () => { - const mockedGet = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - get: mockedGet, - } as any; - }); - - it("should return document file", async () => { - mockedGet.mockResolvedValueOnce({ data: { data: {} } }); - const result = await getDocumentDownload({ - documentId: "123", - deepLinkCode: "456", - }); - expect(mockedGet).toBeCalledTimes(1); - expect(mockedGet).toBeCalledWith(`/store-api/document/download/123/456`, { - responseType: "blob", - }); - expect(result).toMatchObject({}); - }); -}); diff --git a/packages/api-client-old/src/services/FormServiceTests/newsletterSubscribe.spec.ts b/packages/api-client-old/src/services/FormServiceTests/newsletterSubscribe.spec.ts deleted file mode 100644 index b3b5e8d7b..000000000 --- a/packages/api-client-old/src/services/FormServiceTests/newsletterSubscribe.spec.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { newsletterSubscribe } from "../formsService"; -import { defaultInstance } from "../../apiService"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("FormService - newsletterSubscribe", () => { - const mockedPost = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - post: mockedPost, - } as any; - }); - - it("should invoke correct API endpoint with given parameters", async () => { - await newsletterSubscribe({ - email: "john@doe.com", - option: "subscribe", - storefrontUrl: "https://shopware6-demo.vuestorefront.io", - }); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith("/store-api/newsletter/subscribe", { - email: "john@doe.com", - option: "subscribe", - storefrontUrl: "https://shopware6-demo.vuestorefront.io", - }); - }); - - it("should throw an error when data is incorrect", async () => { - mockedPost.mockRejectedValueOnce(new Error("400")); - expect(newsletterSubscribe({} as any)).rejects.toThrowError("400"); - expect(mockedPost).toBeCalledWith("/store-api/newsletter/subscribe", { - option: "subscribe", - }); - }); -}); diff --git a/packages/api-client-old/src/services/FormServiceTests/newsletterUnubscribe.spec.ts b/packages/api-client-old/src/services/FormServiceTests/newsletterUnubscribe.spec.ts deleted file mode 100644 index 1d2df06c2..000000000 --- a/packages/api-client-old/src/services/FormServiceTests/newsletterUnubscribe.spec.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { newsletterUnsubscribe } from "../formsService"; -import { defaultInstance } from "../../apiService"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("FormService - newsletterUnsubscribe", () => { - const mockedPost = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - post: mockedPost, - } as any; - }); - it("should invoke correct API endpoint with given parameters", async () => { - await newsletterUnsubscribe({ email: "john@doe.com" }); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith("/store-api/newsletter/unsubscribe", { - email: "john@doe.com", - }); - }); - - it("should throw an error when data is incorrect", async () => { - mockedPost.mockRejectedValueOnce(new Error("500")); - expect(newsletterUnsubscribe({ email: "" })).rejects.toThrowError("500"); - expect(mockedPost).toBeCalledWith("/store-api/newsletter/unsubscribe", { - email: "", - }); - }); -}); diff --git a/packages/api-client-old/src/services/FormServiceTests/sendContactForm.spec.ts b/packages/api-client-old/src/services/FormServiceTests/sendContactForm.spec.ts deleted file mode 100644 index 1e4b77788..000000000 --- a/packages/api-client-old/src/services/FormServiceTests/sendContactForm.spec.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { sendContactForm } from "../formsService"; -import { defaultInstance } from "../../apiService"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("FormService - sendContactForm", () => { - const mockedPost = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - post: mockedPost, - } as any; - }); - it("should invoke correct API endpoint with given parameters", async () => { - await sendContactForm({ - salutationId: "2a69a6c523034b108a3bc292ef4c8891", - firstName: "John", - lastName: "Doe", - email: "John@Doe.com", - phone: "123456789", - subject: "Best form test", - comment: "Please do not reply for this email.", - }); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith("/store-api/contact-form", { - salutationId: "2a69a6c523034b108a3bc292ef4c8891", - firstName: "John", - lastName: "Doe", - email: "John@Doe.com", - phone: "123456789", - subject: "Best form test", - comment: "Please do not reply for this email.", - }); - }); - - it("should throw an error when data is incorrect", async () => { - mockedPost.mockRejectedValueOnce(new Error("400")); - expect(sendContactForm({} as any)).rejects.toThrowError("400"); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith("/store-api/contact-form", {}); - }); -}); diff --git a/packages/api-client-old/src/services/NavigationServiceTests/getStoreNavigation.spec.ts b/packages/api-client-old/src/services/NavigationServiceTests/getStoreNavigation.spec.ts deleted file mode 100644 index 374497e6f..000000000 --- a/packages/api-client-old/src/services/NavigationServiceTests/getStoreNavigation.spec.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { getStoreNavigation } from "../navigationService"; -import { defaultInstance } from "../../apiService"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("NavigationService - getStoreNavigation", () => { - const mockedPost = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - post: mockedPost, - } as any; - }); - it("should return navigation elements for given navigation ids", async () => { - mockedPost.mockResolvedValueOnce({ - data: [ - { - id: "footer-navigation", - }, - ], - }); - const result = await getStoreNavigation({ - requestActiveId: "footer-navigation", - requestRootId: "footer-navigation", - depth: 5, - buildTree: false, - }); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith( - "/store-api/navigation/footer-navigation/footer-navigation", - { buildTree: false, depth: 5 }, - ); - expect(result).toStrictEqual([{ id: "footer-navigation" }]); - }); -}); diff --git a/packages/api-client-old/src/services/NewsletterServiceTests/newsletterConfirmation.spec.ts b/packages/api-client-old/src/services/NewsletterServiceTests/newsletterConfirmation.spec.ts deleted file mode 100644 index 829d7273c..000000000 --- a/packages/api-client-old/src/services/NewsletterServiceTests/newsletterConfirmation.spec.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { newsletterConfirmation } from "../newsletterService"; -import { defaultInstance } from "../../apiService"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("NewsletterService - newsletterConfirmation", () => { - const mockedPost = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - post: mockedPost, - } as any; - }); - - it("should confirm newsletter", async () => { - mockedPost.mockResolvedValueOnce({ data: { data: {} } }); - const result = await newsletterConfirmation({ - hash: "232323", - em: "44242456", - }); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith(`/store-api/newsletter/confirm`, { - hash: "232323", - em: "44242456", - }); - expect(result).toMatchObject({}); - }); -}); diff --git a/packages/api-client-old/src/services/OrderServiceTests/getOrderDownloads.spec.ts b/packages/api-client-old/src/services/OrderServiceTests/getOrderDownloads.spec.ts deleted file mode 100644 index ea6b0f2c9..000000000 --- a/packages/api-client-old/src/services/OrderServiceTests/getOrderDownloads.spec.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { getOrderDownloads } from "../orderService"; -import { defaultInstance } from "../../apiService"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("OrderService - getOrderDownloads", () => { - const mockedGet = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - get: mockedGet, - } as any; - }); - - it("should return order file", async () => { - mockedGet.mockResolvedValueOnce({ data: { data: {} } }); - const result = await getOrderDownloads({ - orderId: "123", - downloadId: "456", - }); - expect(mockedGet).toBeCalledTimes(1); - expect(mockedGet).toBeCalledWith(`/store-api/order/download/123/456`, { - responseType: "blob", - }); - expect(result).toMatchObject({}); - }); -}); diff --git a/packages/api-client-old/src/services/PageServiceTests/getCmsPage.spec.ts b/packages/api-client-old/src/services/PageServiceTests/getCmsPage.spec.ts deleted file mode 100644 index 353fcf188..000000000 --- a/packages/api-client-old/src/services/PageServiceTests/getCmsPage.spec.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { getCmsPage } from "../pageService"; -import { defaultInstance } from "../../apiService"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("PageService - getCmsPage", () => { - const mockedPost = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - post: mockedPost, - } as any; - }); - it("should return cmsPage for given path", async () => { - mockedPost.mockResolvedValueOnce({ - data: { cmsPage: { id: "b218f861361042f3a58a2a9d1b3575b5" } }, - }); - const result = await getCmsPage("Sports/Grocery-Garden"); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith("/store-api/pwa/page", { - path: "Sports/Grocery-Garden", - }); - expect(result).toHaveProperty("cmsPage"); - expect(result.cmsPage.id).toEqual("b218f861361042f3a58a2a9d1b3575b5"); - }); - - it("should invoke search with criteria", async () => { - mockedPost.mockResolvedValueOnce({ - data: { cmsPage: { id: "b218f861361042f3a58a2a9d1b3575b5" } }, - }); - await getCmsPage("Sports/Grocery-Garden", { - p: 2, - limit: 3, - }); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith("/store-api/pwa/page", { - path: "Sports/Grocery-Garden", - p: 2, - limit: 3, - }); - }); -}); diff --git a/packages/api-client-old/src/services/PageServiceTests/getLandingPage.spec.ts b/packages/api-client-old/src/services/PageServiceTests/getLandingPage.spec.ts deleted file mode 100644 index a5d5335df..000000000 --- a/packages/api-client-old/src/services/PageServiceTests/getLandingPage.spec.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { getLandingPage } from "../pageService"; -import { defaultInstance } from "../../apiService"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("PageService - getLandingPage", () => { - const mockedPost = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - post: mockedPost, - } as any; - }); - it("should return getLandingPage for given id", async () => { - mockedPost.mockResolvedValueOnce({ - data: { id: "b218f861361042f3a58a2a9d1b3575b5" }, - }); - const result = await getLandingPage("b218f861361042f3a58a2a9d1b3575b5"); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith( - "/store-api/landing-page/b218f861361042f3a58a2a9d1b3575b5", - undefined, - ); - expect(result).toHaveProperty("id"); - }); - it("should return undefined in case of no data fetched from API", async () => { - mockedPost.mockResolvedValueOnce(null as any); - const result = await getLandingPage("b218f861361042f3a58a2a9d1b3575b5"); - expect(result).toBeUndefined(); - }); -}); diff --git a/packages/api-client-old/src/services/PageServiceTests/getSeoUrl.spec.ts b/packages/api-client-old/src/services/PageServiceTests/getSeoUrl.spec.ts deleted file mode 100644 index 2ccedb8b8..000000000 --- a/packages/api-client-old/src/services/PageServiceTests/getSeoUrl.spec.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { getSeoUrl } from "../pageService"; -import { defaultInstance } from "../../apiService"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("PageService - getSeoUrl", () => { - const mockedPost = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - post: mockedPost, - } as any; - }); - it("should return seo url entities for given criteria", async () => { - mockedPost.mockResolvedValueOnce({ - data: { elements: [{ id: "b218f861361042f3a58a2a9d1b3575b5" }] }, - }); - const result = await getSeoUrl({ - limit: 3, - }); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith("/store-api/seo-url", { - limit: 3, - }); - expect(result).toHaveProperty("elements"); - }); -}); diff --git a/packages/api-client-old/src/services/PageServiceTests/getSeoUrls.spec.ts b/packages/api-client-old/src/services/PageServiceTests/getSeoUrls.spec.ts deleted file mode 100644 index 903ed1b45..000000000 --- a/packages/api-client-old/src/services/PageServiceTests/getSeoUrls.spec.ts +++ /dev/null @@ -1,58 +0,0 @@ -import { getSeoUrls } from "../pageService"; -import { defaultInstance } from "../../apiService"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("PageService - getSeoUrls", () => { - const mockedPost = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - post: mockedPost, - } as any; - }); - it("should return seoUrls for given path", async () => { - mockedPost.mockResolvedValueOnce({ - data: [{ seoPathInfo: "/Sports/Grocery-Garden" }], - }); - const result = await getSeoUrls("3223232321112257"); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith("/store-api/seo-url", { - filter: [ - { - field: "foreignKey", - type: "equals", - value: "3223232321112257", - }, - ], - includes: { - seo_url: ["seoPathInfo"], - }, - }); - expect(result[0].seoPathInfo).toEqual("/Sports/Grocery-Garden"); - }); - it("should make a request with specific languageId if any provided", async () => { - mockedPost.mockResolvedValueOnce({ - data: [{ seoPathInfo: "/Sports/Grocery-Garden" }], - }); - await getSeoUrls("3223232321112257", "someLanguageId"); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedApiInstance.defaults.headers.common["sw-language-id"]).toBe( - "someLanguageId", - ); - expect(mockedPost).toBeCalledWith("/store-api/seo-url", { - filter: [ - { - field: "foreignKey", - type: "equals", - value: "3223232321112257", - }, - ], - includes: { - seo_url: ["seoPathInfo"], - }, - }); - }); -}); diff --git a/packages/api-client-old/src/services/PageServiceTests/getSwCmsPage.spec.ts b/packages/api-client-old/src/services/PageServiceTests/getSwCmsPage.spec.ts deleted file mode 100644 index 3665c27ae..000000000 --- a/packages/api-client-old/src/services/PageServiceTests/getSwCmsPage.spec.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { getSwCmsPage } from "../pageService"; -import { defaultInstance } from "../../apiService"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("PageService - getSwCmsPage", () => { - const mockedPost = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - post: mockedPost, - } as any; - }); - - it("should return getLandingPage for given id", async () => { - mockedPost.mockResolvedValueOnce({}); - const result = await getSwCmsPage("idtest8888"); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith("/store-api/cms/idtest8888"); - }); -}); diff --git a/packages/api-client-old/src/services/PluginServiceTests/invokePost.spec.ts b/packages/api-client-old/src/services/PluginServiceTests/invokePost.spec.ts deleted file mode 100644 index 8aefc68c5..000000000 --- a/packages/api-client-old/src/services/PluginServiceTests/invokePost.spec.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { defaultInstance } from "../../apiService"; -import { invokePost, invokeGet } from "../pluginService"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("PluginService - invokePost", () => { - const mockedPost = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - post: mockedPost, - } as any; - }); - it("should call contextInstance.invoke.post method with provided payload", async () => { - mockedPost.mockResolvedValueOnce({ data: { success: true } }); - - const result = await invokePost({ - address: "/some/post/endpoint", - payload: { - some: "payload", - }, - }); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith("/some/post/endpoint", { - some: "payload", - }); - expect(result.data.success).toEqual(true); - }); -}); -describe("PluginService - invokeGet", () => { - const mockedGet = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - get: mockedGet, - } as any; - }); - it("should call contextInstance.invoke.get method with provided resource", async () => { - mockedGet.mockResolvedValueOnce({ data: { success: true } }); - - const result = await invokeGet({ - address: "/some/get/endpoint", - }); - expect(mockedGet).toBeCalledTimes(1); - expect(mockedGet).toBeCalledWith("/some/get/endpoint"); - expect(result.data.success).toEqual(true); - }); -}); diff --git a/packages/api-client-old/src/services/ProductServiceTests/addProductReview.spec.ts b/packages/api-client-old/src/services/ProductServiceTests/addProductReview.spec.ts deleted file mode 100644 index e28af7439..000000000 --- a/packages/api-client-old/src/services/ProductServiceTests/addProductReview.spec.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { addProductReview } from "../productService"; -import { defaultInstance } from "../../apiService"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("ProductService - addProductReview", () => { - const mockedPost = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - post: mockedPost, - } as any; - }); - it("should invoke a specific POST call in order to add a review", async () => { - const productId = "044a190a54ab4f06803909c3ee8063ef"; - const reviewData = { - title: "Some title", - content: - "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", - points: 5, - }; - - const result = await addProductReview( - productId, - reviewData, - mockedApiInstance, - ); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith( - "/store-api/product/044a190a54ab4f06803909c3ee8063ef/review", - reviewData, - ); - expect(result).toBeUndefined(); - }); - it("should invoke a specific POST call using default API instance", async () => { - const productId = "044a190a54ab4f06803909c3ee8063ef"; - const reviewData = { - title: "Some title", - content: - "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", - points: 5, - }; - - await addProductReview(productId, reviewData); - }); -}); diff --git a/packages/api-client-old/src/services/ProductServiceTests/getCategoryProducts.spec.ts b/packages/api-client-old/src/services/ProductServiceTests/getCategoryProducts.spec.ts deleted file mode 100644 index c1f070880..000000000 --- a/packages/api-client-old/src/services/ProductServiceTests/getCategoryProducts.spec.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { defaultInstance } from "../../apiService"; -import { getCategoryProducts } from "../productService"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("ProductService - getCategoryProducts", () => { - const mockedPost = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - post: mockedPost, - } as any; - }); - it("should return listing data with no searchCriteria", async () => { - mockedPost.mockResolvedValueOnce({ - data: { elements: [{ id: "044a190a54ab4f06803909c3ee8063ef" }] }, - }); - const categoryId = "044a190a54ab4f06803909c3ee8063ef"; - const result = await getCategoryProducts(categoryId); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith( - "/store-api/product-listing/044a190a54ab4f06803909c3ee8063ef", - undefined, - ); - expect(result).toHaveProperty("elements"); - }); - it("should return listing data with searchCriteria provided", async () => { - mockedPost.mockResolvedValueOnce({ - data: { elements: [{ id: "044a190a54ab4f06803909c3ee8063ef" }] }, - }); - const categoryId = "044a190a54ab4f06803909c3ee8063ef"; - const result = await getCategoryProducts(categoryId, { - limit: 10, - }); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith( - "/store-api/product-listing/044a190a54ab4f06803909c3ee8063ef", - { limit: 10 }, - ); - expect(result).toHaveProperty("elements"); - }); -}); diff --git a/packages/api-client-old/src/services/ProductServiceTests/getProduct.spec.ts b/packages/api-client-old/src/services/ProductServiceTests/getProduct.spec.ts deleted file mode 100644 index 7e46e7918..000000000 --- a/packages/api-client-old/src/services/ProductServiceTests/getProduct.spec.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { getProduct } from "../productService"; -import { defaultInstance } from "../../apiService"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("ProductService - getProduct", () => { - const mockedPost = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - post: mockedPost, - } as any; - }); - it("should return chosen product", async () => { - mockedPost.mockResolvedValueOnce({ - data: { product: { id: "044a190a54ab4f06803909c3ee8063ef" } }, - }); - const productId = "044a190a54ab4f06803909c3ee8063ef"; - const result = await getProduct(productId); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith( - "/store-api/product/044a190a54ab4f06803909c3ee8063ef", - null, - ); - expect(result.product?.id).toEqual(productId); - }); -}); diff --git a/packages/api-client-old/src/services/ProductServiceTests/getProductCrossSelling.spec.ts b/packages/api-client-old/src/services/ProductServiceTests/getProductCrossSelling.spec.ts deleted file mode 100644 index 4b15fe7cd..000000000 --- a/packages/api-client-old/src/services/ProductServiceTests/getProductCrossSelling.spec.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { getProductCrossSelling } from "../productService"; -import { defaultInstance } from "../../apiService"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("ProductService - getProductCrossSelling", () => { - const mockedPost = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - post: mockedPost, - } as any; - }); - it("should return chosen product", async () => { - mockedPost.mockResolvedValueOnce({ - data: { crossSelling: { name: "my crossselling" } }, - }); - const productId = "044a190a54ab4f06803909c3ee8063ef"; - const result = await getProductCrossSelling(productId); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith( - "/store-api/product/044a190a54ab4f06803909c3ee8063ef/cross-selling", - null, - ); - expect(result.crossSelling.name).toEqual("my crossselling"); - }); -}); diff --git a/packages/api-client-old/src/services/ProductServiceTests/getProductReviews.spec.ts b/packages/api-client-old/src/services/ProductServiceTests/getProductReviews.spec.ts deleted file mode 100644 index 531b65904..000000000 --- a/packages/api-client-old/src/services/ProductServiceTests/getProductReviews.spec.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { getProductReviews } from "../productService"; -import { defaultInstance } from "../../apiService"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("ProductService - getProductReviews", () => { - const mockedPost = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - post: mockedPost, - } as any; - }); - it("should return reviews of chosen product", async () => { - mockedPost.mockResolvedValueOnce({ - data: { elements: [{ productId: "044a190a54ab4f06803909c3ee8063ef" }] }, - }); - const productId = "044a190a54ab4f06803909c3ee8063ef"; - const result = await getProductReviews(productId); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith( - "/store-api/product/044a190a54ab4f06803909c3ee8063ef/reviews", - {}, - ); - expect(result).toHaveProperty("elements"); - }); -}); diff --git a/packages/api-client-old/src/services/ProductServiceTests/getProductVariantForOptions.spec.ts b/packages/api-client-old/src/services/ProductServiceTests/getProductVariantForOptions.spec.ts deleted file mode 100644 index cc248d1e9..000000000 --- a/packages/api-client-old/src/services/ProductServiceTests/getProductVariantForOptions.spec.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { getProductVariantForOptions } from "../productService"; -import { defaultInstance } from "../../apiService"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -const consoleWarnSpy = vi.spyOn(console, "warn"); - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; -describe("ProductService - getProductVariantForOptions", () => { - const mockedPost = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - post: mockedPost, - } as any; - consoleWarnSpy.mockImplementation(() => {}); - }); - - it("should make a request with provided arguments", async () => { - await getProductVariantForOptions({ - productId: "product-id", - optionIds: ["option-id-1", "option-id-2"], - switchedGroup: "switched-group-id", - }); - - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith( - "/store-api/product/product-id/find-variant", - { - options: ["option-id-1", "option-id-2"], - switchedGroup: "switched-group-id", - }, - ); - }); - it("should return data with specific format", async () => { - mockedPost.mockResolvedValueOnce({ - data: { variantId: "found-variant-id", options: ["currentOption"] }, - }); - const response = await getProductVariantForOptions({ - productId: "some-id", - } as any); - - expect(response).toStrictEqual({ - variantId: "found-variant-id", - options: ["currentOption"], - }); - }); -}); diff --git a/packages/api-client-old/src/services/ProductServiceTests/getProducts.spec.ts b/packages/api-client-old/src/services/ProductServiceTests/getProducts.spec.ts deleted file mode 100644 index 082a3b60b..000000000 --- a/packages/api-client-old/src/services/ProductServiceTests/getProducts.spec.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { getProducts } from "../productService"; -import { defaultInstance } from "../../apiService"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -const consoleWarnSpy = vi.spyOn(console, "warn"); - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; -describe("ProductService - getProducts", () => { - const mockedPost = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - post: mockedPost, - } as any; - consoleWarnSpy.mockImplementation(() => {}); - }); - it("should return array of products (default amount of 10)", async () => { - mockedPost.mockResolvedValueOnce({ - data: { total: 3, elements: [1, 2, 3] }, - }); - - const result = await getProducts(); - expect(result.total).toEqual(3); - expect(result?.elements).toHaveLength(3); - expect(mockedPost).toBeCalledTimes(1); - }); - it("should invoke api with limit", async () => { - mockedPost.mockResolvedValueOnce({ - data: { total: 3, data: [1, 2, 3] }, - }); - await getProducts({ p: 1, limit: 5 }); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith("/store-api/product", { - limit: 5, - p: 1, - }); - }); - it("should invoke api with limit and sort", async () => { - mockedPost.mockResolvedValueOnce({ - data: { total: 3, data: [1, 2, 3] }, - }); - await getProducts({ p: 1, limit: 75, order: "name-asc" }); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith("/store-api/product", { - limit: 75, - p: 1, - order: "name-asc", - }); - }); - // it("should show deprecation info on this method", async () => { - // mockedPost.mockResolvedValueOnce({ - // data: { total: 3, data: [1, 2, 3] }, - // }); - // await getProducts(); - // expect(consoleWarnSpy).toBeCalledWith( - // '[DEPRECATED][@shopware-pwa/shopware-6-client][getProducts] This method has been deprecated. Use "getCategoryProductsListing" instead.' - // ); - // }); -}); diff --git a/packages/api-client-old/src/services/SearchServiceTests/searchProducts.spec.ts b/packages/api-client-old/src/services/SearchServiceTests/searchProducts.spec.ts deleted file mode 100644 index 6735e80ab..000000000 --- a/packages/api-client-old/src/services/SearchServiceTests/searchProducts.spec.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { searchProducts } from "../searchService"; -import { defaultInstance } from "../../apiService"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("SearchService - searchProducts", () => { - const mockedPost = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - post: mockedPost, - } as any; - }); - it("should return ProductListingResult", async () => { - mockedPost.mockResolvedValueOnce({ - data: { apiAlias: "product_listing" }, - }); - const result = await searchProducts({ - query: "searchTerm", - limit: 10, - p: 1, - }); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith("/store-api/search?search=searchTerm", { - query: "searchTerm", - limit: 10, - p: 1, - }); - expect(result).toHaveProperty("apiAlias"); - }); - - it("should call for empty queery", async () => { - mockedPost.mockResolvedValueOnce({ - data: { apiAlias: "product_listing" }, - }); - const result = await searchProducts(undefined); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith("/store-api/search?search=", undefined); - expect(result).toHaveProperty("apiAlias"); - }); -}); diff --git a/packages/api-client-old/src/services/SearchServiceTests/searchSuggestedProducts.spec.ts b/packages/api-client-old/src/services/SearchServiceTests/searchSuggestedProducts.spec.ts deleted file mode 100644 index 7e8118792..000000000 --- a/packages/api-client-old/src/services/SearchServiceTests/searchSuggestedProducts.spec.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { searchSuggestedProducts } from "../searchService"; -import { defaultInstance } from "../../apiService"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("SearchService - searchSuggestedProducts", () => { - const mockedPost = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - post: mockedPost, - } as any; - }); - it("should return ProductListingResult", async () => { - mockedPost.mockResolvedValueOnce({ - data: { apiAlias: "product_listing" }, - }); - const result = await searchSuggestedProducts({ - query: "searchTerm", - limit: 10, - p: 1, - }); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith( - "/store-api/search-suggest?search=searchTerm", - { - query: "searchTerm", - limit: 10, - p: 1, - }, - ); - expect(result).toHaveProperty("apiAlias"); - }); - - it("should call for empty queery", async () => { - mockedPost.mockResolvedValueOnce({ - data: { apiAlias: "product_listing" }, - }); - const result = await searchSuggestedProducts(undefined); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith( - "/store-api/search-suggest?search=", - undefined, - ); - expect(result).toHaveProperty("apiAlias"); - }); -}); diff --git a/packages/api-client-old/src/services/SitemapServiceTests/getSitemap.spec.ts b/packages/api-client-old/src/services/SitemapServiceTests/getSitemap.spec.ts deleted file mode 100644 index 84aea5e84..000000000 --- a/packages/api-client-old/src/services/SitemapServiceTests/getSitemap.spec.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { getSitemap } from "../sitemapService"; -import { defaultInstance } from "../../apiService"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("SitemapService - getSitemap", () => { - const mockedGet = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - get: mockedGet, - } as any; - }); - - it("should return sitemap links", async () => { - mockedGet.mockResolvedValueOnce({ data: { data: {} } }); - const result = await getSitemap(); - expect(mockedGet).toBeCalledTimes(1); - expect(mockedGet).toBeCalledWith(`/store-api/sitemap`); - expect(result).toMatchObject({}); - }); -}); diff --git a/packages/api-client-old/src/services/WishlistServiceTests/addWishlistProduct.spec.ts b/packages/api-client-old/src/services/WishlistServiceTests/addWishlistProduct.spec.ts deleted file mode 100644 index d481de5b3..000000000 --- a/packages/api-client-old/src/services/WishlistServiceTests/addWishlistProduct.spec.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { addWishlistProduct } from "../wishlistService"; -import { getAddWishlistProductEndpoint } from "../.."; -import { defaultInstance } from "../../apiService"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("WishlistService - addWishlistProduct", () => { - const mockedPost = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - post: mockedPost, - } as any; - }); - it("should invoke a post method for specific endpoint", async () => { - mockedPost.mockResolvedValueOnce({ - data: { apiAlias: "wishlist_products" }, - }); - const result = await addWishlistProduct("some-product-uuid"); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith( - getAddWishlistProductEndpoint("some-product-uuid"), - ); - expect(result).toHaveProperty("apiAlias"); - }); -}); diff --git a/packages/api-client-old/src/services/WishlistServiceTests/getWishlistProducts.spec.ts b/packages/api-client-old/src/services/WishlistServiceTests/getWishlistProducts.spec.ts deleted file mode 100644 index fa46d2441..000000000 --- a/packages/api-client-old/src/services/WishlistServiceTests/getWishlistProducts.spec.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { getWishlistProducts } from "../wishlistService"; -import { getGetWishlistProductsEndpoint } from "../.."; -import { defaultInstance } from "../../apiService"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("WishlistService - getWishlistProducts", () => { - const mockedPost = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - post: mockedPost, - } as any; - }); - it("should invoke a post method for specific endpoint", async () => { - mockedPost.mockResolvedValueOnce({ - data: { apiAlias: "wishlist_products" }, - }); - const result = await getWishlistProducts({ - includes: { - product: ["name"], - }, - }); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith(getGetWishlistProductsEndpoint(), { - includes: { product: ["name"] }, - }); - expect(result).toHaveProperty("apiAlias"); - }); -}); diff --git a/packages/api-client-old/src/services/WishlistServiceTests/mergeWishlistProducts.spec.ts b/packages/api-client-old/src/services/WishlistServiceTests/mergeWishlistProducts.spec.ts deleted file mode 100644 index f1f63e9ca..000000000 --- a/packages/api-client-old/src/services/WishlistServiceTests/mergeWishlistProducts.spec.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { mergeWishlistProducts } from "../wishlistService"; -import { getMergeWishlistProductsEndpoint } from "../.."; -import { defaultInstance } from "../../apiService"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("WishlistService - mergeWishlistProducts", () => { - const mockedPost = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - post: mockedPost, - } as any; - }); - it("should invoke a post method for specific endpoint", async () => { - mockedPost.mockResolvedValueOnce({ - data: { success: true }, - }); - const result = await mergeWishlistProducts([ - "some-product-uuid-1", - "some-product-uuid-2", - ]); - expect(mockedPost).toBeCalledTimes(1); - expect(mockedPost).toBeCalledWith(getMergeWishlistProductsEndpoint(), { - productIds: ["some-product-uuid-1", "some-product-uuid-2"], - }); - expect(result).toHaveProperty("success"); - }); -}); diff --git a/packages/api-client-old/src/services/WishlistServiceTests/removeWishlistProduct.spec.ts b/packages/api-client-old/src/services/WishlistServiceTests/removeWishlistProduct.spec.ts deleted file mode 100644 index 87effe95f..000000000 --- a/packages/api-client-old/src/services/WishlistServiceTests/removeWishlistProduct.spec.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { removeWishlistProduct } from "../wishlistService"; -import { getRemoveWishlistProductEndpoint } from "../.."; -import { defaultInstance } from "../../apiService"; -import { describe, expect, it, beforeEach, vi } from "vitest"; - -vi.mock("../../../src/apiService"); -const mockedApiInstance = defaultInstance; - -describe("WishlistService - removeWishlistProduct", () => { - const mockedDelete = vi.fn(); - beforeEach(() => { - vi.resetAllMocks(); - mockedApiInstance.invoke = { - delete: mockedDelete, - } as any; - }); - it("should invoke a delete method for specific endpoint", async () => { - mockedDelete.mockResolvedValueOnce({ - data: { success: true }, - }); - const result = await removeWishlistProduct("some-product-uuid"); - expect(mockedDelete).toBeCalledTimes(1); - expect(mockedDelete).toBeCalledWith( - getRemoveWishlistProductEndpoint("some-product-uuid"), - ); - expect(result).toHaveProperty("success"); - }); -}); diff --git a/packages/api-client-old/src/services/cartService.ts b/packages/api-client-old/src/services/cartService.ts deleted file mode 100644 index 2943f73ce..000000000 --- a/packages/api-client-old/src/services/cartService.ts +++ /dev/null @@ -1,196 +0,0 @@ -import { - getCheckoutCartEndpoint, - getCheckoutCartLineItemEndpoint, -} from "../endpoints"; -import { defaultInstance, ShopwareApiInstance } from "../apiService"; -import type { Cart, LineItem } from "@shopware-pwa/types"; - -/** - * When no sw-context-token given then this method return an empty cart with the new sw-context-token. - * - * When sw-context-token given then this method simply returns the current state of the cart. - * - * As the purpose of this method is not clear we recommend to use `getCart` method because its behaviour seems to be the same. - * - * @param {ShopwareApiInstance} contextInstance instance of the api client (by default it's an Axios instance) - * - * @throws ClientApiError - * - * @public - * - * @category Cart - */ -export async function clearCart( - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise<{ - contextToken: string; - apiAlias: "array_struct"; -}> { - const resp = await contextInstance.invoke.post(getCheckoutCartEndpoint()); - const contextToken = resp.data["sw-context-token"]; - return { contextToken, apiAlias: "array_struct" }; -} - -/** - * Gets the current cart for the sw-context-token. - * @throws ClientApiError - * @public - * - * @category Cart - */ -export async function getCart( - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise { - const resp = await contextInstance.invoke.get(getCheckoutCartEndpoint()); - - return resp.data; -} - -/** - * Adds specific quantity of the product to the cart by productId. It creates a new cart line item. - * - * Warning: This method does not change the state of the cart in any way if productId already exists in a cart. For changing the quantity use addQuantityToCartLineItem() or changeCartLineItemQuantity() methods. - * - * @throws ClientApiError - * @public - * - * @param {string} productId id of the cart line item (usually it's a product id) - * @param {number} quantity quantity of the product to be added to the cart - * @param {ShopwareApiInstance} contextInstance instance of the api client (by default it's an Axios instance) - * - * @category Cart - */ -export async function addProductToCart( - productId: string, - quantity?: number, - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise { - const qty = quantity || 1; - const item: Partial = { - quantity: qty, - type: "product", - referencedId: productId, - id: productId, - }; - const resp = await contextInstance.invoke.post( - getCheckoutCartLineItemEndpoint(), - { - items: [item], - }, - ); - - return resp.data; -} - -/** - * Changes the current quantity in specific cart line item to given quantity. - * - * Example: If current quantity is 3 and you pass 2 as quantity parameter, you will get a new cart's state with quantity 2. - * - * @param {string} itemId id of the cart line item - * @param {number} newQuantity new quantity of the cart line item - * @param {ShopwareApiInstance} contextInstance instance of the api client (by default it's an Axios instance) - * - * @throws ClientApiError - * @public - * - * @category Cart - */ -export async function changeCartItemQuantity( - itemId: string, - newQuantity = 1, - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise { - const params = { - items: [ - { - id: itemId, - quantity: parseInt(newQuantity.toString(), 10), - }, - ], - }; - const resp = await contextInstance.invoke.patch( - getCheckoutCartLineItemEndpoint(), - params, - ); - - return resp.data; -} - -/** - * Deletes the cart line item by id. - * - * This method may be used for deleting "product" type item lines as well as "promotion" type item lines. - * - * @param itemId - id of the cart line item - * @param contextInstance - instance of the api client (by default it's an Axios instance) - * - * @throws ClientApiError - * @category Cart - * @public - */ -export async function removeCartItem( - itemId: string, - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise { - const resp = await contextInstance.invoke.delete( - `${getCheckoutCartLineItemEndpoint()}?ids[]=${itemId}`, - ); - - return resp.data; -} - -/** - * Adds new promotion code to the cart by its code. - * - * Promotion code is being added as separate cart item line. - * - * @param promotionCode - code of the promotion - * @param contextInstance - instance of the api client (by default it's an Axios instance) - * - * @throws ClientApiError - * @category Cart - * @public - */ -export async function addPromotionCode( - promotionCode: string, - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise { - const item: Partial = { - type: "promotion", - referencedId: promotionCode, - }; - const resp = await contextInstance.invoke.post( - getCheckoutCartLineItemEndpoint(), - { - items: [item], - }, - ); - - return resp.data; -} - -/** - * Adds multiple items to the cart. - * Accepts every type of cart item. - * - * @param items - array of cart items - * @param contextInstance - instance of the api client (by default it's an Axios instance) - * - * @throws ClientApiError - * @category Cart - * @public - */ -export async function addCartItems( - items: Partial[], - contextInstance: ShopwareApiInstance = defaultInstance, -) { - const resp = await contextInstance.invoke.post( - getCheckoutCartLineItemEndpoint(), - { - items, - }, - ); - - return resp.data; -} diff --git a/packages/api-client-old/src/services/categoryService.ts b/packages/api-client-old/src/services/categoryService.ts deleted file mode 100644 index 32ea7762e..000000000 --- a/packages/api-client-old/src/services/categoryService.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { getCategoryEndpoint, getCategoryDetailsEndpoint } from "../endpoints"; -import type { - Category, - EntityResult, - ShopwareSearchParams, -} from "@shopware-pwa/types"; -import { defaultInstance, ShopwareApiInstance } from "../apiService"; - -/** - * Get a list of categories by provided search criteria. - * - * @param {ShopwareSearchParams} search criteria search criteria for categories - * @param {ShopwareApiInstance} contextInstance instance of the api client (by default it's an Axios instance) - * - * @throws ClientApiError - * @category Category - * @public - */ -export async function getCategories( - searchCriteria?: ShopwareSearchParams, - contextInstance: ShopwareApiInstance = defaultInstance, -) { - const resp = await contextInstance.invoke.post< - EntityResult<"category", Category> - >(getCategoryEndpoint(), searchCriteria); - - return resp.data; -} - -/** - * Get a single category by its id. - * - * @param {string} categoryId id of the category - * @param {ShopwareApiInstance} contextInstance instance of the api client (by default it's an Axios instance) - * - * @throws ClientApiError - * @category Category - * @public - */ -export async function getCategory( - categoryId: string, - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise { - const resp = await contextInstance.invoke.get( - getCategoryDetailsEndpoint(categoryId), - ); - - return resp.data; -} diff --git a/packages/api-client-old/src/services/checkoutService.ts b/packages/api-client-old/src/services/checkoutService.ts deleted file mode 100644 index 2a9dc7961..000000000 --- a/packages/api-client-old/src/services/checkoutService.ts +++ /dev/null @@ -1,158 +0,0 @@ -import { defaultInstance, ShopwareApiInstance } from "../apiService"; -import { - getCheckoutOrderEndpoint, - handlePaymentEndpoint, - getCustomerOrderEndpoint, - getCancelOrderEndpoint, - getChangeOrderPaymentMethodEndpoint, -} from "../endpoints"; -import type { - CreateOrderParams, - Order, - OrderState, - ShopwareSearchParams, -} from "@shopware-pwa/types"; - -/** - * Creates an order for logged in and guest users - * - * @param params CreateOrderParams - * @param contextInstance ShopwareApiInstance - * - * @category Checkout - * @public - */ -export async function createOrder( - params?: CreateOrderParams, - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise { - const resp = await contextInstance.invoke.post( - getCheckoutOrderEndpoint(), - params, - ); - - return resp.data; -} - -/** - * @param orderId Id of an order - * @param finishUrl URL where the customer is redirected to after payment is done - * @param errorUrl URL where the customer is redirected to after payment fails - * - * @category Checkout - * @public - */ -export async function handlePayment( - params: { - orderId: string; - finishUrl?: string; - errorUrl?: string; - paymentDetails?: unknown; - }, - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise<{ - redirectUrl: string | null; - apiAlias: string; -}> { - if (!params?.orderId) { - throw new Error("handlePayment method requires orderId"); - } - - /** - * save contextToken in sessionStorage when using Webkit - * https://github.com/vuestorefront/shopware-pwa/pull/1817 - */ - if (navigator?.userAgent.includes("WebKit")) { - if (typeof sessionStorage !== "undefined") { - sessionStorage.setItem( - "sw-context-token", - contextInstance.config.contextToken as string, - ); - } - } - - const resp = await contextInstance.invoke.get(handlePaymentEndpoint(), { - params, - }); - - return resp.data; -} - -/** - * Get order details - * - * @param orderId Id of an order - * @param params ShopwareSearchParams - * @param contextInstance - ShopwareApiInstance - * - * @throws ClientApiError - * @category Checkout - * @public - */ -export async function getOrderDetails( - orderId: string, - params?: ShopwareSearchParams, - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise { - const resp = await contextInstance.invoke.post( - getCustomerOrderEndpoint(), - Object.assign({}, params, { - filter: [ - { - // filter order's collection by given id - type: "equals", - field: "id", - value: orderId, - }, - ], - }), - ); - return resp.data?.orders?.elements?.[0]; -} - -/** - * Cancel an order - * - * @param orderId Id of an order - * @param contextInstance - ShopwareApiInstance - * - * @throws ClientApiError - * @category Checkout - * @public - */ -export async function cancelOrder( - orderId: string, - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise { - const resp = await contextInstance.invoke.post(getCancelOrderEndpoint(), { - orderId, - }); - return resp.data; -} - -/** - * Change payment method for given order - * - * @param orderId Id of an order - * - * @throws ClientApiError - * @category Checkout - * @public - */ -export async function changeOrderPaymentMethod( - orderId: string, - paymentMethodId: string, - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise<{ - apiAlias: string; - success: boolean; -}> { - const resp = await contextInstance.invoke.post( - getChangeOrderPaymentMethodEndpoint(), - { - orderId, - paymentMethodId, - }, - ); - return resp.data; -} diff --git a/packages/api-client-old/src/services/contextService.ts b/packages/api-client-old/src/services/contextService.ts deleted file mode 100644 index 2eacdfdd3..000000000 --- a/packages/api-client-old/src/services/contextService.ts +++ /dev/null @@ -1,448 +0,0 @@ -import type { Currency } from "@shopware-pwa/types"; -import { defaultInstance, ShopwareApiInstance } from "../apiService"; -import { - getContextCurrencyEndpoint, - getContextCountryEndpoint, - getContextPaymentMethodEndpoint, - getContextShippingMethodEndpoint, - getContextLanguageEndpoint, - getContextSalutationEndpoint, - getContextEndpoint, -} from "../endpoints"; -import type { - Country, - ShippingMethod, - PaymentMethod, - Language, - Salutation, - EntityResult, - UpdateContextParams, - ContextTokenResponse, - SessionContext, - ShopwareSearchParams, -} from "@shopware-pwa/types"; -import { extractContextToken } from "../helpers/context"; - -/** - * Updates the current session's context - * - * @param params {UpdateContextParams} params to update the context - * @param {ShopwareApiInstance} contextInstance instance of the api client (by default it's an Axios instance) - * - * @throws ClientApiError - * @category Context - * @public - */ -async function updateContext( - params: UpdateContextParams, - contextInstance: ShopwareApiInstance, -): Promise<{ - contextToken: string; - redirectUrl?: string; - apiAlias: "array_struct"; -}> { - const resp = await contextInstance.invoke.patch(getContextEndpoint(), params); - const contextToken = extractContextToken(resp); - return { - contextToken, - redirectUrl: resp.data.redirectUrl, - apiAlias: "array_struct", - }; -} - -/** - * Loads session context, containing all session-related data. - * - * @param {ShopwareApiInstance} contextInstance instance of the api client (by default it's an Axios instance) - * - * @throws ClientApiErrosr - * @category Context - * @public - */ -export async function getSessionContext( - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise { - const { data } = await contextInstance.invoke.get(getContextEndpoint()); - return data; -} - -/** - * Set the current session's shipping address to correspoding to id - * - * @param {string} shippingAddressId id of the shipping address - * @param {ShopwareApiInstance} contextInstance instance of the api client (by default it's an Axios instance) - * - * @throws ClientApiError - * @category Context - * @public - */ -export async function setCurrentShippingAddress( - shippingAddressId: string, - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise { - return (await updateContext( - { shippingAddressId }, - contextInstance, - )) as unknown as ContextTokenResponse; -} - -/** - * Set the current session's billing address to correspoding to id - * - * @param {string} billingAddressId id of the billing address - * @param {ShopwareApiInstance} contextInstance instance of the api client (by default it's an Axios instance) - * - * @throws ClientApiError - * @category Context - * @public - */ -export async function setCurrentBillingAddress( - billingAddressId: string, - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise { - return (await updateContext( - { billingAddressId }, - contextInstance, - )) as unknown as ContextTokenResponse; -} - -/** - * Get all available currencies - * - * @param {ShopwareApiInstance} contextInstance instance of the api client (by default it's an Axios instance) - * - * @throws ClientApiError - * @category Context - * @public - */ -export async function getAvailableCurrencies( - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise { - const { data } = await contextInstance.invoke.get( - getContextCurrencyEndpoint(), - ); - - return data; -} - -/** - * Set the current session's currency to correspoding to id - * - * @param {string} newCurrencyID id of the currency - * @param {ShopwareApiInstance} contextInstance instance of the api client (by default it's an Axios instance) - * - * @throws ClientApiError - * @category Context - * @public - */ -export async function setCurrentCurrency( - newCurrencyID: string, - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise { - const params = { currencyId: newCurrencyID }; - const resp = (await updateContext( - params, - contextInstance, - )) as unknown as ContextTokenResponse; - - return resp; -} - -/** - * Get all available languages - * - * @param {ShopwareApiInstance} contextInstance instance of the api client (by default it's an Axios instance) - * - * @throws ClientApiError - * @category Context - * @public - */ -export async function getAvailableLanguages( - contextInstance: ShopwareApiInstance = defaultInstance, -) { - const { data } = await contextInstance.invoke.get< - EntityResult<"language", Language> - >(getContextLanguageEndpoint()); - - return data; -} - -/** - * Set the current session's language to corresponding to id - * - * @param {string} newLanguageId id of the language - * @param {ShopwareApiInstance} contextInstance instance of the api client (by default it's an Axios instance) - * - * @throws ClientApiError - * @category Context - * @public - */ -export async function setCurrentLanguage( - newLanguageId: string, - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise { - const params = { languageId: newLanguageId }; - const resp = (await updateContext( - params, - contextInstance, - )) as unknown as ContextTokenResponse; - - return resp; -} - -/** - * Set the current session's country - * - * @param {string} newCountryId id of the country - * @param {ShopwareApiInstance} contextInstance instance of the api client (by default it's an Axios instance) - * - * @throws ClientApiError - * @category Context - * @public - */ - -export async function setCurrentCountry( - newCountryId: string, - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise { - const params = { countryId: newCountryId }; - const resp = (await updateContext( - params, - contextInstance, - )) as unknown as ContextTokenResponse; - - return resp; -} - -/** - * Get all available countries - * - * @param {ShopwareApiInstance} contextInstance instance of the api client (by default it's an Axios instance) - * - * @throws ClientApiError - * @category Context - * @public - */ -export async function getAvailableCountries( - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise> { - const { data } = await contextInstance.invoke.post< - EntityResult<"country", Country> - >(getContextCountryEndpoint(), { - associations: { - states: {}, - }, - }); - return data; -} - -/** - * Get all available salutations - * - * @param {ShopwareApiInstance} contextInstance instance of the api client (by default it's an Axios instance) - * - * @throws ClientApiError - * @category Context - * @public - */ -export async function getAvailableSalutations( - contextInstance: ShopwareApiInstance = defaultInstance, -) { - const resp = await contextInstance.invoke.get< - EntityResult<"salutation", Salutation> - >(getContextSalutationEndpoint()); - return resp.data; -} - -/** - * get all available payment methods - * - * @param {ShopwareApiInstance} contextInstance instance of the api client (by default it's an Axios instance) - * @param {object} params additional params - * - * @throws ClientApiError - * @category Context - * @public - */ -export async function getAvailablePaymentMethods( - contextInstance: ShopwareApiInstance = defaultInstance, - params: { onlyAvailable?: boolean } = {}, -) { - const resp = await contextInstance.invoke.get< - EntityResult<"payment_method", PaymentMethod> - >(getContextPaymentMethodEndpoint(), { - params, - }); - - return resp.data; -} - -/** - * Get payment method details - * - * @param {string} paymentId id of the payment method - * @param {ShopwareApiInstance} contextInstance instance of the api client (by default it's an Axios instance) - * - * @throws ClientApiError - * @category Context - * @public - */ -export async function getPaymentMethodDetails( - paymentId: string, - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise { - const { data } = await contextInstance.invoke.get( - getContextPaymentMethodEndpoint(), - { - params: { - "filter[id]": paymentId, - }, - }, - ); - - return data?.elements?.[0]; -} - -/** - * Set the current session's payment method to correspoding to id - * - * @param {string} newPaymentMethodId id of the payment method - * @param {ShopwareApiInstance} contextInstance instance of the api client (by default it's an Axios instance) - * - * @throws ClientApiError - * @category Context - * @public - */ -export async function setCurrentPaymentMethod( - newPaymentMethodId: string, - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise { - const params = { paymentMethodId: newPaymentMethodId }; - const resp = (await updateContext( - params, - contextInstance, - )) as unknown as ContextTokenResponse; - - return resp; -} - -/** - * Get all available shipping methods - * - * @param {ShopwareApiInstance} contextInstance instance of the api client (by default it's an Axios instance) - * @param {object} params additional params - * - * @throws ClientApiError - * @category Context - * @public - */ -export async function getAvailableShippingMethods( - contextInstance: ShopwareApiInstance = defaultInstance, - params: ShopwareSearchParams = {}, -) { - const resp = await contextInstance.invoke.post< - EntityResult<"shipping_method", ShippingMethod> - >(getContextShippingMethodEndpoint(), params); - - return resp.data; -} - -/** - * Get Shipping method details - * - * @param {string} shippingId id of the shipping method - * @param {ShopwareApiInstance} contextInstance instance of the api client (by default it's an Axios instance) - * - * @throws ClientApiError - * @category Context - * @public - */ -export async function getShippingMethodDetails( - shippingId: string, - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise { - const { data } = await contextInstance.invoke.get( - getContextShippingMethodEndpoint(), - { - params: { - "filter[id]": shippingId, - }, - }, - ); - - return data?.elements?.[0]; -} - -/** - * Set the current session's shipping method to correspoding to id - * - * @param {string} newShippingMethodId id of the shipping method - * @param {ShopwareApiInstance} contextInstance instance of the api client (by default it's an Axios instance) - * - * @throws ClientApiError - * @category Context - * @public - */ -export async function setCurrentShippingMethod( - newShippingMethodId: string, - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise { - const params = { shippingMethodId: newShippingMethodId }; - const resp = (await updateContext( - params, - contextInstance, - )) as unknown as ContextTokenResponse; - - return resp; -} -/** - * Get the current session's country - * - * @param {string} countryId id of the country - * @param {ShopwareApiInstance} contextInstance instance of the api client (by default it's an Axios instance) - * - * @throws ClientApiError - * @category Context - * @public - */ -export async function getUserCountry( - countryId: string, - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise { - const { data } = await contextInstance.invoke.get( - getContextCountryEndpoint(), - { - params: { - "filter[id]": countryId, - }, - }, - ); - - return data?.elements?.[0]; -} - -/** - * Get the current session's salutation - * - * @param {string} salutationId id of the salutation - * @param {ShopwareApiInstance} contextInstance instance of the api client (by default it's an Axios instance) - * - * @throws ClientApiError - * @category Context - * @public - */ -export async function getUserSalutation( - salutationId: string, - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise { - const { data } = await contextInstance.invoke.get( - getContextSalutationEndpoint(), - { - params: { - "filter[id]": salutationId, - }, - }, - ); - - return data?.elements?.[0]; -} diff --git a/packages/api-client-old/src/services/customerService.ts b/packages/api-client-old/src/services/customerService.ts deleted file mode 100644 index 4007df548..000000000 --- a/packages/api-client-old/src/services/customerService.ts +++ /dev/null @@ -1,493 +0,0 @@ -import { - getCustomerEndpoint, - getCustomerAddressEndpoint, - getCustomerUpdateEmailEndpoint, - getCustomerRegisterEndpoint, - getCustomerDetailsUpdateEndpoint, - getCustomerUpdatePasswordEndpoint, - getCustomerResetPasswordEndpoint, - getCustomerDefaultBillingAddressEndpoint, - getCustomerDefaultShippingAddressEndpoint, - getCustomerLogoutEndpoint, - getCustomerLoginEndpoint, - getCustomerOrderEndpoint, - getCustomerAddAddressEndpoint, - getConfirmPasswordResetEndpoint, - getCustomerAccountConfirmEndpoint, - getCustomerUpdatePaymentMethodEndpoint, - getNewsletterRecipientEndpoint, -} from "../endpoints"; -import { defaultInstance, ShopwareApiInstance } from "../apiService"; -import type { - Customer, - CustomerAddress, - CustomerRegistrationParams, - Order, - EntityResult, - ShopwareSearchParams, - ClientApiError, -} from "@shopware-pwa/types"; - -/** - * @category Customer - * @public - */ -export interface CustomerRegisterResponse { - data: string; -} - -/** - * Register a customer - * - * @param params CustomerRegistrationParams - * @param contextInstance ShopwareApiInstance - * - * @throws ClientApiError - * @category Customer - * @public - */ -export async function register( - params: CustomerRegistrationParams, - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise { - const resp = await contextInstance.invoke.post( - getCustomerRegisterEndpoint(), - params, - ); - return resp.data; -} - -/** - * Login user to shopware instance. - * - * @param {object} parameters username and password - * @param contextInstance ShopwareApiInstance - * - * @throws ClientApiError - * @category Customer - * @public - */ -export async function login( - parameters: { username?: string; password?: string } = {}, - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise<{ contextToken: string; apiAlias: "array_struct" }> { - const resp = await contextInstance.invoke.post( - getCustomerLoginEndpoint(), - parameters, - ); - const contextToken = - resp.data["sw-context-token"] || resp.data["contextToken"]; - return { contextToken, apiAlias: "array_struct" }; -} - -/** - * End up the user session. - * - * @param contextInstance ShopwareApiInstance - * - * @throws ClientApiError - * @category Customer - * @public - */ -export async function logout( - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise { - await contextInstance.invoke.post(getCustomerLogoutEndpoint()); -} - -/** - * Get customer's object - * - * @param parameters ShopwareSearchParams - * - * @throws ClientApiError - * @category Customer - * @public - */ -export async function getCustomer( - parameters: ShopwareSearchParams = {}, - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise { - try { - const resp = await contextInstance.invoke.post( - getCustomerEndpoint(), - parameters, - ); - return resp.data; - } catch (e) { - const err = e as ClientApiError; - if (err.statusCode === 403) return null; - throw new Error("Unexpected getCustomerResponse. " + err); - } -} - -/** - * Get all customer's addresses - * - * @param parameters ShopwareSearchParams - * @param contextInstance ShopwareApiInstance - * - * @throws ClientApiError - * @category Customer - * @public - */ -export async function getCustomerAddresses( - parameters: ShopwareSearchParams = {}, - contextInstance: ShopwareApiInstance = defaultInstance, -) { - const resp = await contextInstance.invoke.post< - EntityResult<"customer_address", CustomerAddress> - >(getCustomerAddressEndpoint(), parameters); - return resp.data; -} - -type CustomerOrdersResponse = { - apiAlias: "order-route-response-struct"; - orders: EntityResult<"order", Order>; - paymentChangeable: { [key: string]: number } | []; -}; -/** - * Get all customer's orders - * - * @param parameters ShopwareSearchParams - * @param contextInstance ShopwareApiInstance - * - * @throws ClientApiError - * @category Customer - * @public - */ -export async function getCustomerOrders( - parameters: ShopwareSearchParams = {}, - contextInstance: ShopwareApiInstance = defaultInstance, -) { - const resp = await contextInstance.invoke.post( - getCustomerOrderEndpoint(), - parameters, - ); - return resp.data.orders; -} - -/** - * Get the customer's address by id - * - * @param {string} addressId ID of the address - * @param contextInstance ShopwareApiInstance - * - * @throws ClientApiError - * @category Customer - * @public - */ -export async function getCustomerAddress( - addressId: string, - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise { - const resp = await contextInstance.invoke.get( - getCustomerAddressEndpoint(addressId), - ); - return resp.data.data; -} - -/** - * Create an address and respond the new address's id - * - * @param {Partial} params address data - * @param contextInstance ShopwareApiInstance - * - * @throws ClientApiError - * @category Customer - * @public - */ -export async function createCustomerAddress( - params: Partial, - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise { - const resp = await contextInstance.invoke.post( - getCustomerAddAddressEndpoint(), - params, - ); - return resp.data; -} - -/** - * Update an address for specific ID - * - * @param {Partial} params address data - * @param contextInstance ShopwareApiInstance - * - * @throws ClientApiError - * @category Customer - * @public - */ -export async function updateCustomerAddress( - params: Partial, - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise { - const resp = await contextInstance.invoke.patch( - getCustomerAddressEndpoint(params.id), - params, - ); - return resp.data; -} - -/** - * Delete's the customer's address by id - * - * @param {string} addressId ID of the address - * @param contextInstance ShopwareApiInstance - * - * @throws ClientApiError - * @category Customer - * @public - */ -export async function deleteCustomerAddress( - addressId: string, - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise { - await contextInstance.invoke.delete(getCustomerAddressEndpoint(addressId)); -} - -/** - * Set address as default - * - * @param {string} addressId ID of the address - * @param contextInstance ShopwareApiInstance - * - * @throws ClientApiError - * @category Customer - * @public - */ -export async function setDefaultCustomerBillingAddress( - addressId: string, - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise { - const response = await contextInstance.invoke.patch( - getCustomerDefaultBillingAddressEndpoint(addressId), - ); - return response.data; -} - -/** - * Set address as default - * - * @param {string} addressId ID of the address - * @param contextInstance ShopwareApiInstance - * - * @throws ClientApiError - * @category Customer - * @public - */ -export async function setDefaultCustomerShippingAddress( - addressId: string, - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise { - const response = await contextInstance.invoke.patch( - getCustomerDefaultShippingAddressEndpoint(addressId), - ); - return response.data; -} - -/** - * @category Customer - * @public - */ -export interface CustomerUpdateEmailParam { - email: string; - emailConfirmation: string; - password: string; -} - -/** - * Update a customer's email - * - * @param params CustomerUpdateEmailParam email data - * @param contextInstance ShopwareApiInstance - * - * @throws ClientApiError - * @category Customer - * @public - */ -export async function updateEmail( - params: CustomerUpdateEmailParam, - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise { - await contextInstance.invoke.post(getCustomerUpdateEmailEndpoint(), params); -} - -/** - * @category Customer - * @public - */ -export interface CustomerUpdatePasswordParam { - password: string; - newPassword: string; - newPasswordConfirm: string; -} - -/** - * Update a customer's password - * - * @param params CustomerUpdatePasswordParam password data - * @param contextInstance ShopwareApiInstance - * - * @throws ClientApiError - * @category Customer - * @public - */ -export async function updatePassword( - params: CustomerUpdatePasswordParam, - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise { - await contextInstance.invoke.post( - getCustomerUpdatePasswordEndpoint(), - params, - ); -} - -/** - * @category Customer - * @public - */ -export interface CustomerResetPasswordParam { - email: string; - storefrontUrl?: string; -} - -/** - * Reset a customer's password - * - * @param params CustomerResetPasswordParam password data - * @param contextInstance ShopwareApiInstance - * - * @throws ClientApiError - * @category Customer - * @public - */ -export async function resetPassword( - params: CustomerResetPasswordParam, - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise { - if (params && !params.storefrontUrl) { - params.storefrontUrl = contextInstance.config.endpoint; - } - - await contextInstance.invoke.post(getCustomerResetPasswordEndpoint(), params); -} - -/** - * Confirm a customer's password reset. Set new password for account. - * - * @param {object} params new password and hash - * - * @throws ClientApiError - * @category Customer - * @public - */ -export async function confirmPasswordReset( - params: { - newPassword: string; - hash: string; - [key: string]: unknown; // additional params - }, - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise { - if (!params) return; - await contextInstance.invoke.post(getConfirmPasswordResetEndpoint(), { - newPasswordConfirm: params.newPassword, - ...params, - }); -} - -/** - * @category Customer - * @public - */ -export interface CustomerUpdateProfileParam { - firstName: string; - lastName: string; - salutationId: string; - title: string | null; -} - -/** - * Update a customer's profile data - * - * @param {object} params profile data - * @param contextInstance ShopwareApiInstance - * - * @throws ClientApiError - * @category Customer - * @public - */ -export async function updateProfile( - params: CustomerUpdateProfileParam, - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise { - await contextInstance.invoke.post(getCustomerDetailsUpdateEndpoint(), params); -} - -/** - * Confirm an account registration in double opt-in mode - * - * @param params hash and em tokens - * @param contextInstance ShopwareApiInstance - * - * @throws ClientApiError - * @category Customer - * @public - */ -export async function confirmAccountRegistration( - params: { - hash: string; - em: string; - }, - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise { - const response = await contextInstance.invoke.post( - getCustomerAccountConfirmEndpoint(), - params, - ); - return response.data; -} - -/** - * Set payment method under provided ID as default - * - * @param {string} paymentMethodId ID of the payment method - * @param contextInstance ShopwareApiInstance - * - * @throws ClientApiError - * @category Customer - * @public - */ -export async function setDefaultCustomerPaymentMethod( - paymentMethodId: string, - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise<{ - success: boolean; -}> { - const response = await contextInstance.invoke.post( - getCustomerUpdatePaymentMethodEndpoint(paymentMethodId), - ); - return response.data; -} - -/** - * Checking if user is newsletter subscriber - * - * @param contextInstance ShopwareApiInstance - * - * @throws ClientApiError - * @category Customer - * @public - */ -export async function isNewsletterSubscriber( - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise<{ - status: string; - apiAlias: string; -}> { - const response = await contextInstance.invoke.post( - getNewsletterRecipientEndpoint(), - ); - return response.data; -} diff --git a/packages/api-client-old/src/services/documentService.ts b/packages/api-client-old/src/services/documentService.ts deleted file mode 100644 index 723025033..000000000 --- a/packages/api-client-old/src/services/documentService.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { getDocumentDownloadEndpoint } from "../endpoints"; -import { defaultInstance, ShopwareApiInstance } from "../apiService"; - -type DocumentDownloadParams = { - documentId: string; - deepLinkCode: string; -}; - -/** - * Download selected document - * - * @param {DocumentDownloadParams} params documentId and deepLinkCode - * - * @throws ClientApiError - * @public - */ -export async function getDocumentDownload( - params: DocumentDownloadParams, - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise { - const resp = await contextInstance.invoke.get( - getDocumentDownloadEndpoint(params.documentId, params.deepLinkCode), - { - responseType: "blob", - }, - ); - return resp.data; -} diff --git a/packages/api-client-old/src/services/formsService.ts b/packages/api-client-old/src/services/formsService.ts deleted file mode 100644 index 4a2e26771..000000000 --- a/packages/api-client-old/src/services/formsService.ts +++ /dev/null @@ -1,122 +0,0 @@ -import { - getContactFormEndpoint, - getStoreNewsletterSubscribeEndpoint, - getStoreNewsletterUnsubscribeEndpoint, -} from "../endpoints"; -import { defaultInstance, ShopwareApiInstance } from "../apiService"; - -/** - * @category Forms - * @public - */ -export interface ContactFormData { - cmsPageType?: string; - /** The message of the contact form */ - comment: string; - /** Email address */ - email: string; - /** Entity name for slot config */ - entityName?: string; - /** Firstname. This field may be required depending on the system settings. */ - firstName?: string; - /** Lastname. This field may be required depending on the system settings. */ - lastName?: string; - /** - * Identifier of the navigation page. Can be used to override the configuration. - * Take a look at the settings of a category containing a concact form in the administration. - */ - navigationId?: string; - /** Phone. This field may be required depending on the system settings. */ - phone?: string; - /** Identifier of the salutation. Use `/api/salutation` endpoint to fetch possible values. */ - salutationId: string; - /** Identifier of the cms element */ - slotId?: string; - /** The subject of the contact form. */ - subject: string; -} - -/** - * Sends contact form - * - * @param {ContactFormData} params contact form data - * @param {ShopwareApiInstance} contextInstance instance of the api client (by default it's an Axios instance) - * - * @category Forms - * @public - */ -export async function sendContactForm( - params: ContactFormData, - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise { - await contextInstance.invoke.post(getContactFormEndpoint(), params); -} - -/** - * @category Forms - * @public - */ -export interface NewsletterSubscribeData { - /** City */ - city?: string; - /** Custom field data that should be added to the subscription. */ - customFields?: string; - /** Email address that will receive the confirmation and the newsletter. */ - email: string; - /** First name */ - firstName?: string; - /** Identifier of the language. */ - languageId?: string; - /** Last name */ - lastName?: string; - /** Defines what should be done. */ - option: string; - /** Identifier of the salutation. */ - salutationId?: string; - /** Url of the storefront of the shop. This will be used for generating the link to the /newsletter/confirm inside the confirm email. */ - storefrontUrl: string; - /** Street */ - street?: string; - /** Zip code */ - tags?: string; - /** Zip code */ - zipCode?: string; -} -/** - * Subscribes to newsletter - * - * @param {NewsletterSubscribeData} params newsletter subscribe data - * @param {ShopwareApiInstance} contextInstance instance of the api client (by default it's an Axios instance) - * - * @category Forms - * @public - */ -export async function newsletterSubscribe( - params: NewsletterSubscribeData, - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise { - await contextInstance.invoke.post( - getStoreNewsletterSubscribeEndpoint(), - Object.assign({}, { option: "subscribe" }, params), - ); -} - -/** - * Unsubscribe from newsletter - * - * @param {NewsletterSubscribeData} params newsletter subscribe data: email - * - * @category Forms - * @public - */ -export async function newsletterUnsubscribe( - params: { - email: string; - }, - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise { - await contextInstance.invoke.post( - getStoreNewsletterUnsubscribeEndpoint(), - params, - ); -} diff --git a/packages/api-client-old/src/services/navigationService.ts b/packages/api-client-old/src/services/navigationService.ts deleted file mode 100644 index 23902657c..000000000 --- a/packages/api-client-old/src/services/navigationService.ts +++ /dev/null @@ -1,54 +0,0 @@ -import { getStoreNavigationEndpoint } from "../endpoints"; -import { defaultInstance, ShopwareApiInstance } from "../apiService"; -import type { - StoreNavigationElement, - StoreNavigationType, - ShopwareSearchParams, -} from "@shopware-pwa/types"; - -/** - * More about the navigation parameters: https://docs.shopware.com/en/shopware-platform-dev-en/store-api-guide/navigation?category=shopware-platform-dev-en/store-api-guide - * @category Navigation - * @public - */ -export interface GetStoreNavigationParams { - requestActiveId: StoreNavigationType; - requestRootId: StoreNavigationType; - depth?: number; - buildTree?: boolean; - searchCriteria?: ShopwareSearchParams; -} - -/** - * Get a list of categories by provided search criteria. - * - * @param {GetStoreNavigationParams} params search criteria for categories - * @param {ShopwareApiInstance} contextInstance instance of the api client (by default it's an Axios instance) - * - * @throws ClientApiError - * @category Navigation - * @public - */ -export async function getStoreNavigation( - { - requestActiveId, - requestRootId, - depth, - buildTree, - searchCriteria, - }: GetStoreNavigationParams, - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise { - const resp = await contextInstance.invoke.post( - getStoreNavigationEndpoint(requestActiveId, requestRootId), - { - ...(searchCriteria || {}), - ...{ - depth, - buildTree, - }, - }, - ); - - return resp.data; -} diff --git a/packages/api-client-old/src/services/newsletterService.ts b/packages/api-client-old/src/services/newsletterService.ts deleted file mode 100644 index 924c86adc..000000000 --- a/packages/api-client-old/src/services/newsletterService.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { getStoreNewsletterConfirmEndpoint } from "../endpoints"; -import { defaultInstance, ShopwareApiInstance } from "../apiService"; - -type NewsletterConfirmationParams = { - /** Email hash from the email received */ - em: string; - /** Hash from the email received */ - hash: string; -}; - -/** - * Confirmation from newsletter - * - * @param {NewsletterConfirmationParams} params - * @param {ShopwareApiInstance} contextInstance - * @returns - */ -export async function newsletterConfirmation( - params: NewsletterConfirmationParams, - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise { - const response = await contextInstance.invoke.post( - getStoreNewsletterConfirmEndpoint(), - params, - ); - return response.data; -} diff --git a/packages/api-client-old/src/services/orderService.ts b/packages/api-client-old/src/services/orderService.ts deleted file mode 100644 index fa646780d..000000000 --- a/packages/api-client-old/src/services/orderService.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { defaultInstance, ShopwareApiInstance } from "../apiService"; -import { getOrderDownloadsEndpoint } from "../endpoints"; - -type GetUserCountryParams = { - orderId: string; - downloadId: string; -}; - -/** - * Get order downloads (file) - * - * @param {GetUserCountryParams} data orderId and downloadId - * @param {ShopwareApiInstance} contextInstance instance of the api client (by default it's an Axios instance) - * - * @throws ClientApiError - * @public - */ -export async function getOrderDownloads( - data: GetUserCountryParams, - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise { - const resp = await contextInstance.invoke.get( - getOrderDownloadsEndpoint(data.orderId, data.downloadId), - { - responseType: "blob", - }, - ); - return resp.data; -} diff --git a/packages/api-client-old/src/services/pageService.ts b/packages/api-client-old/src/services/pageService.ts deleted file mode 100644 index fbc5b9ba0..000000000 --- a/packages/api-client-old/src/services/pageService.ts +++ /dev/null @@ -1,132 +0,0 @@ -import { - getLandingPageDetailsEndpoint, - getPageResolverEndpoint, - getSeoUrlEndpoint, - getCmsEndpoint, -} from "../endpoints"; -import { defaultInstance, ShopwareApiInstance } from "../apiService"; -import type { - ShopwareSearchParams, - CmsPageResponse, - EntityResult, - SeoUrl, - LandingPage, -} from "@shopware-pwa/types"; -import { invokePost } from "./pluginService"; - -/** - * @throws ClientApiError - * @category CMS - * @public - * @deprecated the method is becoming obsolete and will be removed in the future as the SwagShopwarePwa plugin won't be needed. - */ -export async function getCmsPage( - path: string, - criteria?: ShopwareSearchParams, - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise { - const resp = await contextInstance.invoke.post(getPageResolverEndpoint(), { - path: path, - ...criteria, - }); - - return resp.data; -} - -/** - * Fetches a landing page entity - * - * @param {string} landingPageId id of the landing page - * @param {ShopwareSearchParams} params search criteria for landing page - * @param {ShopwareApiInstance} contextInstance instance of the api client (by default it's an Axios instance) - * - * @throws ClientApiError - * @category CMS - * @public - */ -export async function getLandingPage( - landingPageId: string, - params?: ShopwareSearchParams, - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise { - const endpoint = getLandingPageDetailsEndpoint(landingPageId); - const response = await contextInstance.invoke.post(endpoint, params); - return response?.data; -} - -/** - * Returns an array of SEO URLs for given entity - * Can be used for other languages as well by providing the languageId - * - * @param {string} entityId id of the entity - * @param {string} languageId id of the language - * @param {ShopwareApiInstance} contextInstance instance of the api client (by default it's an Axios instance) - * - * @category CMS - * @public - */ -export async function getSeoUrls( - entityId: string, - languageId?: string, - contextInstance: ShopwareApiInstance = defaultInstance, -) { - if (languageId) { - contextInstance.defaults.headers.common["sw-language-id"] = languageId; - } - const resp = await contextInstance.invoke.post< - EntityResult<"seo_url", SeoUrl> - >(getSeoUrlEndpoint(), { - filter: [ - { - type: "equals", - field: "foreignKey", - value: entityId, - }, - ], - includes: { - seo_url: ["seoPathInfo"], - }, - }); - - return resp.data; -} - -/** - * Returns an array of SEO URLs for given entity - * - * @param {ShopwareSearchParams} params search criteria for SEO URL - * @param {ShopwareApiInstance} contextInstance instance of the api client (by default it's an Axios instance) - * - * @category CMS - * @public - * @throws ClientApiError - */ -export async function getSeoUrl( - params: ShopwareSearchParams, - contextInstance: ShopwareApiInstance = defaultInstance, -) { - const seoUrlResponse = await invokePost>( - { - address: getSeoUrlEndpoint(), - payload: params, - }, - contextInstance, - ); - - return seoUrlResponse.data; -} - -/** - * Returns Shopware CMS page data - * - * @param {string} pageId - * @param {ShopwareApiInstance} contextInstance - * @returns - */ -export async function getSwCmsPage( - pageId: string, - contextInstance: ShopwareApiInstance = defaultInstance, -) { - const resp = await contextInstance.invoke.post(getCmsEndpoint(pageId)); - return resp.data; -} diff --git a/packages/api-client-old/src/services/pluginService.ts b/packages/api-client-old/src/services/pluginService.ts deleted file mode 100644 index 30a8e0e02..000000000 --- a/packages/api-client-old/src/services/pluginService.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { AxiosResponse } from "axios"; -import { defaultInstance, ShopwareApiInstance } from "../apiService"; - -/** - * Invoke custom POST request to shopware API. Mostly for plugins usage. - * You can skip domain and pass only endpoint ex. `/api/my/endpoint` - * - * @param {string} address endpoint address - * @param {unknown} payload payload to send - * @param {ShopwareApiInstance} contextInstance instance of the api client (by default it's an Axios instance) - * - * @throws ClientApiError - * @public - */ -export function invokePost( - { - address, - payload, - }: { - address: string; - payload?: unknown; - }, - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise> { - return contextInstance.invoke.post(address, payload); -} - -/** - * Invoke custom GET request to shopware API. Mostly for plugins usage. - * You can skip domain and pass only endpoint ex. `/api/my/endpoint` - * - * @param {string} address endpoint address - * @param {ShopwareApiInstance} contextInstance instance of the api client (by default it's an Axios instance) - * - * @throws ClientApiError - * @public - */ -export function invokeGet( - { address }: { address: string }, - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise> { - return contextInstance.invoke.get(address); -} diff --git a/packages/api-client-old/src/services/productService.ts b/packages/api-client-old/src/services/productService.ts deleted file mode 100644 index 5fc727364..000000000 --- a/packages/api-client-old/src/services/productService.ts +++ /dev/null @@ -1,169 +0,0 @@ -import { - getProductEndpoint, - getProductDetailsEndpoint, - getProductListingEndpoint, - getProductReviewsEndpoint, - getProductCrossSellingEndpoint, -} from "../endpoints"; -import type { - ProductListingResult, - Product, - ShopwareSearchParams, - ProductResponse, - EntityResult, - ProductReview, -} from "@shopware-pwa/types"; - -import { defaultInstance, ShopwareApiInstance } from "../apiService"; - -/** - * Get default amount of products - * - * @param {ShopwareSearchParams} criteria search criteria for products - * @param {ShopwareApiInstance} contextInstance instance of the api client (by default it's an Axios instance) - * - * @throws ClientApiError - * @category Product - * @public - */ -export async function getProducts( - criteria?: ShopwareSearchParams, - contextInstance: ShopwareApiInstance = defaultInstance, -) { - const resp = await contextInstance.invoke.post< - EntityResult<"product", Product> - >(`${getProductEndpoint()}`, { - ...(criteria || {}), - }); - return resp.data; -} - -/** - * Get default amount of products and listing configuration for given category - * - * @throws ClientApiError - * @category Product - * @public - */ -export async function getCategoryProducts( - categoryId: string, - criteria?: ShopwareSearchParams, - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise { - const resp = await contextInstance.invoke.post( - `${getProductListingEndpoint(categoryId)}`, - criteria, - ); - return resp.data; -} - -/** - * Get the product with passed productId - * - * @throws ClientApiError - * @category Product - * @public - */ -export async function getProduct( - productId: string, - params: unknown = null, - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise { - const resp = await contextInstance.invoke.post( - getProductDetailsEndpoint(productId), - params, - ); - return resp.data; -} - -/** - * Get the product with passed productId - * - * @throws ClientApiError - * @category Product - * @public - */ -export async function getProductCrossSelling( - productId: string, - params: unknown = null, - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise<{ - crossSelling: { - name: string; - }; -}> { - const resp = await contextInstance.invoke.post( - getProductCrossSellingEndpoint(productId), - params, - ); - return resp.data; -} - -/** - * Add a review to specific product by its ID - * - * @throws ClientApiError - * @category Product - * @public - */ -export async function addProductReview( - productId: string, - productReviewData: { - title: string; - content: string; - points: number; - }, - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise { - await contextInstance.invoke.post( - `${getProductDetailsEndpoint(productId)}/review`, - productReviewData, - ); -} - -/** - * Get product reviews - * - * @throws ClientApiError - * @category Product - * @public - */ -export async function getProductReviews( - productId: string, - criteria?: ShopwareSearchParams, - contextInstance: ShopwareApiInstance = defaultInstance, -) { - const resp = await contextInstance.invoke.post< - EntityResult<"product_review", ProductReview> - >(`${getProductReviewsEndpoint(productId)}`, { - ...(criteria || {}), - }); - return resp.data; -} - -/** - * Get matching product variant for given options - * - * @category Product - */ -export async function getProductVariantForOptions( - { - productId, - optionIds, - switchedGroup, - }: { productId?: string; optionIds?: string[]; switchedGroup?: string }, - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise<{ - variantId: string; - options: string[]; -}> { - const response = await contextInstance.invoke.post<{ - variantId: string; - options: string[]; - }>(`/store-api/product/${productId}/find-variant`, { - options: optionIds, - switchedGroup, - }); - - return response?.data; -} diff --git a/packages/api-client-old/src/services/searchService.ts b/packages/api-client-old/src/services/searchService.ts deleted file mode 100644 index 724ab650a..000000000 --- a/packages/api-client-old/src/services/searchService.ts +++ /dev/null @@ -1,54 +0,0 @@ -import { getSuggestSearchEndpoint, getSearchEndpoint } from "../endpoints"; -import { defaultInstance, ShopwareApiInstance } from "../apiService"; -import type { - ProductListingResult, - ShopwareSearchParams, -} from "@shopware-pwa/types"; - -/** - * Search for products based on criteria. - * From: Shopware 6.4 - * - * @param {ShopwareSearchParams} criteria search criteria for products - * @param {ShopwareApiInstance} contextInstance instance of the api client (by default it's an Axios instance) - * - * @category Search - * @public - */ -export async function searchProducts( - criteria?: ShopwareSearchParams & { query?: string }, - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise { - const resp = await contextInstance.invoke.post( - `${getSearchEndpoint()}?search=${encodeURIComponent( - criteria?.query || "", - )}`, - criteria, - ); - - return resp.data; -} - -/** - * Search for suggested products based on criteria. - * From: Shopware 6.4 - * - * @param {ShopwareSearchParams} criteria search criteria for products - * @param {ShopwareApiInstance} contextInstance instance of the api client (by default it's an Axios instance) - * - * @category Search - * @public - */ -export async function searchSuggestedProducts( - criteria?: ShopwareSearchParams & { query?: string }, - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise { - const resp = await contextInstance.invoke.post( - `${getSuggestSearchEndpoint()}?search=${encodeURIComponent( - criteria?.query || "", - )}`, - criteria, - ); - - return resp.data; -} diff --git a/packages/api-client-old/src/services/sitemapService.ts b/packages/api-client-old/src/services/sitemapService.ts deleted file mode 100644 index 877fb2cb5..000000000 --- a/packages/api-client-old/src/services/sitemapService.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { getSitemapEndpoint } from "../endpoints"; -import { defaultInstance, ShopwareApiInstance } from "../apiService"; -import type { SitemapResult } from "@shopware-pwa/types"; - -/** - * Get sitemap - * - * @throws ClientApiError - * @public - */ -export async function getSitemap( - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise { - const resp = await contextInstance.invoke.get(`${getSitemapEndpoint()}`); - return resp.data; -} diff --git a/packages/api-client-old/src/services/wishlistService.ts b/packages/api-client-old/src/services/wishlistService.ts deleted file mode 100644 index 304e8eead..000000000 --- a/packages/api-client-old/src/services/wishlistService.ts +++ /dev/null @@ -1,113 +0,0 @@ -/** - * WISHLIST feature must be activated in Shopware 6 - */ -import { - getAddWishlistProductEndpoint, - getGetWishlistProductsEndpoint, - getMergeWishlistProductsEndpoint, - getRemoveWishlistProductEndpoint, -} from "../endpoints"; -import { defaultInstance, ShopwareApiInstance } from "../apiService"; -import type { - ShopwareSearchParams, - CustomerWishlistResponse, -} from "@shopware-pwa/types"; - -/** - * Add a product with a specific ID to the wishlist - * - * @param {string} productId ID of the product to add to the wishlist - * @param {ShopwareApiInstance}contextInstance instance of the api client (by default it's an Axios instance) - * - * @remarks Only for logged-in users - * @throws ClientApiError - * @category Wishlist - * @public - */ -export async function addWishlistProduct( - productId: string, - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise<{ - apiAlias: string; - success: boolean; -}> { - const resp = await contextInstance.invoke.post( - getAddWishlistProductEndpoint(productId), - ); - - return resp.data; -} - -/** - * Fetch a current Wishlist with added products - * - * @param {ShopwareSearchParams} criteria search criteria for products - * @param {ShopwareApiInstance} contextInstance instance of the api client (by default it's an Axios instance) - * - * @remarks Only for logged-in users - * @throws ClientApiError - * @category Wishlist - * @public - */ -export async function getWishlistProducts( - criteria?: ShopwareSearchParams, - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise { - const resp = await contextInstance.invoke.post( - getGetWishlistProductsEndpoint(), - criteria, - ); - - return resp.data; -} - -/** - * Delete a product with a specific ID from the wishlist - * - * @param {string} productId ID of the product to remove from the wishlist - * @param {ShopwareApiInstance} contextInstance instance of the api client (by default it's an Axios instance) - * - * @remarks Only for logged-in users - * @throws ClientApiError - * @category Wishlist - * @public - */ -export async function removeWishlistProduct( - productId: string, - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise<{ - apiAlias: string; - success: boolean; -}> { - const resp = await contextInstance.invoke.delete( - getRemoveWishlistProductEndpoint(productId), - ); - - return resp.data; -} - -/** - * Merge the current Wishlist with a products with provided IDs - * - * @param {string[]} productIds IDs of the products to merge with the wishlist - * @param {ShopwareApiInstance} contextInstance instance of the api client (by default it's an Axios instance) - * - * @remarks Only for logged-in users - * @throws ClientApiError - * @category Wishlist - * @public - */ -export async function mergeWishlistProducts( - productIds: string[], - contextInstance: ShopwareApiInstance = defaultInstance, -): Promise<{ - apiAlias: string; - success: boolean; -}> { - const resp = await contextInstance.invoke.post( - getMergeWishlistProductsEndpoint(), - { productIds }, - ); - - return resp.data; -} diff --git a/packages/api-client-old/src/settings.spec.ts b/packages/api-client-old/src/settings.spec.ts deleted file mode 100644 index 38d8b3d35..000000000 --- a/packages/api-client-old/src/settings.spec.ts +++ /dev/null @@ -1,156 +0,0 @@ -import { config, setup, update, onConfigChange } from "."; -import { defaultInstance, _createInstance } from "../src/apiService"; -import { createInstance } from "."; -import { ConfigChangedArgs } from "../src"; -import { faker } from "@faker-js/faker"; -import { defaultConfig } from "./settings"; -import { describe, expect, it, vi, beforeEach } from "vitest"; - -const consoleWarnSpy = vi.spyOn(console, "warn"); - -const DEFAULT_ENDPOINT = defaultConfig.endpoint; -const DEFAULT_TIMEOUT = 10000; - -describe("Settings", () => { - beforeEach(() => { - vi.resetAllMocks(); - setup(); // we need to clean settings to default values before every test - consoleWarnSpy.mockImplementationOnce(() => {}); - }); - - describe("setup", () => { - it("should have default timeout config", () => { - expect(config.timeout).toEqual(DEFAULT_TIMEOUT); - }); - - it("should have default endpoint config", () => { - expect(config.endpoint).toEqual(DEFAULT_ENDPOINT); - }); - - it("should change default endpoint after setup invocation", () => { - setup({ - endpoint: "https://my-new-endpoint.com", - }); - expect(config.endpoint).toEqual("https://my-new-endpoint.com"); - }); - - it("should keep default endpoint between tests", () => { - expect(config.endpoint).toEqual(DEFAULT_ENDPOINT); - }); - - it("should clean contextToken on setup without it", () => { - update({ contextToken: "xxx" }); - setup(); - - expect(config.contextToken).toBeFalsy(); - }); - }); - - describe("update", () => { - it("should have contextToken after update", () => { - update({ contextToken: "xxx" }); - - expect(config.contextToken).toEqual("xxx"); - }); - - it("should have contextToken in axios defaults after update", () => { - update({ contextToken: "xxx" }); - - expect( - defaultInstance.defaults.headers.common["sw-context-token"], - ).toEqual("xxx"); - }); - - it("should clean contextToken from axios detault headers after reset", () => { - update({ contextToken: "xxx" }); - setup(); - - expect( - defaultInstance.defaults.headers.common["sw-context-token"], - ).toBeUndefined(); - }); - - it("should have languageId in axios defaults after update", () => { - update({ languageId: "someLanguageId" }); - - expect(defaultInstance.defaults.headers.common["sw-language-id"]).toEqual( - "someLanguageId", - ); - }); - - it("should clean languageId from axios detault headers after reset", () => { - update({ languageId: "someLanguageId" }); - setup(); - - expect( - defaultInstance.defaults.headers.common["sw-language-id"], - ).toBeUndefined(); - }); - - it("should have default config with empty invocation", () => { - update(); - expect(config.accessToken).toEqual("SWSC40-LJTNO6COUEN7CJMXKLA"); - expect(config.contextToken).toEqual(""); - }); - - it("should change defaultPaginationLimit", () => { - update({ defaultPaginationLimit: 50 }); - expect(config.accessToken).toEqual("SWSC40-LJTNO6COUEN7CJMXKLA"); - expect(config.defaultPaginationLimit).toEqual(50); - }); - - it("should change default timeout", () => { - update({ timeout: 50 }); - expect(config.timeout).toEqual(50); - expect(defaultInstance.defaults.timeout).toBe(50); - }); - it("should not change default timeout if it's falsy", () => { - update({ timeout: undefined }); - expect(config.timeout).toBeUndefined(); - }); - it("should cast timeout to number if it's a string type", () => { - update({ timeout: "12345" as any }); - expect(defaultInstance.defaults.timeout).toBe(12345); - }); - it("should set the 0 timeout if casting does not work", () => { - update({ timeout: "-----------" as any }); - expect(defaultInstance.defaults.timeout).toBe(0); - }); - }); - - describe("onConfigChange", () => { - it("should notify, when update method has been called", () => { - const contextToken = faker.string.uuid(); - onConfigChange((configChangedArgs: ConfigChangedArgs) => { - expect(configChangedArgs.config.contextToken).toEqual(contextToken); - }); - update({ contextToken: contextToken }); - }); - - it("should show console warning when no callback methods are connected", () => { - const apiInstance = _createInstance(); - // @ts-expect-error for older axios version - apiInstance.update({ contextToken: "xxx" }, { url: "/some-url" }); - expect(consoleWarnSpy).toBeCalledWith( - '[shopware-6-api] After calling API method /some-url there is no "onConfigChange" listener. See https://shopware-pwa-docs.vuestorefront.io/landing/fundamentals/security.html#context-awareness', - ); - }); - }); - - describe("createInstance", () => { - it("should return config proxy", () => { - const apiInstance = createInstance(); - expect(Object.keys(apiInstance)).toEqual( - expect.arrayContaining([ - "onConfigChange", - "config", - "setup", - "update", - "invoke", - "defaults", - "_axiosInstance", - ]), - ); - }); - }); -}); diff --git a/packages/api-client-old/src/settings.ts b/packages/api-client-old/src/settings.ts deleted file mode 100644 index b63290d8e..000000000 --- a/packages/api-client-old/src/settings.ts +++ /dev/null @@ -1,38 +0,0 @@ -/** - * @public - */ -export type ClientSettings = { - /** - * shopware URL - */ - endpoint?: string; - /** - * id specific for each sales channel - */ - accessToken?: string; - /** - * session id (dynamic) - */ - contextToken?: string; - /** - * default amount of products shown on listings - */ - defaultPaginationLimit?: number; - /** - * timeout limit (ms) - */ - timeout?: number; - /** - * id of current language - */ - languageId?: string; -}; - -export const defaultConfig: ClientSettings = { - endpoint: "https://pwa-demo-api.shopware.com/prev/", - accessToken: "SWSC40-LJTNO6COUEN7CJMXKLA", - contextToken: "", - languageId: "", - defaultPaginationLimit: 10, - timeout: 10000, // ms -}; diff --git a/packages/api-client-old/tsconfig.json b/packages/api-client-old/tsconfig.json deleted file mode 100644 index 2cd12d269..000000000 --- a/packages/api-client-old/tsconfig.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "extends": "tsconfig/base.json", - "include": ["src"], - "exclude": ["dist", "node_modules", "src/**/*.spec.ts", "src/**/*.test.ts"], - "files": ["src/index.ts"], - "compilerOptions": { - "paths": { - "#shopware": ["./types/api-types.ts"] - }, - "skipLibCheck": true - } -} diff --git a/packages/api-client-old/types/api-types.ts b/packages/api-client-old/types/api-types.ts deleted file mode 100644 index 98f0de4ed..000000000 --- a/packages/api-client-old/types/api-types.ts +++ /dev/null @@ -1,19 +0,0 @@ -declare module "#shopware" { - import type { createAPIClient } from "@shopware/api-client"; - - // for default types - export type operations = - import("@shopware/api-client/store-api-types").operations; - // or for locally generated types - // export type operations = import("./api-types/storeApiTypes").operations; - - // for default types - export type Schemas = - import("@shopware/api-client/store-api-types").components["schemas"]; - // or for locally generated types - // export type Schemas = - // import("./api-types/storeApiTypes").components["schemas"]; - - // we're exporting our own Api Client definition as it depends on our own instance - export type ApiClient = ReturnType>; -} diff --git a/packages/api-client-old/vitest.config.ts b/packages/api-client-old/vitest.config.ts deleted file mode 100644 index 98b57d400..000000000 --- a/packages/api-client-old/vitest.config.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { defineConfig } from "vitest/config"; - -export default defineConfig({ - test: { - environment: "happy-dom", - coverage: { - enabled: true, - reportOnFailure: true, - thresholds: { - "100": true, - }, - }, - }, -}); diff --git a/packages/nuxt3-module/README.md b/packages/nuxt3-module/README.md index 664da8620..31d14fc36 100644 --- a/packages/nuxt3-module/README.md +++ b/packages/nuxt3-module/README.md @@ -86,7 +86,7 @@ All composable functions are fully typed with TypeScript and they are registed g ## 📦 Advanced packaging -Internally, the module uses [API Client](https://npmjs.com/package/@shopware-pwa/api-client) and [Composables](https://npmjs.com/package/@shopware-pwa/composables-next) packages, configured together to make everything working well. If you need to check how it's working on a different version of one of them, install a package locally in your project (to be installed and available in project's `package.json` file), then the Nuxt module will use yours. Keep in mind that the different configuration may lead to unexpected behavior. +Internally, the module uses [API Client](https://npmjs.com/package/@shopware/api-client) and [Composables](https://npmjs.com/package/@shopware-pwa/composables-next) packages, configured together to make everything working well. If you need to check how it's working on a different version of one of them, install a package locally in your project (to be installed and available in project's `package.json` file), then the Nuxt module will use yours. Keep in mind that the different configuration may lead to unexpected behavior. ## Links diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 8aad6deb3..ba0f0b311 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -529,7 +529,7 @@ importers: dependencies: "@vueuse/nuxt": specifier: 11.1.0 - version: 11.1.0(magicast@0.3.5)(nuxt@3.13.2(@biomejs/biome@1.9.4)(@opentelemetry/api@1.9.0)(@parcel/watcher@2.4.1)(@types/node@20.17.2)(encoding@0.1.13)(eslint@9.13.0(jiti@1.21.6))(ioredis@5.4.1)(less@4.2.0)(magicast@0.3.5)(optionator@0.9.3)(rollup@4.24.2)(sass@1.77.8)(terser@5.36.0)(typescript@5.6.3)(vite@5.4.10(@types/node@20.17.2)(less@4.2.0)(sass@1.77.8)(terser@5.36.0))(vue-tsc@2.1.6(typescript@5.6.3))(webpack-sources@3.2.3))(rollup@4.24.2)(vue@3.5.12(typescript@5.6.3))(webpack-sources@3.2.3) + version: 11.1.0(magicast@0.3.5)(nuxt@3.13.2(@biomejs/biome@1.9.4)(@opentelemetry/api@1.9.0)(@parcel/watcher@2.4.1)(@types/node@20.17.2)(encoding@0.1.13)(eslint@9.13.0(jiti@1.21.6))(ioredis@5.4.1)(less@4.2.0)(magicast@0.3.5)(optionator@0.9.3)(rollup@4.24.2)(sass@1.77.8)(terser@5.36.0)(typescript@5.6.3)(vite@5.4.10(@types/node@20.17.2)(less@4.2.0)(sass@1.77.8)(terser@5.36.0))(webpack-sources@3.2.3))(rollup@4.24.2)(vue@3.5.12(typescript@5.6.3))(webpack-sources@3.2.3) vue: specifier: 3.5.12 version: 3.5.12(typescript@5.6.3) @@ -885,43 +885,6 @@ importers: specifier: 2.1.3 version: 2.1.3(@edge-runtime/vm@3.2.0)(@types/node@20.17.2)(happy-dom@15.7.4)(jsdom@25.0.1)(less@4.2.0)(sass@1.77.8)(terser@5.36.0) - packages/api-client-old: - dependencies: - "@shopware-pwa/types": - specifier: workspace:* - version: link:../types - axios: - specifier: ^1.7.4 - version: 1.7.4 - query-string: - specifier: 9.1.0 - version: 9.1.0 - devDependencies: - "@faker-js/faker": - specifier: 9.0.3 - version: 9.0.3 - "@shopware/api-client": - specifier: workspace:* - version: link:../api-client - "@vitest/coverage-v8": - specifier: 2.1.3 - version: 2.1.3(vitest@2.1.3(@edge-runtime/vm@3.2.0)(@types/node@20.17.2)(happy-dom@15.7.4)(jsdom@25.0.1)(less@4.2.0)(sass@1.77.8)(terser@5.36.0)) - eslint-config-shopware: - specifier: workspace:* - version: link:../eslint-config-shopware - happy-dom: - specifier: 15.7.4 - version: 15.7.4 - tsconfig: - specifier: workspace:* - version: link:../tsconfig - unbuild: - specifier: 2.0.0 - version: 2.0.0(sass@1.77.8)(typescript@5.6.3) - vitest: - specifier: 2.1.3 - version: 2.1.3(@edge-runtime/vm@3.2.0)(@types/node@20.17.2)(happy-dom@15.7.4)(jsdom@25.0.1)(less@4.2.0)(sass@1.77.8)(terser@5.36.0) - packages/api-gen: dependencies: "@shopware/api-client": @@ -1288,7 +1251,7 @@ importers: version: 2.0.4(vue@3.5.12(typescript@5.6.3)) "@vueuse/nuxt": specifier: 11.1.0 - version: 11.1.0(magicast@0.3.5)(nuxt@3.13.2(@biomejs/biome@1.9.4)(@opentelemetry/api@1.9.0)(@parcel/watcher@2.4.1)(@types/node@20.17.2)(encoding@0.1.13)(eslint@9.13.0(jiti@1.21.6))(ioredis@5.4.1)(less@4.2.0)(magicast@0.3.5)(optionator@0.9.3)(rollup@4.24.2)(sass@1.77.8)(terser@5.36.0)(typescript@5.6.3)(vite@5.4.10(@types/node@20.17.2)(less@4.2.0)(sass@1.77.8)(terser@5.36.0))(vue-tsc@2.1.6(typescript@5.6.3))(webpack-sources@3.2.3))(rollup@4.24.2)(vue@3.5.12(typescript@5.6.3))(webpack-sources@3.2.3) + version: 11.1.0(magicast@0.3.5)(nuxt@3.13.2(@biomejs/biome@1.9.4)(@opentelemetry/api@1.9.0)(@parcel/watcher@2.4.1)(@types/node@20.17.2)(encoding@0.1.13)(eslint@9.13.0(jiti@1.21.6))(ioredis@5.4.1)(less@4.2.0)(magicast@0.3.5)(optionator@0.9.3)(rollup@4.24.2)(sass@1.77.8)(terser@5.36.0)(typescript@5.6.3)(vite@5.4.10(@types/node@20.17.2)(less@4.2.0)(sass@1.77.8)(terser@5.36.0))(webpack-sources@3.2.3))(rollup@4.24.2)(vue@3.5.12(typescript@5.6.3))(webpack-sources@3.2.3) defu: specifier: 6.1.4 version: 6.1.4 @@ -4521,13 +4484,6 @@ packages: } deprecated: Please update to a newer version. - "@faker-js/faker@9.0.3": - resolution: - { - integrity: sha512-lWrrK4QNlFSU+13PL9jMbMKLJYXDFu3tQfayBsMXX7KL/GiQeqfB1CzHkqD5UHBUtPAuPo6XwGbMFNdVMZObRA==, - } - engines: { node: ">=18.0.0", npm: ">=9.0.0" } - "@fal-works/esbuild-plugin-global-externals@2.1.2": resolution: { @@ -12283,13 +12239,6 @@ packages: integrity: sha512-O8x12RzrUF8xyVcY0KJowWsmaJxQbmy0/EtnNtHRpsOcT7dFk5W598coHqBVpmWo1oQQfsCqfCmkZN5DJrZVdg==, } - decode-uri-component@0.4.1: - resolution: - { - integrity: sha512-+8VxcR21HhTy8nOt6jf20w0c9CADrw1O8d+VZ/YzzCt4bJ3uBjw+D1q2osAB8RnpwwaeYBxy0HyKQxD5JBMuuQ==, - } - engines: { node: ">=14.16" } - deep-eql@5.0.2: resolution: { @@ -13885,13 +13834,6 @@ packages: } engines: { node: ">=8" } - filter-obj@5.1.0: - resolution: - { - integrity: sha512-qWeTREPoT7I0bifpPUXtxkZJ1XJzxWtfoWWkdVGqa+eCr3SHW/Ocp89o8vLvbUuQnadybJpjOKu4V+RwO6sGng==, - } - engines: { node: ">=14.16" } - finalhandler@1.3.1: resolution: { @@ -19307,13 +19249,6 @@ packages: } engines: { node: ">=0.6" } - query-string@9.1.0: - resolution: - { - integrity: sha512-t6dqMECpCkqfyv2FfwVS1xcB6lgXW/0XZSaKdsCNGYkqMO76AFiJEg4vINzoDKcZa6MS7JX+OHIjwh06K5vczw==, - } - engines: { node: ">=18" } - querystring@0.2.1: resolution: { @@ -20614,13 +20549,6 @@ packages: } engines: { node: ">=0.10.0" } - split-on-first@3.0.0: - resolution: - { - integrity: sha512-qxQJTx2ryR0Dw0ITYyekNQWpz6f8dGd7vffGNflQQ3Iqj9NJ6qiZ7ELpZsJ/QBhIVAiDfXdag3+Gp8RvWa62AA==, - } - engines: { node: ">=12" } - sprintf-js@1.0.3: resolution: { @@ -26054,8 +25982,6 @@ snapshots: "@faker-js/faker@5.5.3": {} - "@faker-js/faker@9.0.3": {} - "@fal-works/esbuild-plugin-global-externals@2.1.2": {} "@floating-ui/core@1.6.5": @@ -31985,7 +31911,7 @@ snapshots: - vue - webpack-sources - "@vueuse/nuxt@11.1.0(magicast@0.3.5)(nuxt@3.13.2(@biomejs/biome@1.9.4)(@opentelemetry/api@1.9.0)(@parcel/watcher@2.4.1)(@types/node@20.17.2)(encoding@0.1.13)(eslint@9.13.0(jiti@1.21.6))(ioredis@5.4.1)(less@4.2.0)(magicast@0.3.5)(optionator@0.9.3)(rollup@4.24.2)(sass@1.77.8)(terser@5.36.0)(typescript@5.6.3)(vite@5.4.10(@types/node@20.17.2)(less@4.2.0)(sass@1.77.8)(terser@5.36.0))(vue-tsc@2.1.6(typescript@5.6.3))(webpack-sources@3.2.3))(rollup@4.24.2)(vue@3.5.12(typescript@5.6.3))(webpack-sources@3.2.3)": + "@vueuse/nuxt@11.1.0(magicast@0.3.5)(nuxt@3.13.2(@biomejs/biome@1.9.4)(@opentelemetry/api@1.9.0)(@parcel/watcher@2.4.1)(@types/node@20.17.2)(encoding@0.1.13)(eslint@9.13.0(jiti@1.21.6))(ioredis@5.4.1)(less@4.2.0)(magicast@0.3.5)(optionator@0.9.3)(rollup@4.24.2)(sass@1.77.8)(terser@5.36.0)(typescript@5.6.3)(vite@5.4.10(@types/node@20.17.2)(less@4.2.0)(sass@1.77.8)(terser@5.36.0))(webpack-sources@3.2.3))(rollup@4.24.2)(vue@3.5.12(typescript@5.6.3))(webpack-sources@3.2.3)": dependencies: "@nuxt/kit": 3.13.2(magicast@0.3.5)(rollup@4.24.2)(webpack-sources@3.2.3) "@vueuse/core": 11.1.0(patch_hash=rtnblm55jutyponlgwgfoiesem)(vue@3.5.12(typescript@5.6.3)) @@ -33437,8 +33363,6 @@ snapshots: dependencies: character-entities: 2.0.2 - decode-uri-component@0.4.1: {} - deep-eql@5.0.2: {} deep-equal@2.2.3: @@ -34633,8 +34557,6 @@ snapshots: dependencies: to-regex-range: 5.0.1 - filter-obj@5.1.0: {} - finalhandler@1.3.1: dependencies: debug: 4.3.7(supports-color@9.4.0) @@ -38634,12 +38556,6 @@ snapshots: qs@6.9.7: {} - query-string@9.1.0: - dependencies: - decode-uri-component: 0.4.1 - filter-obj: 5.1.0 - split-on-first: 3.0.0 - querystring@0.2.1: {} queue-microtask@1.2.3: {} @@ -39567,8 +39483,6 @@ snapshots: speakingurl@14.0.1: {} - split-on-first@3.0.0: {} - sprintf-js@1.0.3: {} stack-generator@2.0.10: