From 6c2610584de973f90777defc0f5daa94330b5335 Mon Sep 17 00:00:00 2001 From: Catalin Pinte Date: Wed, 5 Oct 2022 09:02:29 +0300 Subject: [PATCH] Update types (#831) * Update product types * Cart types progress, add zod & initial schema validator * Update normalize.ts * Update with-schema-parser.ts * Updated types, schemas & providers * Fix providers after schema parse errors * Fix paths * More provider fixes * Fix kibocommerce & commercejs * Add customer updated types & fixes * Add checkout & customer types * Import core types only from commerce * Update tsconfig.json * Convert hooks interfaces to types * Requested changes * Change to relative paths * Move Zod dependency --- README.md | 15 +- .../src/api/definitions/catalog.ts | 2 +- .../src/api/endpoints/cart/get-cart.ts | 2 +- .../src/api/endpoints/cart/index.ts | 2 +- .../api/endpoints/catalog/products/index.ts | 2 +- .../src/api/endpoints/checkout/index.ts | 2 +- .../customer/get-logged-in-customer.ts | 14 +- .../src/api/endpoints/customer/index.ts | 2 +- .../src/api/endpoints/login/index.ts | 2 +- .../src/api/endpoints/logout/index.ts | 2 +- .../src/api/endpoints/signup/index.ts | 2 +- .../api/endpoints/wishlist/get-wishlist.ts | 3 +- .../src/api/endpoints/wishlist/index.ts | 2 +- .../src/api/endpoints/wishlist/remove-item.ts | 3 +- .../src/api/operations/get-all-pages.ts | 11 +- .../api/operations/get-all-product-paths.ts | 2 +- .../src/api/operations/get-all-products.ts | 2 +- .../api/operations/get-customer-wishlist.ts | 6 +- .../src/api/operations/get-page.ts | 2 +- .../src/api/operations/get-product.ts | 4 +- .../src/api/operations/get-site-info.ts | 6 +- .../bigcommerce/src/api/operations/login.ts | 2 +- .../bigcommerce/src/api/utils/parse-item.ts | 8 +- packages/bigcommerce/src/auth/use-login.tsx | 2 +- packages/bigcommerce/src/auth/use-logout.tsx | 2 +- packages/bigcommerce/src/auth/use-signup.tsx | 4 +- .../bigcommerce/src/cart/use-remove-item.tsx | 10 +- .../bigcommerce/src/customer/use-customer.tsx | 8 +- packages/bigcommerce/src/lib/normalize.ts | 28 +- .../bigcommerce/src/product/use-search.tsx | 2 +- packages/bigcommerce/src/types.ts | 32 ++ packages/bigcommerce/src/types/cart.ts | 66 ---- packages/bigcommerce/src/types/checkout.ts | 1 - packages/bigcommerce/src/types/common.ts | 1 - packages/bigcommerce/src/types/customer.ts | 5 - packages/bigcommerce/src/types/index.ts | 25 -- packages/bigcommerce/src/types/login.ts | 8 - packages/bigcommerce/src/types/logout.ts | 1 - packages/bigcommerce/src/types/page.ts | 11 - packages/bigcommerce/src/types/product.ts | 1 - packages/bigcommerce/src/types/signup.ts | 1 - packages/bigcommerce/src/types/site.ts | 19 -- packages/bigcommerce/src/types/wishlist.ts | 24 -- .../bigcommerce/src/wishlist/use-add-item.tsx | 6 +- .../src/wishlist/use-remove-item.tsx | 4 +- .../bigcommerce/src/wishlist/use-wishlist.tsx | 6 +- packages/commerce/package.json | 3 +- packages/commerce/src/api/endpoints/cart.ts | 100 +++--- .../src/api/endpoints/customer/index.ts | 2 +- packages/commerce/src/api/endpoints/index.ts | 0 packages/commerce/src/api/endpoints/login.ts | 2 +- .../commerce/src/api/endpoints/wishlist.ts | 2 +- packages/commerce/src/api/index.ts | 10 +- packages/commerce/src/api/operations.ts | 7 + packages/commerce/src/api/utils/errors.ts | 25 ++ .../src/api/utils/with-operation-callback.ts | 42 +++ packages/commerce/src/auth/use-login.tsx | 2 +- packages/commerce/src/auth/use-logout.tsx | 2 +- packages/commerce/src/auth/use-signup.tsx | 2 +- packages/commerce/src/cart/use-add-item.tsx | 2 +- packages/commerce/src/cart/use-cart.tsx | 5 +- .../commerce/src/cart/use-remove-item.tsx | 2 +- .../commerce/src/cart/use-update-item.tsx | 2 +- .../commerce/src/checkout/use-checkout.ts | 2 +- .../src/checkout/use-submit-checkout.tsx | 4 +- .../src/customer/address/use-add-item.tsx | 2 +- .../src/customer/address/use-addresses.tsx | 2 +- .../src/customer/address/use-remove-item.tsx | 2 +- .../src/customer/address/use-update-item.tsx | 2 +- .../src/customer/card/use-add-item.tsx | 2 +- .../commerce/src/customer/card/use-cards.tsx | 5 +- .../src/customer/card/use-remove-item.tsx | 2 +- .../src/customer/card/use-update-item.tsx | 2 +- .../commerce/src/customer/use-customer.tsx | 2 +- packages/commerce/src/product/use-search.tsx | 2 +- packages/commerce/src/schemas/page.ts | 18 ++ packages/commerce/src/schemas/product.ts | 60 ++++ packages/commerce/src/schemas/site.ts | 18 ++ packages/commerce/src/types/cart.ts | 297 +++++++++++------- packages/commerce/src/types/checkout.ts | 98 ++++-- packages/commerce/src/types/common.ts | 30 +- .../commerce/src/types/customer/address.ts | 136 ++++---- packages/commerce/src/types/customer/card.ts | 151 +++++---- packages/commerce/src/types/customer/index.ts | 49 ++- packages/commerce/src/types/login.ts | 20 +- packages/commerce/src/types/logout.ts | 14 +- packages/commerce/src/types/page.ts | 47 ++- packages/commerce/src/types/product.ts | 194 +++++++++--- packages/commerce/src/types/signup.ts | 30 +- packages/commerce/src/types/site.ts | 49 ++- packages/commerce/src/types/wishlist.ts | 91 ++++-- .../commerce/src/wishlist/use-add-item.tsx | 2 +- .../commerce/src/wishlist/use-remove-item.tsx | 2 +- .../commerce/src/wishlist/use-wishlist.tsx | 2 +- .../src/api/endpoints/checkout/index.ts | 2 +- .../src/api/endpoints/login/index.ts | 2 +- .../src/api/operations/get-all-pages.ts | 2 +- .../api/operations/get-all-product-paths.ts | 8 +- .../src/api/operations/get-all-products.ts | 2 +- .../commercejs/src/api/operations/get-page.ts | 2 +- .../src/api/operations/get-product.ts | 2 +- .../src/api/operations/get-site-info.ts | 5 +- packages/commercejs/src/cart/use-add-item.tsx | 2 +- packages/commercejs/src/cart/use-cart.tsx | 2 +- .../commercejs/src/cart/use-remove-item.tsx | 6 +- .../commercejs/src/cart/use-update-item.tsx | 12 +- .../src/customer/address/use-add-item.tsx | 30 +- .../src/customer/card/use-add-item.tsx | 30 +- .../commercejs/src/customer/use-customer.tsx | 18 +- .../commercejs/src/product/use-search.tsx | 2 +- packages/commercejs/src/types.ts | 6 + packages/commercejs/src/types/cart.ts | 4 - packages/commercejs/src/types/checkout.ts | 3 - packages/commercejs/src/types/common.ts | 1 - packages/commercejs/src/types/customer.ts | 1 - packages/commercejs/src/types/index.ts | 25 -- packages/commercejs/src/types/login.ts | 9 - packages/commercejs/src/types/logout.ts | 1 - packages/commercejs/src/types/page.ts | 1 - packages/commercejs/src/types/product.ts | 4 - packages/commercejs/src/types/signup.ts | 1 - packages/commercejs/src/types/site.ts | 3 - packages/commercejs/src/types/wishlist.ts | 1 - .../commercejs/src/utils/normalize-cart.ts | 8 +- .../src/utils/normalize-category.ts | 2 +- .../src/utils/normalize-checkout.ts | 2 +- .../commercejs/src/utils/normalize-product.ts | 10 +- .../commercejs/src/wishlist/use-wishlist.tsx | 12 +- .../src/api/endpoints/customer/index.ts | 2 +- .../src/api/endpoints/login/index.ts | 6 +- .../src/api/endpoints/logout/index.ts | 2 +- .../src/api/endpoints/signup/index.ts | 2 +- .../src/api/operations/get-all-pages.ts | 16 +- .../src/api/operations/get-all-products.ts | 9 +- .../api/operations/get-customer-wishlist.ts | 20 +- .../src/api/operations/get-page.ts | 19 +- .../src/api/operations/get-site-info.ts | 17 +- packages/kibocommerce/src/auth/use-login.tsx | 6 +- packages/kibocommerce/src/auth/use-logout.tsx | 30 +- packages/kibocommerce/src/auth/use-signup.tsx | 4 +- .../src/customer/use-customer.tsx | 24 +- packages/kibocommerce/src/lib/normalize.ts | 110 ++++--- packages/kibocommerce/src/types/customer.ts | 27 -- packages/kibocommerce/src/types/login.ts | 8 - packages/kibocommerce/src/types/logout.ts | 1 - packages/kibocommerce/src/types/page.ts | 35 --- packages/kibocommerce/src/types/signup.ts | 1 - .../local/src/api/operations/get-product.ts | 4 +- .../local/src/api/operations/get-site-info.ts | 2 +- packages/local/src/data.json | 11 +- packages/local/src/wishlist/use-wishlist.tsx | 13 +- .../src/api/endpoints/cart/add-item.ts | 4 +- .../src/api/endpoints/cart/index.ts | 2 +- .../api/endpoints/checkout/get-checkout.ts | 2 + .../src/api/endpoints/checkout/index.ts | 2 +- .../api/endpoints/customer/address/index.ts | 2 +- .../src/api/endpoints/customer/card/index.ts | 2 +- packages/ordercloud/src/api/utils/cart.ts | 3 +- .../ordercloud/src/checkout/use-checkout.tsx | 6 +- packages/ordercloud/src/types/cart.ts | 31 -- packages/ordercloud/src/types/checkout.ts | 4 - .../ordercloud/src/types/customer/address.ts | 6 - .../ordercloud/src/types/customer/card.ts | 5 - packages/ordercloud/src/utils/product.ts | 10 +- .../ordercloud/src/wishlist/use-wishlist.tsx | 13 +- .../src/api/operations/get-all-pages.ts | 21 +- .../api/operations/get-all-product-paths.ts | 22 +- .../src/api/operations/get-all-products.ts | 13 +- .../saleor/src/api/operations/get-page.ts | 24 +- .../saleor/src/api/operations/get-product.ts | 6 +- .../src/api/utils/fetch-all-products.ts | 41 --- packages/saleor/src/cart/use-remove-item.tsx | 2 +- packages/saleor/src/cart/use-update-item.tsx | 25 +- packages/saleor/src/product/use-search.tsx | 8 +- packages/saleor/src/types/cart.ts | 32 -- packages/saleor/src/utils/get-categories.ts | 16 +- packages/saleor/src/utils/get-vendors.ts | 2 +- packages/saleor/src/utils/normalize.ts | 49 ++- .../src/utils/queries/collection-one.ts | 6 +- .../queries/get-all-product-vendors-query.ts | 2 +- .../queries/get-all-products-paths-query.ts | 6 +- .../saleor/src/utils/queries/page-many.ts | 2 +- .../saleor/src/utils/queries/product-many.ts | 9 +- .../src/utils/queries/product-one-by-slug.ts | 1 + .../sfcc/src/api/utils/normalise-product.ts | 13 +- .../src/api/endpoints/catalog/products.ts | 1 - .../catalog/products/get-products.ts | 26 ++ .../api/endpoints/catalog/products/index.ts | 19 ++ .../src/api/endpoints/checkout/index.ts | 2 +- packages/shopify/src/api/index.ts | 18 +- .../src/api/operations/get-all-pages.ts | 2 +- .../api/operations/get-all-product-paths.ts | 2 +- .../src/api/operations/get-all-products.ts | 2 +- .../shopify/src/api/operations/get-page.ts | 2 +- .../shopify/src/api/operations/get-product.ts | 2 +- .../src/api/operations/get-site-info.ts | 29 +- packages/shopify/src/api/operations/index.ts | 7 - packages/shopify/src/api/operations/login.ts | 2 +- .../src/api/utils/fetch-graphql-api.ts | 2 +- packages/shopify/src/auth/use-login.tsx | 4 +- packages/shopify/src/auth/use-logout.tsx | 2 +- packages/shopify/src/auth/use-signup.tsx | 4 +- packages/shopify/src/cart/use-add-item.tsx | 2 +- packages/shopify/src/cart/use-cart.tsx | 7 +- packages/shopify/src/cart/use-remove-item.tsx | 6 +- packages/shopify/src/cart/use-update-item.tsx | 15 +- .../shopify/src/customer/use-customer.tsx | 30 +- packages/shopify/src/product/use-search.tsx | 2 +- packages/shopify/src/types/cart.ts | 32 -- packages/shopify/src/types/checkout.ts | 1 - packages/shopify/src/types/common.ts | 1 - packages/shopify/src/types/customer.ts | 5 - packages/shopify/src/types/index.ts | 25 -- packages/shopify/src/types/login.ts | 8 - packages/shopify/src/types/logout.ts | 1 - packages/shopify/src/types/page.ts | 11 - packages/shopify/src/types/product.ts | 1 - packages/shopify/src/types/signup.ts | 1 - packages/shopify/src/types/site.ts | 1 - packages/shopify/src/types/wishlist.ts | 1 - .../shopify/src/utils/checkout-to-cart.ts | 2 +- packages/shopify/src/utils/get-brands.ts | 23 +- packages/shopify/src/utils/get-categories.ts | 6 +- .../shopify/src/utils/get-search-variables.ts | 2 +- packages/shopify/src/utils/normalize.ts | 16 +- .../spree/src/api/operations/get-site-info.ts | 11 +- packages/spree/src/types/index.ts | 44 +-- packages/spree/src/utils/get-media-gallery.ts | 4 +- .../utils/normalizations/normalize-cart.ts | 1 - .../utils/normalizations/normalize-page.ts | 2 +- .../utils/normalizations/normalize-product.ts | 5 +- .../utils/normalizations/normalize-user.ts | 7 +- .../normalizations/normalize-wishlist.ts | 73 ++--- packages/spree/src/wishlist/use-add-item.tsx | 9 +- .../spree/src/wishlist/use-remove-item.tsx | 6 +- packages/spree/src/wishlist/use-wishlist.tsx | 5 +- .../swell/src/api/operations/get-all-pages.ts | 15 +- packages/swell/src/api/operations/get-page.ts | 9 +- .../swell/src/api/operations/get-site-info.ts | 6 +- packages/swell/src/api/operations/login.ts | 2 +- packages/swell/src/auth/use-login.tsx | 13 +- packages/swell/src/auth/use-logout.tsx | 5 +- packages/swell/src/auth/use-signup.tsx | 7 +- packages/swell/src/cart/use-add-item.tsx | 5 +- packages/swell/src/cart/use-update-item.tsx | 14 +- .../swell/src/cart/utils/checkout-to-cart.ts | 2 +- packages/swell/src/customer/use-customer.tsx | 7 +- packages/swell/src/product/use-search.tsx | 7 +- packages/swell/src/types.ts | 18 +- packages/swell/src/types/login.ts | 10 - packages/swell/src/utils/get-categories.ts | 2 +- packages/swell/src/utils/get-vendors.ts | 20 +- packages/swell/src/utils/normalize.ts | 20 +- packages/swell/src/wishlist/use-wishlist.tsx | 13 +- .../vendure/src/api/operations/get-product.ts | 1 + .../src/api/operations/get-site-info.ts | 4 +- packages/vendure/src/api/operations/login.ts | 2 +- .../src/api/utils/fetch-graphql-api.ts | 2 + packages/vendure/src/auth/use-login.tsx | 6 +- packages/vendure/src/auth/use-logout.tsx | 8 +- packages/vendure/src/auth/use-signup.tsx | 10 +- packages/vendure/src/cart/use-add-item.tsx | 4 +- packages/vendure/src/cart/use-cart.tsx | 4 +- packages/vendure/src/cart/use-remove-item.tsx | 11 +- packages/vendure/src/cart/use-update-item.tsx | 3 +- .../vendure/src/customer/use-customer.tsx | 2 +- packages/vendure/src/fetcher.ts | 2 +- packages/vendure/src/product/use-search.tsx | 2 +- packages/vendure/src/types/cart.ts | 1 - packages/vendure/src/types/checkout.ts | 1 - packages/vendure/src/types/common.ts | 1 - packages/vendure/src/types/customer.ts | 1 - packages/vendure/src/types/index.ts | 25 -- packages/vendure/src/types/login.ts | 12 - packages/vendure/src/types/logout.ts | 1 - packages/vendure/src/types/page.ts | 1 - packages/vendure/src/types/product.ts | 1 - packages/vendure/src/types/signup.ts | 1 - packages/vendure/src/types/site.ts | 1 - packages/vendure/src/types/wishlist.ts | 1 - packages/vendure/src/utils/normalize.ts | 4 +- .../vendure/src/wishlist/use-wishlist.tsx | 15 +- pnpm-lock.yaml | 12 +- site/components/cart/CartItem/CartItem.tsx | 2 +- .../HomeAllProductsGrid.tsx | 15 +- site/components/search.tsx | 28 +- .../WishlistButton/WishlistButton.tsx | 4 +- .../wishlist/WishlistCard/WishlistCard.tsx | 4 +- site/lib/search.tsx | 4 +- site/pages/product/[slug].tsx | 1 + site/pages/wishlist.tsx | 2 +- 291 files changed, 1972 insertions(+), 1788 deletions(-) create mode 100644 packages/bigcommerce/src/types.ts delete mode 100644 packages/bigcommerce/src/types/cart.ts delete mode 100644 packages/bigcommerce/src/types/checkout.ts delete mode 100644 packages/bigcommerce/src/types/common.ts delete mode 100644 packages/bigcommerce/src/types/customer.ts delete mode 100644 packages/bigcommerce/src/types/index.ts delete mode 100644 packages/bigcommerce/src/types/login.ts delete mode 100644 packages/bigcommerce/src/types/logout.ts delete mode 100644 packages/bigcommerce/src/types/page.ts delete mode 100644 packages/bigcommerce/src/types/product.ts delete mode 100644 packages/bigcommerce/src/types/signup.ts delete mode 100644 packages/bigcommerce/src/types/site.ts delete mode 100644 packages/bigcommerce/src/types/wishlist.ts create mode 100644 packages/commerce/src/api/endpoints/index.ts create mode 100644 packages/commerce/src/api/utils/with-operation-callback.ts create mode 100644 packages/commerce/src/schemas/page.ts create mode 100644 packages/commerce/src/schemas/product.ts create mode 100644 packages/commerce/src/schemas/site.ts create mode 100644 packages/commercejs/src/types.ts delete mode 100644 packages/commercejs/src/types/cart.ts delete mode 100644 packages/commercejs/src/types/checkout.ts delete mode 100644 packages/commercejs/src/types/common.ts delete mode 100644 packages/commercejs/src/types/customer.ts delete mode 100644 packages/commercejs/src/types/index.ts delete mode 100644 packages/commercejs/src/types/login.ts delete mode 100644 packages/commercejs/src/types/logout.ts delete mode 100644 packages/commercejs/src/types/page.ts delete mode 100644 packages/commercejs/src/types/product.ts delete mode 100644 packages/commercejs/src/types/signup.ts delete mode 100644 packages/commercejs/src/types/site.ts delete mode 100644 packages/commercejs/src/types/wishlist.ts delete mode 100644 packages/kibocommerce/src/types/customer.ts delete mode 100644 packages/kibocommerce/src/types/login.ts delete mode 100644 packages/kibocommerce/src/types/logout.ts delete mode 100644 packages/kibocommerce/src/types/page.ts delete mode 100644 packages/kibocommerce/src/types/signup.ts delete mode 100644 packages/ordercloud/src/types/checkout.ts delete mode 100644 packages/saleor/src/api/utils/fetch-all-products.ts delete mode 100644 packages/saleor/src/types/cart.ts delete mode 100644 packages/shopify/src/api/endpoints/catalog/products.ts create mode 100644 packages/shopify/src/api/endpoints/catalog/products/get-products.ts create mode 100644 packages/shopify/src/api/endpoints/catalog/products/index.ts delete mode 100644 packages/shopify/src/api/operations/index.ts delete mode 100644 packages/shopify/src/types/cart.ts delete mode 100644 packages/shopify/src/types/checkout.ts delete mode 100644 packages/shopify/src/types/common.ts delete mode 100644 packages/shopify/src/types/customer.ts delete mode 100644 packages/shopify/src/types/index.ts delete mode 100644 packages/shopify/src/types/login.ts delete mode 100644 packages/shopify/src/types/logout.ts delete mode 100644 packages/shopify/src/types/page.ts delete mode 100644 packages/shopify/src/types/product.ts delete mode 100644 packages/shopify/src/types/signup.ts delete mode 100644 packages/shopify/src/types/site.ts delete mode 100644 packages/shopify/src/types/wishlist.ts delete mode 100644 packages/vendure/src/types/cart.ts delete mode 100644 packages/vendure/src/types/checkout.ts delete mode 100644 packages/vendure/src/types/common.ts delete mode 100644 packages/vendure/src/types/customer.ts delete mode 100644 packages/vendure/src/types/index.ts delete mode 100644 packages/vendure/src/types/login.ts delete mode 100644 packages/vendure/src/types/logout.ts delete mode 100644 packages/vendure/src/types/page.ts delete mode 100644 packages/vendure/src/types/product.ts delete mode 100644 packages/vendure/src/types/signup.ts delete mode 100644 packages/vendure/src/types/site.ts delete mode 100644 packages/vendure/src/types/wishlist.ts diff --git a/README.md b/README.md index 0d81bf1321..0b752d8c6b 100644 --- a/README.md +++ b/README.md @@ -23,8 +23,8 @@ Demo live at: [demo.vercel.store](https://demo.vercel.store/) > To run a minimal version of Next.js Commerce you can start with the default local provider `@vercel/commerce-local` that has disabled all features (cart, auth) and use static files for the backend ```bash -pnpm install # run this command in root folder of the mono repo -pnpm dev +pnpm install & pnpm build # run this commands in root folder of the mono repo +pnpm dev # run this commands in the site folder ``` > If you encounter any problems while installing and running for the first time, please see the Troubleshoot section @@ -111,10 +111,11 @@ Our commitment to Open Source can be found [here](https://vercel.com/oss). 1. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local device. 2. Create a new branch `git checkout -b MY_BRANCH_NAME` 3. Install the dependencies: `pnpm install` -4. Duplicate `site/.env.template` and rename it to `site/.env.local` -5. Add proper store values to `site/.env.local` -6. Run `pnpm dev` to build the packages and watch for code changes -7. Run `pnpm turbo run build` to check the build after your changes +4. Build the packages: `pnpm build` +5. Duplicate `site/.env.template` and rename it to `site/.env.local` +6. Add proper store values to `site/.env.local` +7. Run `cd site` & `pnpm dev` to watch for code changes +8. Run `pnpm turbo run build` to check the build after your changes ## Work in progress @@ -191,7 +192,7 @@ info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this comm The error usually occurs when running `pnpm dev` inside of the `/site/` folder after installing a fresh repository. -In order to fix this, run `pnpm dev` in the monorepo root folder first. +In order to fix this, run `pnpm build` in the monorepo root folder first. > Using `pnpm dev` from the root is recommended for developing, which will run watch mode on all packages. diff --git a/packages/bigcommerce/src/api/definitions/catalog.ts b/packages/bigcommerce/src/api/definitions/catalog.ts index 2c483f7818..d24d5963b5 100644 --- a/packages/bigcommerce/src/api/definitions/catalog.ts +++ b/packages/bigcommerce/src/api/definitions/catalog.ts @@ -1130,7 +1130,7 @@ export interface definitions { */ search_keywords?: string /** - * Image URL used for this category on the storefront. Images can be uploaded via form file post to `/brands/{brandId}/image`, or by providing a publicly accessible URL in this field. + * Image URL used for this category on the storefront. Images can be uploaded via form file post to `/{brandId}/image`, or by providing a publicly accessible URL in this field. */ image_url?: string custom_url?: definitions['customUrl_Full'] diff --git a/packages/bigcommerce/src/api/endpoints/cart/get-cart.ts b/packages/bigcommerce/src/api/endpoints/cart/get-cart.ts index cce0b2fcac..5b48119ca5 100644 --- a/packages/bigcommerce/src/api/endpoints/cart/get-cart.ts +++ b/packages/bigcommerce/src/api/endpoints/cart/get-cart.ts @@ -2,7 +2,7 @@ import { normalizeCart } from '../../../lib/normalize' import { BigcommerceApiError } from '../../utils/errors' import getCartCookie from '../../utils/get-cart-cookie' -import type { BigcommerceCart } from '../../../types/cart' +import type { BigcommerceCart } from '../../../types' import type { CartEndpoint } from '.' // Return current cart info diff --git a/packages/bigcommerce/src/api/endpoints/cart/index.ts b/packages/bigcommerce/src/api/endpoints/cart/index.ts index 3766511786..92601e1890 100644 --- a/packages/bigcommerce/src/api/endpoints/cart/index.ts +++ b/packages/bigcommerce/src/api/endpoints/cart/index.ts @@ -1,6 +1,6 @@ import { GetAPISchema, createEndpoint } from '@vercel/commerce/api' import cartEndpoint from '@vercel/commerce/api/endpoints/cart' -import type { CartSchema } from '../../../types/cart' +import type { CartSchema } from '@vercel/commerce/types/cart' import type { BigcommerceAPI } from '../..' import getCart from './get-cart' import addItem from './add-item' diff --git a/packages/bigcommerce/src/api/endpoints/catalog/products/index.ts b/packages/bigcommerce/src/api/endpoints/catalog/products/index.ts index 24472434d9..8de51fd939 100644 --- a/packages/bigcommerce/src/api/endpoints/catalog/products/index.ts +++ b/packages/bigcommerce/src/api/endpoints/catalog/products/index.ts @@ -1,6 +1,6 @@ import { GetAPISchema, createEndpoint } from '@vercel/commerce/api' import productsEndpoint from '@vercel/commerce/api/endpoints/catalog/products' -import type { ProductsSchema } from '../../../../types/product' +import type { ProductsSchema } from '@vercel/commerce/types/product' import type { BigcommerceAPI } from '../../..' import getProducts from './get-products' diff --git a/packages/bigcommerce/src/api/endpoints/checkout/index.ts b/packages/bigcommerce/src/api/endpoints/checkout/index.ts index 83bc4ae084..908ba0fd73 100644 --- a/packages/bigcommerce/src/api/endpoints/checkout/index.ts +++ b/packages/bigcommerce/src/api/endpoints/checkout/index.ts @@ -1,6 +1,6 @@ import { GetAPISchema, createEndpoint } from '@vercel/commerce/api' import checkoutEndpoint from '@vercel/commerce/api/endpoints/checkout' -import type { CheckoutSchema } from '../../../types/checkout' +import type { CheckoutSchema } from '@vercel/commerce/types/checkout' import type { BigcommerceAPI } from '../..' import getCheckout from './get-checkout' diff --git a/packages/bigcommerce/src/api/endpoints/customer/get-logged-in-customer.ts b/packages/bigcommerce/src/api/endpoints/customer/get-logged-in-customer.ts index 4c93730f69..e517072ae0 100644 --- a/packages/bigcommerce/src/api/endpoints/customer/get-logged-in-customer.ts +++ b/packages/bigcommerce/src/api/endpoints/customer/get-logged-in-customer.ts @@ -47,7 +47,19 @@ const getLoggedInCustomer: CustomerEndpoint['handlers']['getLoggedInCustomer'] = }) } - return res.status(200).json({ data: { customer } }) + return res.status(200).json({ + data: { + customer: { + id: String(customer.entityId), + firstName: customer.firstName, + lastName: customer.lastName, + email: customer.email, + company: customer.company, + phone: customer.phone, + notes: customer.notes, + }, + }, + }) } res.status(200).json({ data: null }) diff --git a/packages/bigcommerce/src/api/endpoints/customer/index.ts b/packages/bigcommerce/src/api/endpoints/customer/index.ts index 5efff392c6..c719bc38fd 100644 --- a/packages/bigcommerce/src/api/endpoints/customer/index.ts +++ b/packages/bigcommerce/src/api/endpoints/customer/index.ts @@ -1,6 +1,6 @@ import { GetAPISchema, createEndpoint } from '@vercel/commerce/api' import customerEndpoint from '@vercel/commerce/api/endpoints/customer' -import type { CustomerSchema } from '../../../types/customer' +import type { CustomerSchema } from '@vercel/commerce/types/customer' import type { BigcommerceAPI } from '../..' import getLoggedInCustomer from './get-logged-in-customer' diff --git a/packages/bigcommerce/src/api/endpoints/login/index.ts b/packages/bigcommerce/src/api/endpoints/login/index.ts index 1ad6f71028..0a4331b338 100644 --- a/packages/bigcommerce/src/api/endpoints/login/index.ts +++ b/packages/bigcommerce/src/api/endpoints/login/index.ts @@ -1,6 +1,6 @@ import { GetAPISchema, createEndpoint } from '@vercel/commerce/api' import loginEndpoint from '@vercel/commerce/api/endpoints/login' -import type { LoginSchema } from '../../../types/login' +import type { LoginSchema } from '@vercel/commerce/types/login' import type { BigcommerceAPI } from '../..' import login from './login' diff --git a/packages/bigcommerce/src/api/endpoints/logout/index.ts b/packages/bigcommerce/src/api/endpoints/logout/index.ts index 94a246f4b0..01893c3d46 100644 --- a/packages/bigcommerce/src/api/endpoints/logout/index.ts +++ b/packages/bigcommerce/src/api/endpoints/logout/index.ts @@ -1,6 +1,6 @@ import { GetAPISchema, createEndpoint } from '@vercel/commerce/api' import logoutEndpoint from '@vercel/commerce/api/endpoints/logout' -import type { LogoutSchema } from '../../../types/logout' +import type { LogoutSchema } from '@vercel/commerce/types/logout' import type { BigcommerceAPI } from '../..' import logout from './logout' diff --git a/packages/bigcommerce/src/api/endpoints/signup/index.ts b/packages/bigcommerce/src/api/endpoints/signup/index.ts index 64521f9646..3517826aa6 100644 --- a/packages/bigcommerce/src/api/endpoints/signup/index.ts +++ b/packages/bigcommerce/src/api/endpoints/signup/index.ts @@ -1,6 +1,6 @@ import { GetAPISchema, createEndpoint } from '@vercel/commerce/api' import signupEndpoint from '@vercel/commerce/api/endpoints/signup' -import type { SignupSchema } from '../../../types/signup' +import type { SignupSchema } from '@vercel/commerce/types/signup' import type { BigcommerceAPI } from '../..' import signup from './signup' diff --git a/packages/bigcommerce/src/api/endpoints/wishlist/get-wishlist.ts b/packages/bigcommerce/src/api/endpoints/wishlist/get-wishlist.ts index 479a67c6e8..82f4681956 100644 --- a/packages/bigcommerce/src/api/endpoints/wishlist/get-wishlist.ts +++ b/packages/bigcommerce/src/api/endpoints/wishlist/get-wishlist.ts @@ -1,7 +1,6 @@ -import type { Wishlist } from '../../../types/wishlist' +import type { Wishlist } from '@vercel/commerce/types/wishlist' import type { WishlistEndpoint } from '.' import getCustomerId from '../../utils/get-customer-id' -import getCustomerWishlist from '../../operations/get-customer-wishlist' // Return wishlist info const getWishlist: WishlistEndpoint['handlers']['getWishlist'] = async ({ diff --git a/packages/bigcommerce/src/api/endpoints/wishlist/index.ts b/packages/bigcommerce/src/api/endpoints/wishlist/index.ts index 87728225da..1a337006d7 100644 --- a/packages/bigcommerce/src/api/endpoints/wishlist/index.ts +++ b/packages/bigcommerce/src/api/endpoints/wishlist/index.ts @@ -1,6 +1,6 @@ import { GetAPISchema, createEndpoint } from '@vercel/commerce/api' import wishlistEndpoint from '@vercel/commerce/api/endpoints/wishlist' -import type { WishlistSchema } from '../../../types/wishlist' +import type { WishlistSchema } from '@vercel/commerce/types/wishlist' import type { BigcommerceAPI } from '../..' import getWishlist from './get-wishlist' import addItem from './add-item' diff --git a/packages/bigcommerce/src/api/endpoints/wishlist/remove-item.ts b/packages/bigcommerce/src/api/endpoints/wishlist/remove-item.ts index 9b19d9b42d..17b3f6decb 100644 --- a/packages/bigcommerce/src/api/endpoints/wishlist/remove-item.ts +++ b/packages/bigcommerce/src/api/endpoints/wishlist/remove-item.ts @@ -1,5 +1,4 @@ -import type { Wishlist } from '../../../types/wishlist' -import getCustomerWishlist from '../../operations/get-customer-wishlist' +import type { Wishlist } from '@vercel/commerce/types/wishlist' import getCustomerId from '../../utils/get-customer-id' import type { WishlistEndpoint } from '.' diff --git a/packages/bigcommerce/src/api/operations/get-all-pages.ts b/packages/bigcommerce/src/api/operations/get-all-pages.ts index 3117b73fc5..97575d5b79 100644 --- a/packages/bigcommerce/src/api/operations/get-all-pages.ts +++ b/packages/bigcommerce/src/api/operations/get-all-pages.ts @@ -2,10 +2,13 @@ import type { OperationContext, OperationOptions, } from '@vercel/commerce/api/operations' -import type { Page, GetAllPagesOperation } from '../../types/page' +import type { GetAllPagesOperation } from '@vercel/commerce/types/page' import type { RecursivePartial, RecursiveRequired } from '../utils/types' import { BigcommerceConfig, Provider } from '..' +import { definitions } from '../definitions/store-content' +import { normalizePage } from '../../lib/normalize' + export default function getAllPagesOperation({ commerce, }: OperationContext) { @@ -33,12 +36,14 @@ export default function getAllPagesOperation({ // RecursivePartial forces the method to check for every prop in the data, which is // required in case there's a custom `url` const { data } = await cfg.storeApiFetch< - RecursivePartial<{ data: Page[] }> + RecursivePartial<{ data: definitions['page_Full'][] }> >('/v3/content/pages') const pages = (data as RecursiveRequired) ?? [] return { - pages: preview ? pages : pages.filter((p) => p.is_visible), + pages: preview + ? pages.map(normalizePage) + : pages.filter((p) => p.is_visible).map(normalizePage), } } diff --git a/packages/bigcommerce/src/api/operations/get-all-product-paths.ts b/packages/bigcommerce/src/api/operations/get-all-product-paths.ts index 90cdab6fd2..6c56ea6923 100644 --- a/packages/bigcommerce/src/api/operations/get-all-product-paths.ts +++ b/packages/bigcommerce/src/api/operations/get-all-product-paths.ts @@ -3,7 +3,7 @@ import type { OperationOptions, } from '@vercel/commerce/api/operations' import type { GetAllProductPathsQuery } from '../../../schema' -import type { GetAllProductPathsOperation } from '../../types/product' +import type { GetAllProductPathsOperation } from '@vercel/commerce/types/product' import type { RecursivePartial, RecursiveRequired } from '../utils/types' import filterEdges from '../utils/filter-edges' import { BigcommerceConfig, Provider } from '..' diff --git a/packages/bigcommerce/src/api/operations/get-all-products.ts b/packages/bigcommerce/src/api/operations/get-all-products.ts index 2833ffcd73..4ec3baba44 100644 --- a/packages/bigcommerce/src/api/operations/get-all-products.ts +++ b/packages/bigcommerce/src/api/operations/get-all-products.ts @@ -6,7 +6,7 @@ import type { GetAllProductsQuery, GetAllProductsQueryVariables, } from '../../../schema' -import type { GetAllProductsOperation } from '../../types/product' +import type { GetAllProductsOperation } from '@vercel/commerce/types/product' import type { RecursivePartial, RecursiveRequired } from '../utils/types' import filterEdges from '../utils/filter-edges' import setProductLocaleMeta from '../utils/set-product-locale-meta' diff --git a/packages/bigcommerce/src/api/operations/get-customer-wishlist.ts b/packages/bigcommerce/src/api/operations/get-customer-wishlist.ts index 25e2157e1f..cdfd05acf7 100644 --- a/packages/bigcommerce/src/api/operations/get-customer-wishlist.ts +++ b/packages/bigcommerce/src/api/operations/get-customer-wishlist.ts @@ -5,7 +5,7 @@ import type { import type { GetCustomerWishlistOperation, Wishlist, -} from '../../types/wishlist' +} from '@vercel/commerce/types/wishlist' import type { RecursivePartial, RecursiveRequired } from '../utils/types' import { BigcommerceConfig, Provider } from '..' import getAllProducts, { ProductEdge } from './get-all-products' @@ -49,7 +49,7 @@ export default function getCustomerWishlistOperation({ if (includeProducts && wishlist?.items?.length) { const ids = wishlist.items - ?.map((item) => (item?.product_id ? String(item?.product_id) : null)) + ?.map((item) => (item?.productId ? String(item?.productId) : null)) .filter((id): id is string => !!id) if (ids?.length) { @@ -66,7 +66,7 @@ export default function getCustomerWishlistOperation({ }, {}) // Populate the wishlist items with the graphql products wishlist.items.forEach((item) => { - const product = item && productsById[item.product_id!] + const product = item && productsById[Number(item.productId)] if (item && product) { // @ts-ignore Fix this type when the wishlist type is properly defined item.product = product diff --git a/packages/bigcommerce/src/api/operations/get-page.ts b/packages/bigcommerce/src/api/operations/get-page.ts index dc38e50887..4a72c5a29d 100644 --- a/packages/bigcommerce/src/api/operations/get-page.ts +++ b/packages/bigcommerce/src/api/operations/get-page.ts @@ -2,7 +2,7 @@ import type { OperationContext, OperationOptions, } from '@vercel/commerce/api/operations' -import type { GetPageOperation, Page } from '../../types/page' +import type { GetPageOperation, Page } from '@vercel/commerce/types/page' import type { RecursivePartial, RecursiveRequired } from '../utils/types' import type { BigcommerceConfig, Provider } from '..' import { normalizePage } from '../../lib/normalize' diff --git a/packages/bigcommerce/src/api/operations/get-product.ts b/packages/bigcommerce/src/api/operations/get-product.ts index c7457de2ac..534d173c78 100644 --- a/packages/bigcommerce/src/api/operations/get-product.ts +++ b/packages/bigcommerce/src/api/operations/get-product.ts @@ -2,7 +2,7 @@ import type { OperationContext, OperationOptions, } from '@vercel/commerce/api/operations' -import type { GetProductOperation } from '../../types/product' +import type { GetProductOperation } from '@vercel/commerce/types/product' import type { GetProductQuery, GetProductQueryVariables } from '../../../schema' import setProductLocaleMeta from '../utils/set-product-locale-meta' import { productInfoFragment } from '../fragments/product' @@ -100,7 +100,7 @@ export default function getAllProductPathsOperation({ const variables: GetProductQueryVariables = { locale, hasLocale: !!locale, - path: slug ? `/${slug}/` : vars.path!, + path: slug ? `/${slug}` : vars.path!, } const { data } = await config.fetch(query, { variables }) const product = data.site?.route?.node diff --git a/packages/bigcommerce/src/api/operations/get-site-info.ts b/packages/bigcommerce/src/api/operations/get-site-info.ts index ad0dd5ebd1..d7bc703556 100644 --- a/packages/bigcommerce/src/api/operations/get-site-info.ts +++ b/packages/bigcommerce/src/api/operations/get-site-info.ts @@ -2,12 +2,12 @@ import type { OperationContext, OperationOptions, } from '@vercel/commerce/api/operations' -import type { GetSiteInfoOperation } from '../../types/site' +import type { GetSiteInfoOperation } from '@vercel/commerce/types/site' import type { GetSiteInfoQuery } from '../../../schema' import filterEdges from '../utils/filter-edges' import type { BigcommerceConfig, Provider } from '..' import { categoryTreeItemFragment } from '../fragments/category-tree' -import { normalizeCategory } from '../../lib/normalize' +import { normalizeBrand, normalizeCategory } from '../../lib/normalize' // Get 3 levels of categories export const getSiteInfoQuery = /* GraphQL */ ` @@ -79,7 +79,7 @@ export default function getSiteInfoOperation({ return { categories: categories ?? [], - brands: filterEdges(brands), + brands: filterEdges(brands).map(normalizeBrand), } } diff --git a/packages/bigcommerce/src/api/operations/login.ts b/packages/bigcommerce/src/api/operations/login.ts index f5349998f2..4a33741f89 100644 --- a/packages/bigcommerce/src/api/operations/login.ts +++ b/packages/bigcommerce/src/api/operations/login.ts @@ -3,7 +3,7 @@ import type { OperationContext, OperationOptions, } from '@vercel/commerce/api/operations' -import type { LoginOperation } from '../../types/login' +import type { LoginOperation } from '@vercel/commerce/types/login' import type { LoginMutation } from '../../../schema' import type { RecursivePartial } from '../utils/types' import concatHeader from '../utils/concat-cookie' diff --git a/packages/bigcommerce/src/api/utils/parse-item.ts b/packages/bigcommerce/src/api/utils/parse-item.ts index bb59a6ec47..324d13a853 100644 --- a/packages/bigcommerce/src/api/utils/parse-item.ts +++ b/packages/bigcommerce/src/api/utils/parse-item.ts @@ -1,5 +1,5 @@ -import type { WishlistItemBody } from '../../types/wishlist' -import type { CartItemBody, OptionSelections } from '../../types/cart' +import type { WishlistItemBody } from '@vercel/commerce/types/wishlist' +import type { CartItemBody, SelectedOption } from '@vercel/commerce/types/cart' type BCWishlistItemBody = { product_id: number @@ -10,7 +10,7 @@ type BCCartItemBody = { product_id: number variant_id: number quantity?: number - option_selections?: OptionSelections[] + option_selections?: SelectedOption[] } export const parseWishlistItem = ( @@ -24,5 +24,5 @@ export const parseCartItem = (item: CartItemBody): BCCartItemBody => ({ quantity: item.quantity, product_id: Number(item.productId), variant_id: Number(item.variantId), - option_selections: item.optionSelections, + option_selections: item.optionsSelected, }) diff --git a/packages/bigcommerce/src/auth/use-login.tsx b/packages/bigcommerce/src/auth/use-login.tsx index a71f15983e..103c4ccbf0 100644 --- a/packages/bigcommerce/src/auth/use-login.tsx +++ b/packages/bigcommerce/src/auth/use-login.tsx @@ -2,7 +2,7 @@ import { useCallback } from 'react' import type { MutationHook } from '@vercel/commerce/utils/types' import { CommerceError } from '@vercel/commerce/utils/errors' import useLogin, { UseLogin } from '@vercel/commerce/auth/use-login' -import type { LoginHook } from '../types/login' +import type { LoginHook } from '@vercel/commerce/types/login' import useCustomer from '../customer/use-customer' export default useLogin as UseLogin diff --git a/packages/bigcommerce/src/auth/use-logout.tsx b/packages/bigcommerce/src/auth/use-logout.tsx index bc5c3a4c03..ff707abf1c 100644 --- a/packages/bigcommerce/src/auth/use-logout.tsx +++ b/packages/bigcommerce/src/auth/use-logout.tsx @@ -1,7 +1,7 @@ import { useCallback } from 'react' import type { MutationHook } from '@vercel/commerce/utils/types' import useLogout, { UseLogout } from '@vercel/commerce/auth/use-logout' -import type { LogoutHook } from '../types/logout' +import type { LogoutHook } from '@vercel/commerce/types/logout' import useCustomer from '../customer/use-customer' export default useLogout as UseLogout diff --git a/packages/bigcommerce/src/auth/use-signup.tsx b/packages/bigcommerce/src/auth/use-signup.tsx index b06126df65..893b2beb28 100644 --- a/packages/bigcommerce/src/auth/use-signup.tsx +++ b/packages/bigcommerce/src/auth/use-signup.tsx @@ -1,8 +1,8 @@ import { useCallback } from 'react' import type { MutationHook } from '@vercel/commerce/utils/types' import { CommerceError } from '@vercel/commerce/utils/errors' -import useSignup, { UseSignup } from '@vercel/commerce/auth/use-signup' -import type { SignupHook } from '../types/signup' +import useSignup, { type UseSignup } from '@vercel/commerce/auth/use-signup' +import type { SignupHook } from '@vercel/commerce/types/signup' import useCustomer from '../customer/use-customer' export default useSignup as UseSignup diff --git a/packages/bigcommerce/src/cart/use-remove-item.tsx b/packages/bigcommerce/src/cart/use-remove-item.tsx index 8bea34f414..bed12c96be 100644 --- a/packages/bigcommerce/src/cart/use-remove-item.tsx +++ b/packages/bigcommerce/src/cart/use-remove-item.tsx @@ -4,8 +4,14 @@ import type { HookFetcherContext, } from '@vercel/commerce/utils/types' import { ValidationError } from '@vercel/commerce/utils/errors' -import useRemoveItem, { UseRemoveItem } from '@vercel/commerce/cart/use-remove-item' -import type { Cart, LineItem, RemoveItemHook } from '@vercel/commerce/types/cart' +import useRemoveItem, { + UseRemoveItem, +} from '@vercel/commerce/cart/use-remove-item' +import type { + Cart, + LineItem, + RemoveItemHook, +} from '@vercel/commerce/types/cart' import useCart from './use-cart' export type RemoveItemFn = T extends LineItem diff --git a/packages/bigcommerce/src/customer/use-customer.tsx b/packages/bigcommerce/src/customer/use-customer.tsx index 36bf886179..e6b8f4968c 100644 --- a/packages/bigcommerce/src/customer/use-customer.tsx +++ b/packages/bigcommerce/src/customer/use-customer.tsx @@ -1,6 +1,8 @@ -import { SWRHook } from '@vercel/commerce/utils/types' -import useCustomer, { UseCustomer } from '@vercel/commerce/customer/use-customer' -import type { CustomerHook } from '../types/customer' +import type { SWRHook } from '@vercel/commerce/utils/types' +import useCustomer, { + type UseCustomer, +} from '@vercel/commerce/customer/use-customer' +import type { CustomerHook } from '@vercel/commerce/types/customer' export default useCustomer as UseCustomer diff --git a/packages/bigcommerce/src/lib/normalize.ts b/packages/bigcommerce/src/lib/normalize.ts index 059e3f8713..1cf20b1366 100644 --- a/packages/bigcommerce/src/lib/normalize.ts +++ b/packages/bigcommerce/src/lib/normalize.ts @@ -1,7 +1,9 @@ -import type { Product } from '../types/product' -import type { Cart, BigcommerceCart, LineItem } from '../types/cart' -import type { Page } from '../types/page' -import type { BCCategory, Category } from '../types/site' +import type { Page } from '@vercel/commerce/types/page' +import type { Product } from '@vercel/commerce/types/product' +import type { Cart, LineItem } from '@vercel/commerce/types/cart' +import type { Category, Brand } from '@vercel/commerce/types/site' +import type { BigcommerceCart, BCCategory, BCBrand } from '../types' + import { definitions } from '../api/definitions/store-content' import update from './immutability' import getSlug from './get-slug' @@ -12,7 +14,7 @@ function normalizeProductOption(productOption: any) { } = productOption return { - id: entityId, + id: String(entityId), values: edges?.map(({ node }: any) => node), ...rest, } @@ -41,7 +43,7 @@ export function normalizeProduct(productNode: any): Product { variants: { $apply: ({ edges }: any) => edges?.map(({ node: { entityId, productOptions, ...rest } }: any) => ({ - id: entityId, + id: String(entityId), options: productOptions?.edges ? productOptions.edges.map(normalizeProductOption) : [], @@ -54,7 +56,7 @@ export function normalizeProduct(productNode: any): Product { : [], }, brand: { - $apply: (brand: any) => (brand?.entityId ? brand?.entityId : null), + $apply: (brand: any) => (brand?.id ? brand.id : null), }, slug: { $set: path?.replace(/^\/+|\/+$/g, ''), @@ -75,7 +77,8 @@ export function normalizePage(page: definitions['page_Full']): Page { name: page.name, is_visible: page.is_visible, sort_order: page.sort_order, - body: page.body, + body: page.body ?? '', + url: page.url, } } @@ -134,3 +137,12 @@ export function normalizeCategory(category: BCCategory): Category { path: category.path, } } + +export function normalizeBrand(brand: BCBrand): Brand { + return { + id: `${brand.node.entityId}`, + name: brand.node.name, + slug: getSlug(brand.node.path), + path: brand.node.path, + } +} diff --git a/packages/bigcommerce/src/product/use-search.tsx b/packages/bigcommerce/src/product/use-search.tsx index fd918e341e..9fa275f199 100644 --- a/packages/bigcommerce/src/product/use-search.tsx +++ b/packages/bigcommerce/src/product/use-search.tsx @@ -1,6 +1,6 @@ import { SWRHook } from '@vercel/commerce/utils/types' import useSearch, { UseSearch } from '@vercel/commerce/product/use-search' -import type { SearchProductsHook } from '../types/product' +import type { SearchProductsHook } from '@vercel/commerce/types/product' export default useSearch as UseSearch diff --git a/packages/bigcommerce/src/types.ts b/packages/bigcommerce/src/types.ts new file mode 100644 index 0000000000..43b65557cf --- /dev/null +++ b/packages/bigcommerce/src/types.ts @@ -0,0 +1,32 @@ +import type { GetSiteInfoQuery } from '../schema' + +export type BCCategory = NonNullable< + GetSiteInfoQuery['site']['categoryTree'] +>[0] + +export type BCBrand = NonNullable< + NonNullable[0] +> + +// TODO: this type should match: +// https://developer.bigcommerce.com/api-reference/cart-checkout/server-server-cart-api/cart/getacart#responses +export type BigcommerceCart = { + id: string + parent_id?: string + customer_id: number + email: string + currency: { code: string } + tax_included: boolean + base_amount: number + discount_amount: number + cart_amount: number + line_items: { + custom_items: any[] + digital_items: any[] + gift_certificates: any[] + physical_items: any[] + } + created_time: string + discounts?: { id: number; discounted_amount: number }[] + // TODO: add missing fields +} diff --git a/packages/bigcommerce/src/types/cart.ts b/packages/bigcommerce/src/types/cart.ts deleted file mode 100644 index 3b5d8288b8..0000000000 --- a/packages/bigcommerce/src/types/cart.ts +++ /dev/null @@ -1,66 +0,0 @@ -import * as Core from '@vercel/commerce/types/cart' - -export * from '@vercel/commerce/types/cart' - -// TODO: this type should match: -// https://developer.bigcommerce.com/api-reference/cart-checkout/server-server-cart-api/cart/getacart#responses -export type BigcommerceCart = { - id: string - parent_id?: string - customer_id: number - email: string - currency: { code: string } - tax_included: boolean - base_amount: number - discount_amount: number - cart_amount: number - line_items: { - custom_items: any[] - digital_items: any[] - gift_certificates: any[] - physical_items: any[] - } - created_time: string - discounts?: { id: number; discounted_amount: number }[] - // TODO: add missing fields -} - -/** - * Extend core cart types - */ - -export type Cart = Core.Cart & { - lineItems: Core.LineItem[] -} - -export type OptionSelections = { - option_id: number - option_value: number | string -} - -export type CartItemBody = Core.CartItemBody & { - productId: string // The product id is always required for BC - optionSelections?: OptionSelections[] -} - -export type CartTypes = { - cart: Cart - item: Core.LineItem - itemBody: CartItemBody -} - -export type CartHooks = Core.CartHooks - -export type GetCartHook = CartHooks['getCart'] -export type AddItemHook = CartHooks['addItem'] -export type UpdateItemHook = CartHooks['updateItem'] -export type RemoveItemHook = CartHooks['removeItem'] - -export type CartSchema = Core.CartSchema - -export type CartHandlers = Core.CartHandlers - -export type GetCartHandler = CartHandlers['getCart'] -export type AddItemHandler = CartHandlers['addItem'] -export type UpdateItemHandler = CartHandlers['updateItem'] -export type RemoveItemHandler = CartHandlers['removeItem'] diff --git a/packages/bigcommerce/src/types/checkout.ts b/packages/bigcommerce/src/types/checkout.ts deleted file mode 100644 index d139db6859..0000000000 --- a/packages/bigcommerce/src/types/checkout.ts +++ /dev/null @@ -1 +0,0 @@ -export * from '@vercel/commerce/types/checkout' diff --git a/packages/bigcommerce/src/types/common.ts b/packages/bigcommerce/src/types/common.ts deleted file mode 100644 index 23b8daa11c..0000000000 --- a/packages/bigcommerce/src/types/common.ts +++ /dev/null @@ -1 +0,0 @@ -export * from '@vercel/commerce/types/common' diff --git a/packages/bigcommerce/src/types/customer.ts b/packages/bigcommerce/src/types/customer.ts deleted file mode 100644 index 6e66366be2..0000000000 --- a/packages/bigcommerce/src/types/customer.ts +++ /dev/null @@ -1,5 +0,0 @@ -import * as Core from '@vercel/commerce/types/customer' - -export * from '@vercel/commerce/types/customer' - -export type CustomerSchema = Core.CustomerSchema diff --git a/packages/bigcommerce/src/types/index.ts b/packages/bigcommerce/src/types/index.ts deleted file mode 100644 index 7ab0b7f64f..0000000000 --- a/packages/bigcommerce/src/types/index.ts +++ /dev/null @@ -1,25 +0,0 @@ -import * as Cart from './cart' -import * as Checkout from './checkout' -import * as Common from './common' -import * as Customer from './customer' -import * as Login from './login' -import * as Logout from './logout' -import * as Page from './page' -import * as Product from './product' -import * as Signup from './signup' -import * as Site from './site' -import * as Wishlist from './wishlist' - -export type { - Cart, - Checkout, - Common, - Customer, - Login, - Logout, - Page, - Product, - Signup, - Site, - Wishlist, -} diff --git a/packages/bigcommerce/src/types/login.ts b/packages/bigcommerce/src/types/login.ts deleted file mode 100644 index eff27ca46a..0000000000 --- a/packages/bigcommerce/src/types/login.ts +++ /dev/null @@ -1,8 +0,0 @@ -import * as Core from '@vercel/commerce/types/login' -import type { LoginMutationVariables } from '../../schema' - -export * from '@vercel/commerce/types/login' - -export type LoginOperation = Core.LoginOperation & { - variables: LoginMutationVariables -} diff --git a/packages/bigcommerce/src/types/logout.ts b/packages/bigcommerce/src/types/logout.ts deleted file mode 100644 index 1de06f8dc8..0000000000 --- a/packages/bigcommerce/src/types/logout.ts +++ /dev/null @@ -1 +0,0 @@ -export * from '@vercel/commerce/types/logout' diff --git a/packages/bigcommerce/src/types/page.ts b/packages/bigcommerce/src/types/page.ts deleted file mode 100644 index ccbc29f7b2..0000000000 --- a/packages/bigcommerce/src/types/page.ts +++ /dev/null @@ -1,11 +0,0 @@ -import * as Core from '@vercel/commerce/types/page' -export * from '@vercel/commerce/types/page' - -export type Page = Core.Page - -export type PageTypes = { - page: Page -} - -export type GetAllPagesOperation = Core.GetAllPagesOperation -export type GetPageOperation = Core.GetPageOperation diff --git a/packages/bigcommerce/src/types/product.ts b/packages/bigcommerce/src/types/product.ts deleted file mode 100644 index 72ca02f02d..0000000000 --- a/packages/bigcommerce/src/types/product.ts +++ /dev/null @@ -1 +0,0 @@ -export * from '@vercel/commerce/types/product' diff --git a/packages/bigcommerce/src/types/signup.ts b/packages/bigcommerce/src/types/signup.ts deleted file mode 100644 index 3f0d1af5ac..0000000000 --- a/packages/bigcommerce/src/types/signup.ts +++ /dev/null @@ -1 +0,0 @@ -export * from '@vercel/commerce/types/signup' diff --git a/packages/bigcommerce/src/types/site.ts b/packages/bigcommerce/src/types/site.ts deleted file mode 100644 index 5c3074cc95..0000000000 --- a/packages/bigcommerce/src/types/site.ts +++ /dev/null @@ -1,19 +0,0 @@ -import * as Core from '@vercel/commerce/types/site' -import type { GetSiteInfoQuery, GetSiteInfoQueryVariables } from '../../schema' - -export * from '@vercel/commerce/types/site' - -export type BCCategory = NonNullable< - GetSiteInfoQuery['site']['categoryTree'] ->[0] - -export type Brand = NonNullable< - NonNullable[0] -> - -export type SiteTypes = { - category: Core.Category - brand: Brand -} - -export type GetSiteInfoOperation = Core.GetSiteInfoOperation diff --git a/packages/bigcommerce/src/types/wishlist.ts b/packages/bigcommerce/src/types/wishlist.ts deleted file mode 100644 index 67cf58c26e..0000000000 --- a/packages/bigcommerce/src/types/wishlist.ts +++ /dev/null @@ -1,24 +0,0 @@ -import * as Core from '@vercel/commerce/types/wishlist' -import { definitions } from '../api/definitions/wishlist' -import type { ProductEdge } from '../api/operations/get-all-products' - -export * from '@vercel/commerce/types/wishlist' - -export type WishlistItem = NonNullable< - definitions['wishlist_Full']['items'] ->[0] & { - product?: ProductEdge['node'] -} - -export type Wishlist = Omit & { - items?: WishlistItem[] -} - -export type WishlistTypes = { - wishlist: Wishlist - itemBody: Core.WishlistItemBody -} - -export type WishlistSchema = Core.WishlistSchema -export type GetCustomerWishlistOperation = - Core.GetCustomerWishlistOperation diff --git a/packages/bigcommerce/src/wishlist/use-add-item.tsx b/packages/bigcommerce/src/wishlist/use-add-item.tsx index c9e237b0b3..ba12eabf8e 100644 --- a/packages/bigcommerce/src/wishlist/use-add-item.tsx +++ b/packages/bigcommerce/src/wishlist/use-add-item.tsx @@ -1,8 +1,10 @@ import { useCallback } from 'react' import type { MutationHook } from '@vercel/commerce/utils/types' import { CommerceError } from '@vercel/commerce/utils/errors' -import useAddItem, { UseAddItem } from '@vercel/commerce/wishlist/use-add-item' -import type { AddItemHook } from '../types/wishlist' +import useAddItem, { + type UseAddItem, +} from '@vercel/commerce/wishlist/use-add-item' +import type { AddItemHook } from '@vercel/commerce/types/wishlist' import useCustomer from '../customer/use-customer' import useWishlist from './use-wishlist' diff --git a/packages/bigcommerce/src/wishlist/use-remove-item.tsx b/packages/bigcommerce/src/wishlist/use-remove-item.tsx index 40ca0da049..63cca503d7 100644 --- a/packages/bigcommerce/src/wishlist/use-remove-item.tsx +++ b/packages/bigcommerce/src/wishlist/use-remove-item.tsx @@ -2,9 +2,9 @@ import { useCallback } from 'react' import type { MutationHook } from '@vercel/commerce/utils/types' import { CommerceError } from '@vercel/commerce/utils/errors' import useRemoveItem, { - UseRemoveItem, + type UseRemoveItem, } from '@vercel/commerce/wishlist/use-remove-item' -import type { RemoveItemHook } from '../types/wishlist' +import type { RemoveItemHook } from '@vercel/commerce/types/wishlist' import useCustomer from '../customer/use-customer' import useWishlist from './use-wishlist' diff --git a/packages/bigcommerce/src/wishlist/use-wishlist.tsx b/packages/bigcommerce/src/wishlist/use-wishlist.tsx index 7882233f52..058b03c8cb 100644 --- a/packages/bigcommerce/src/wishlist/use-wishlist.tsx +++ b/packages/bigcommerce/src/wishlist/use-wishlist.tsx @@ -1,11 +1,11 @@ import { useMemo } from 'react' import { SWRHook } from '@vercel/commerce/utils/types' import useWishlist, { - UseWishlist, + type UseWishlist, } from '@vercel/commerce/wishlist/use-wishlist' import useCustomer from '../customer/use-customer' -import type { GetWishlistHook } from '../types/wishlist' +import type { GetWishlistHook } from '@vercel/commerce/types/wishlist' export default useWishlist as UseWishlist export const handler: SWRHook = { @@ -32,7 +32,7 @@ export const handler: SWRHook = { const { data: customer } = useCustomer() const response = useData({ input: [ - ['customerId', customer?.entityId], + ['customerId', customer?.id], ['includeProducts', input?.includeProducts], ], swrOptions: { diff --git a/packages/commerce/package.json b/packages/commerce/package.json index 72cd36c4a1..784201f2ec 100644 --- a/packages/commerce/package.json +++ b/packages/commerce/package.json @@ -52,7 +52,8 @@ "import-cwd": "^3.0.0", "js-cookie": "^3.0.1", "swr": "^1.3.0", - "node-fetch": "^2.6.7" + "node-fetch": "^2.6.7", + "zod": "^3.19.0" }, "peerDependencies": { "next": "^12", diff --git a/packages/commerce/src/api/endpoints/cart.ts b/packages/commerce/src/api/endpoints/cart.ts index abd5df4929..e5a05dbd6f 100644 --- a/packages/commerce/src/api/endpoints/cart.ts +++ b/packages/commerce/src/api/endpoints/cart.ts @@ -3,58 +3,60 @@ import { CommerceAPIError } from '../utils/errors' import isAllowedOperation from '../utils/is-allowed-operation' import type { GetAPISchema } from '..' -const cartEndpoint: GetAPISchema>['endpoint']['handler'] = - async (ctx) => { - const { req, res, handlers, config } = ctx - - if ( - !isAllowedOperation(req, res, { - GET: handlers['getCart'], - POST: handlers['addItem'], - PUT: handlers['updateItem'], - DELETE: handlers['removeItem'], - }) - ) { - return +const cartEndpoint: GetAPISchema< + any, + CartSchema +>['endpoint']['handler'] = async (ctx) => { + const { req, res, handlers, config } = ctx + + if ( + !isAllowedOperation(req, res, { + GET: handlers['getCart'], + POST: handlers['addItem'], + PUT: handlers['updateItem'], + DELETE: handlers['removeItem'], + }) + ) { + return + } + + const { cookies } = req + const cartId = cookies[config.cartCookie] + + try { + // Return current cart info + if (req.method === 'GET') { + const body = { cartId } + return await handlers['getCart']({ ...ctx, body }) + } + + // Create or add an item to the cart + if (req.method === 'POST') { + const body = { ...req.body, cartId } + return await handlers['addItem']({ ...ctx, body }) } - const { cookies } = req - const cartId = cookies[config.cartCookie] - - try { - // Return current cart info - if (req.method === 'GET') { - const body = { cartId } - return await handlers['getCart']({ ...ctx, body }) - } - - // Create or add an item to the cart - if (req.method === 'POST') { - const body = { ...req.body, cartId } - return await handlers['addItem']({ ...ctx, body }) - } - - // Update item in cart - if (req.method === 'PUT') { - const body = { ...req.body, cartId } - return await handlers['updateItem']({ ...ctx, body }) - } - - // Remove an item from the cart - if (req.method === 'DELETE') { - const body = { ...req.body, cartId } - return await handlers['removeItem']({ ...ctx, body }) - } - } catch (error) { - console.error(error) - - const message = - error instanceof CommerceAPIError - ? 'An unexpected error ocurred with the Commerce API' - : 'An unexpected error ocurred' - - res.status(500).json({ data: null, errors: [{ message }] }) + // Update item in cart + if (req.method === 'PUT') { + const body = { ...req.body, cartId } + return await handlers['updateItem']({ ...ctx, body }) } + + // Remove an item from the cart + if (req.method === 'DELETE') { + const body = { ...req.body, cartId } + return await handlers['removeItem']({ ...ctx, body }) + } + } catch (error) { + console.error(error) + + const message = + error instanceof CommerceAPIError + ? 'An unexpected error ocurred with the Commerce API' + : 'An unexpected error ocurred' + + res.status(500).json({ data: null, errors: [{ message }] }) } +} export default cartEndpoint diff --git a/packages/commerce/src/api/endpoints/customer/index.ts b/packages/commerce/src/api/endpoints/customer/index.ts index eb2a048b72..2107ebb895 100644 --- a/packages/commerce/src/api/endpoints/customer/index.ts +++ b/packages/commerce/src/api/endpoints/customer/index.ts @@ -6,7 +6,7 @@ import isAllowedOperation from '../../utils/is-allowed-operation' const customerEndpoint: GetAPISchema< any, - CustomerSchema + CustomerSchema >['endpoint']['handler'] = async (ctx) => { const { req, res, handlers } = ctx diff --git a/packages/commerce/src/api/endpoints/index.ts b/packages/commerce/src/api/endpoints/index.ts new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/commerce/src/api/endpoints/login.ts b/packages/commerce/src/api/endpoints/login.ts index 6f69629b13..cfec82e6ac 100644 --- a/packages/commerce/src/api/endpoints/login.ts +++ b/packages/commerce/src/api/endpoints/login.ts @@ -5,7 +5,7 @@ import type { GetAPISchema } from '..' const loginEndpoint: GetAPISchema< any, - LoginSchema + LoginSchema >['endpoint']['handler'] = async (ctx) => { const { req, res, handlers } = ctx diff --git a/packages/commerce/src/api/endpoints/wishlist.ts b/packages/commerce/src/api/endpoints/wishlist.ts index 233ac52945..688fcd5da9 100644 --- a/packages/commerce/src/api/endpoints/wishlist.ts +++ b/packages/commerce/src/api/endpoints/wishlist.ts @@ -5,7 +5,7 @@ import type { GetAPISchema } from '..' const wishlistEndpoint: GetAPISchema< any, - WishlistSchema + WishlistSchema >['endpoint']['handler'] = async (ctx) => { const { req, res, handlers, config } = ctx diff --git a/packages/commerce/src/api/index.ts b/packages/commerce/src/api/index.ts index 6914b93643..4e10e36662 100644 --- a/packages/commerce/src/api/index.ts +++ b/packages/commerce/src/api/index.ts @@ -11,11 +11,14 @@ import type { WishlistSchema } from '../types/wishlist' import type { CheckoutSchema } from '../types/checkout' import type { CustomerCardSchema } from '../types/customer/card' import type { CustomerAddressSchema } from '../types/customer/address' + +import { withOperationCallback } from './utils/with-operation-callback' + import { - defaultOperations, OPERATIONS, AllOperations, APIOperations, + defaultOperations, } from './operations' export type APISchemas = @@ -106,7 +109,10 @@ export function getCommerceApi

( OPERATIONS.forEach((k) => { const op = ops[k] if (op) { - commerce[k] = op({ commerce }) as AllOperations

[typeof k] + commerce[k] = withOperationCallback( + k, + op({ commerce }) + ) as AllOperations

[typeof k] } }) diff --git a/packages/commerce/src/api/operations.ts b/packages/commerce/src/api/operations.ts index 2910a2d82b..daf66acd4f 100644 --- a/packages/commerce/src/api/operations.ts +++ b/packages/commerce/src/api/operations.ts @@ -25,6 +25,13 @@ export const OPERATIONS = [ 'getProduct', ] as const +export type Operation = { + [O in AllowedOperations]: { + name: O + data: Awaited[O]>> + } +}[AllowedOperations] + export const defaultOperations = OPERATIONS.reduce((ops, k) => { ops[k] = noop return ops diff --git a/packages/commerce/src/api/utils/errors.ts b/packages/commerce/src/api/utils/errors.ts index 6f9ecce0c3..065faf34af 100644 --- a/packages/commerce/src/api/utils/errors.ts +++ b/packages/commerce/src/api/utils/errors.ts @@ -1,4 +1,7 @@ +import { ZodError } from 'zod' + import type { Response } from '@vercel/fetch' +import { CommerceError } from '../../utils/errors' export class CommerceAPIError extends Error { status: number @@ -20,3 +23,25 @@ export class CommerceNetworkError extends Error { this.name = 'CommerceNetworkError' } } + +export const getOperationError = (operation: string, error: unknown) => { + if (error instanceof ZodError) { + return new CommerceError({ + code: 'SCHEMA_VALIDATION_ERROR', + message: + `The ${operation} operation returned invalid data and has ${ + error.issues.length + } parse ${error.issues.length === 1 ? 'error' : 'errors'}: \n` + + error.issues + .map( + (e, index) => + `Error #${index + 1} ${ + e.path.length > 0 ? `Path: ${e.path.join('.')}, ` : '' + }Code: ${e.code}, Message: ${e.message}` + ) + .join('\n'), + }) + } + + return error +} diff --git a/packages/commerce/src/api/utils/with-operation-callback.ts b/packages/commerce/src/api/utils/with-operation-callback.ts new file mode 100644 index 0000000000..b4f5a88ee4 --- /dev/null +++ b/packages/commerce/src/api/utils/with-operation-callback.ts @@ -0,0 +1,42 @@ +import type { AllowedOperations, Operation } from '../operations' + +import { z } from 'zod' +import { getOperationError } from './errors' +import { pageSchema } from '../../schemas/page' +import { siteInfoSchema } from '../../schemas/site' +import { productSchema, productsPathsSchema } from '../../schemas/product' + +export const withOperationCallback = + (name: AllowedOperations, fn: (...args: any[]) => Promise) => + async (...args: any[]) => { + try { + const data = await fn(...args) + parse({ name, data }) + return data + } catch (error) { + throw getOperationError(name, error) + } + } + +const parse = ({ name, data }: Operation) => { + switch (name) { + case 'getProduct': + productSchema.nullable().parse(data.product) + break + case 'getAllProducts': + z.array(productSchema).parse(data.products) + break + case 'getAllProductPaths': + productsPathsSchema.parse(data.products) + break + case 'getPage': + pageSchema.nullable().parse(data.page) + break + case 'getAllPages': + z.array(pageSchema).parse(data.pages) + break + case 'getSiteInfo': + siteInfoSchema.parse(data) + break + } +} diff --git a/packages/commerce/src/auth/use-login.tsx b/packages/commerce/src/auth/use-login.tsx index 67fb429dc5..ce2473543a 100644 --- a/packages/commerce/src/auth/use-login.tsx +++ b/packages/commerce/src/auth/use-login.tsx @@ -5,7 +5,7 @@ import type { LoginHook } from '../types/login' import type { Provider } from '..' export type UseLogin< - H extends MutationHook> = MutationHook + H extends MutationHook = MutationHook > = ReturnType export const fetcher: HookFetcherFn = mutationFetcher diff --git a/packages/commerce/src/auth/use-logout.tsx b/packages/commerce/src/auth/use-logout.tsx index 6ca16decf7..f8eaeb60d4 100644 --- a/packages/commerce/src/auth/use-logout.tsx +++ b/packages/commerce/src/auth/use-logout.tsx @@ -5,7 +5,7 @@ import type { LogoutHook } from '../types/logout' import type { Provider } from '..' export type UseLogout< - H extends MutationHook> = MutationHook + H extends MutationHook = MutationHook > = ReturnType export const fetcher: HookFetcherFn = mutationFetcher diff --git a/packages/commerce/src/auth/use-signup.tsx b/packages/commerce/src/auth/use-signup.tsx index 2f846fad6b..d9ac23426f 100644 --- a/packages/commerce/src/auth/use-signup.tsx +++ b/packages/commerce/src/auth/use-signup.tsx @@ -5,7 +5,7 @@ import type { SignupHook } from '../types/signup' import type { Provider } from '..' export type UseSignup< - H extends MutationHook> = MutationHook + H extends MutationHook = MutationHook > = ReturnType export const fetcher: HookFetcherFn = mutationFetcher diff --git a/packages/commerce/src/cart/use-add-item.tsx b/packages/commerce/src/cart/use-add-item.tsx index f4072c7633..072e68674d 100644 --- a/packages/commerce/src/cart/use-add-item.tsx +++ b/packages/commerce/src/cart/use-add-item.tsx @@ -5,7 +5,7 @@ import type { AddItemHook } from '../types/cart' import type { Provider } from '..' export type UseAddItem< - H extends MutationHook> = MutationHook + H extends MutationHook = MutationHook > = ReturnType export const fetcher: HookFetcherFn = mutationFetcher diff --git a/packages/commerce/src/cart/use-cart.tsx b/packages/commerce/src/cart/use-cart.tsx index cfce59e36c..e37b9844c4 100644 --- a/packages/commerce/src/cart/use-cart.tsx +++ b/packages/commerce/src/cart/use-cart.tsx @@ -4,9 +4,8 @@ import type { SWRHook, HookFetcherFn } from '../utils/types' import type { GetCartHook } from '../types/cart' import { Provider, useCommerce } from '..' -export type UseCart< - H extends SWRHook> = SWRHook -> = ReturnType +export type UseCart = SWRHook> = + ReturnType export const fetcher: HookFetcherFn = async ({ options, diff --git a/packages/commerce/src/cart/use-remove-item.tsx b/packages/commerce/src/cart/use-remove-item.tsx index f2bb43ffbc..a401f5e104 100644 --- a/packages/commerce/src/cart/use-remove-item.tsx +++ b/packages/commerce/src/cart/use-remove-item.tsx @@ -5,7 +5,7 @@ import type { RemoveItemHook } from '../types/cart' import type { Provider } from '..' export type UseRemoveItem< - H extends MutationHook> = MutationHook + H extends MutationHook = MutationHook > = ReturnType export const fetcher: HookFetcherFn = mutationFetcher diff --git a/packages/commerce/src/cart/use-update-item.tsx b/packages/commerce/src/cart/use-update-item.tsx index 2527732eb7..099a0b129b 100644 --- a/packages/commerce/src/cart/use-update-item.tsx +++ b/packages/commerce/src/cart/use-update-item.tsx @@ -5,7 +5,7 @@ import type { UpdateItemHook } from '../types/cart' import type { Provider } from '..' export type UseUpdateItem< - H extends MutationHook> = MutationHook + H extends MutationHook = MutationHook > = ReturnType export const fetcher: HookFetcherFn = mutationFetcher diff --git a/packages/commerce/src/checkout/use-checkout.ts b/packages/commerce/src/checkout/use-checkout.ts index 0fe74cb28c..a593d57db7 100644 --- a/packages/commerce/src/checkout/use-checkout.ts +++ b/packages/commerce/src/checkout/use-checkout.ts @@ -7,7 +7,7 @@ import { useHook, useSWRHook } from '../utils/use-hook' import { Provider, useCommerce } from '..' export type UseCheckout< - H extends SWRHook> = SWRHook + H extends SWRHook = SWRHook > = ReturnType export const fetcher: HookFetcherFn = async ({ diff --git a/packages/commerce/src/checkout/use-submit-checkout.tsx b/packages/commerce/src/checkout/use-submit-checkout.tsx index a5d8650029..7304d0047a 100644 --- a/packages/commerce/src/checkout/use-submit-checkout.tsx +++ b/packages/commerce/src/checkout/use-submit-checkout.tsx @@ -6,9 +6,7 @@ import { useHook, useMutationHook } from '../utils/use-hook' import { mutationFetcher } from '../utils/default-fetcher' export type UseSubmitCheckout< - H extends MutationHook< - SubmitCheckoutHook - > = MutationHook + H extends MutationHook = MutationHook > = ReturnType export const fetcher: HookFetcherFn = mutationFetcher diff --git a/packages/commerce/src/customer/address/use-add-item.tsx b/packages/commerce/src/customer/address/use-add-item.tsx index 94c45142ec..664ab06fcf 100644 --- a/packages/commerce/src/customer/address/use-add-item.tsx +++ b/packages/commerce/src/customer/address/use-add-item.tsx @@ -6,7 +6,7 @@ import { useHook, useMutationHook } from '../../utils/use-hook' import { mutationFetcher } from '../../utils/default-fetcher' export type UseAddItem< - H extends MutationHook> = MutationHook + H extends MutationHook = MutationHook > = ReturnType export const fetcher: HookFetcherFn = mutationFetcher diff --git a/packages/commerce/src/customer/address/use-addresses.tsx b/packages/commerce/src/customer/address/use-addresses.tsx index 7fc12924c5..5d60255031 100644 --- a/packages/commerce/src/customer/address/use-addresses.tsx +++ b/packages/commerce/src/customer/address/use-addresses.tsx @@ -7,7 +7,7 @@ import { useHook, useSWRHook } from '../../utils/use-hook' import { Provider, useCommerce } from '../..' export type UseAddresses< - H extends SWRHook> = SWRHook + H extends SWRHook = SWRHook > = ReturnType export const fetcher: HookFetcherFn = async ({ diff --git a/packages/commerce/src/customer/address/use-remove-item.tsx b/packages/commerce/src/customer/address/use-remove-item.tsx index 820a65dadd..e284cdd30e 100644 --- a/packages/commerce/src/customer/address/use-remove-item.tsx +++ b/packages/commerce/src/customer/address/use-remove-item.tsx @@ -6,7 +6,7 @@ import { useHook, useMutationHook } from '../../utils/use-hook' import { mutationFetcher } from '../../utils/default-fetcher' export type UseRemoveItem< - H extends MutationHook> = MutationHook + H extends MutationHook = MutationHook > = ReturnType export const fetcher: HookFetcherFn = mutationFetcher diff --git a/packages/commerce/src/customer/address/use-update-item.tsx b/packages/commerce/src/customer/address/use-update-item.tsx index d058822968..74803f30d1 100644 --- a/packages/commerce/src/customer/address/use-update-item.tsx +++ b/packages/commerce/src/customer/address/use-update-item.tsx @@ -6,7 +6,7 @@ import { useHook, useMutationHook } from '../../utils/use-hook' import { mutationFetcher } from '../../utils/default-fetcher' export type UseUpdateItem< - H extends MutationHook> = MutationHook + H extends MutationHook = MutationHook > = ReturnType export const fetcher: HookFetcherFn = mutationFetcher diff --git a/packages/commerce/src/customer/card/use-add-item.tsx b/packages/commerce/src/customer/card/use-add-item.tsx index 7b4ffdb177..a3983988a6 100644 --- a/packages/commerce/src/customer/card/use-add-item.tsx +++ b/packages/commerce/src/customer/card/use-add-item.tsx @@ -6,7 +6,7 @@ import { useHook, useMutationHook } from '../../utils/use-hook' import { mutationFetcher } from '../../utils/default-fetcher' export type UseAddItem< - H extends MutationHook> = MutationHook + H extends MutationHook = MutationHook > = ReturnType export const fetcher: HookFetcherFn = mutationFetcher diff --git a/packages/commerce/src/customer/card/use-cards.tsx b/packages/commerce/src/customer/card/use-cards.tsx index 57099504fa..53562c8ec2 100644 --- a/packages/commerce/src/customer/card/use-cards.tsx +++ b/packages/commerce/src/customer/card/use-cards.tsx @@ -6,9 +6,8 @@ import Cookies from 'js-cookie' import { useHook, useSWRHook } from '../../utils/use-hook' import { Provider, useCommerce } from '../..' -export type UseCards< - H extends SWRHook> = SWRHook -> = ReturnType +export type UseCards = SWRHook> = + ReturnType export const fetcher: HookFetcherFn = async ({ options, diff --git a/packages/commerce/src/customer/card/use-remove-item.tsx b/packages/commerce/src/customer/card/use-remove-item.tsx index 1d85fa636e..5b1539f270 100644 --- a/packages/commerce/src/customer/card/use-remove-item.tsx +++ b/packages/commerce/src/customer/card/use-remove-item.tsx @@ -6,7 +6,7 @@ import { useHook, useMutationHook } from '../../utils/use-hook' import { mutationFetcher } from '../../utils/default-fetcher' export type UseRemoveItem< - H extends MutationHook> = MutationHook + H extends MutationHook = MutationHook > = ReturnType export const fetcher: HookFetcherFn = mutationFetcher diff --git a/packages/commerce/src/customer/card/use-update-item.tsx b/packages/commerce/src/customer/card/use-update-item.tsx index cd8837d7f3..0542e5dc91 100644 --- a/packages/commerce/src/customer/card/use-update-item.tsx +++ b/packages/commerce/src/customer/card/use-update-item.tsx @@ -6,7 +6,7 @@ import { useHook, useMutationHook } from '../../utils/use-hook' import { mutationFetcher } from '../../utils/default-fetcher' export type UseUpdateItem< - H extends MutationHook> = MutationHook + H extends MutationHook = MutationHook > = ReturnType export const fetcher: HookFetcherFn = mutationFetcher diff --git a/packages/commerce/src/customer/use-customer.tsx b/packages/commerce/src/customer/use-customer.tsx index bbeeb3269c..9bb703f7e8 100644 --- a/packages/commerce/src/customer/use-customer.tsx +++ b/packages/commerce/src/customer/use-customer.tsx @@ -5,7 +5,7 @@ import type { HookFetcherFn, SWRHook } from '../utils/types' import type { Provider } from '..' export type UseCustomer< - H extends SWRHook> = SWRHook + H extends SWRHook = SWRHook > = ReturnType export const fetcher: HookFetcherFn = SWRFetcher diff --git a/packages/commerce/src/product/use-search.tsx b/packages/commerce/src/product/use-search.tsx index 342b49e6e0..7998e9994f 100644 --- a/packages/commerce/src/product/use-search.tsx +++ b/packages/commerce/src/product/use-search.tsx @@ -5,7 +5,7 @@ import type { SearchProductsHook } from '../types/product' import type { Provider } from '..' export type UseSearch< - H extends SWRHook> = SWRHook + H extends SWRHook = SWRHook > = ReturnType export const fetcher: HookFetcherFn = SWRFetcher diff --git a/packages/commerce/src/schemas/page.ts b/packages/commerce/src/schemas/page.ts new file mode 100644 index 0000000000..5dfd175e11 --- /dev/null +++ b/packages/commerce/src/schemas/page.ts @@ -0,0 +1,18 @@ +import { z } from 'zod' + +export const pageSchema = z.object({ + id: z.string(), + name: z.string(), + url: z.string().startsWith('/').optional(), + body: z.string(), + is_visible: z.boolean().optional(), + sort_order: z.number().optional(), +}) + +export const pagesPathsSchema = z.array( + z.object({ + page: z.object({ + path: z.string().startsWith('/'), + }), + }) +) diff --git a/packages/commerce/src/schemas/product.ts b/packages/commerce/src/schemas/product.ts new file mode 100644 index 0000000000..ca02158e9e --- /dev/null +++ b/packages/commerce/src/schemas/product.ts @@ -0,0 +1,60 @@ +import { z } from 'zod' + +export const productPriceSchema = z.object({ + value: z.number(), + currencyCode: z.string().max(3).optional(), + retailPrice: z.number().optional(), +}) + +export const productOptionSchema = z.object({ + id: z.string(), + displayName: z.string(), + values: z.array( + z.object({ + label: z.string(), + hexColors: z.array(z.string()).optional(), + }) + ), +}) + +export const productImageSchema = z.object({ + url: z.string().url().or(z.string().startsWith('/')), + alt: z.string().optional(), + width: z.number().optional(), + height: z.number().optional(), +}) + +export const productVariantSchema = z.object({ + id: z.string(), + sku: z.string().nullish(), + name: z.string().optional(), + options: z.array(productOptionSchema), + image: productImageSchema.optional(), +}) + +export const productSchema = z.object({ + id: z.string(), + name: z.string(), + description: z.string(), + descriptionHtml: z.string().optional(), + sku: z.string().nullish(), + slug: z.string(), + path: z.string().startsWith('/'), + images: z.array(productImageSchema), + variants: z.array(productVariantSchema), + price: productPriceSchema, + options: z.array(productOptionSchema), + vendor: z.string().optional(), +}) + +export const productsPathsSchema = z.array( + z.object({ path: z.string().startsWith('/') }) +) + +export const searchProductBodySchema = z.object({ + search: z.string(), + categoryId: z.string(), + brandId: z.string().optional(), + sort: z.string().optional(), + locale: z.string().optional(), +}) diff --git a/packages/commerce/src/schemas/site.ts b/packages/commerce/src/schemas/site.ts new file mode 100644 index 0000000000..f6c101e7f4 --- /dev/null +++ b/packages/commerce/src/schemas/site.ts @@ -0,0 +1,18 @@ +import { z } from 'zod' + +export const siteInfoSchema = z.object({ + categories: z.array( + z.object({ + id: z.string(), + name: z.string(), + path: z.string().startsWith('/'), + }) + ), + brands: z.array( + z.object({ + id: z.string(), + name: z.string(), + path: z.string().startsWith('/'), + }) + ), +}) diff --git a/packages/commerce/src/types/cart.ts b/packages/commerce/src/types/cart.ts index e4af878de1..487d746794 100644 --- a/packages/commerce/src/types/cart.ts +++ b/packages/commerce/src/types/cart.ts @@ -1,177 +1,264 @@ -import type { Discount, Measurement, Image } from './common' +import type { Discount, Image, Measurement } from './common' -export type SelectedOption = { - // The option's id. +// TODO: This should use the same type as the `ProductVariant` type from `product.ts` +export interface ProductVariant { + /** + * The unique identifier for the variant. + */ + id: string + /** + * The SKU (stock keeping unit) associated with the product variant. + */ + sku?: string + /** + * The product variant’s name, or the product's name. + */ + name: string + /** + * The product variant’s price after all discounts are applied. + */ + price: number + /** + * The product variant’s price before discounts are applied. + */ + listPrice: number + /** + * Indicates if the variant is available for sale. + */ + availableForSale?: boolean + /** + * Whether a customer needs to provide a shipping address when placing + * an order for the product variant. + */ + requiresShipping?: boolean + /** + * The image associated with the variant. + */ + image?: Image + /** + * The variant's weight. If a weight was not explicitly specified on the + * variant, this will be the product's weight. + */ + weight?: Measurement + /** + * The variant's height. If a height was not explicitly specified on the + * variant, this will be the product's height. + */ + height?: Measurement + /** + * The variant's width. If a width was not explicitly specified on the + * variant, this will be the product's width. + */ + width?: Measurement + /** + * The variant's depth. If a depth was not explicitly specified on the + * variant, this will be the product's depth. + */ + depth?: Measurement +} + +export interface SelectedOption { + /** + * The unique identifier for the option. + */ id?: string - // The product option’s name. + /** + * The product option’s name, such as "Color" or "Size". + */ name: string - /// The product option’s value. + /** + * The product option’s value, such as "Red" or "XL". + */ value: string } -export type LineItem = { +export interface LineItem { + /** + * The unique identifier for the line item. + */ id: string + /** + * The unique identifier for the product variant. + */ variantId: string + /** + * The unique identifier for the product, if the variant is not provided. + */ productId: string + /** + * This is usually the product's name. + */ name: string + /** + * The quantity of the product variant in the line item. + */ quantity: number + /** + * List of discounts applied to the line item. + */ discounts: Discount[] - // A human-friendly unique string automatically generated from the product’s name + /** + * A human-friendly unique string automatically generated from the product’s name. + */ path: string + /** + * The product variant. + */ variant: ProductVariant + /** + * List of selected options, to be used when displaying the line item, such as Color: Red, Size: XL. + */ options?: SelectedOption[] } -export type ProductVariant = { - id: string - // The SKU (stock keeping unit) associated with the product variant. - sku: string - // The product variant’s title, or the product's name. - name: string - // Whether a customer needs to provide a shipping address when placing - // an order for the product variant. - requiresShipping: boolean - // The product variant’s price after all discounts are applied. - price: number - // Product variant’s price, as quoted by the manufacturer/distributor. - listPrice: number - // Image associated with the product variant. Falls back to the product image - // if no image is available. - image?: Image - // Indicates whether this product variant is in stock. - isInStock?: boolean - // Indicates if the product variant is available for sale. - availableForSale?: boolean - // The variant's weight. If a weight was not explicitly specified on the - // variant this will be the product's weight. - weight?: Measurement - // The variant's height. If a height was not explicitly specified on the - // variant, this will be the product's height. - height?: Measurement - // The variant's width. If a width was not explicitly specified on the - // variant, this will be the product's width. - width?: Measurement - // The variant's depth. If a depth was not explicitly specified on the - // variant, this will be the product's depth. - depth?: Measurement -} - -// Shopping cart, a.k.a Checkout -export type Cart = { +/** + * Shopping cart, a.k.a Checkout + */ +export interface Cart { + /** + * The unique identifier for the cart. + */ id: string - // ID of the customer to which the cart belongs. + /** + * ID of the customer to which the cart belongs. + */ customerId?: string - // The email assigned to this cart + /** + * The URL of the cart. + */ + url?: string + /** + * The email assigned to this cart. + */ email?: string - // The date and time when the cart was created. + /** + * The date and time when the cart was created. + */ createdAt: string - // The currency used for this cart + /** + * The currency used for this cart */ currency: { code: string } - // Specifies if taxes are included in the line items. + /** + * Indicates if taxes are included in the line items. + */ taxesIncluded: boolean + /** + * List of cart line items. + */ lineItems: LineItem[] - // The sum of all the prices of all the items in the cart. - // Duties, taxes, shipping and discounts excluded. + /** + * The sum of all the pricexs of all the items in the cart. + * Duties, taxes, shipping and discounts excluded. + */ lineItemsSubtotalPrice: number - // Price of the cart before duties, shipping and taxes. + /** + * Price of the cart before duties, shipping and taxes.*/ subtotalPrice: number - // The sum of all the prices of all the items in the cart. - // Duties, taxes and discounts included. + /** + * The sum of all the prices of all the items in the cart. + * Duties, taxes and discounts included. + */ totalPrice: number - // Discounts that have been applied on the cart. + /** + * Discounts that have been applied on the cart. + */ discounts?: Discount[] } /** * Base cart item body used for cart mutations */ -export type CartItemBody = { +export interface CartItemBody { + /** + * The unique identifier for the product variant. + */ variantId: string + /** + * The unique identifier for the product, if the variant is not provided. + */ productId?: string + /** + * The quantity of the product variant. + */ quantity?: number + + /** + * The product variant's selected options. + */ + optionsSelected?: SelectedOption[] } /** - * Hooks schema + * Cart Hooks for add, update and remove items from the cart */ - -export type CartTypes = { - cart?: Cart - item: LineItem - itemBody: CartItemBody +export type CartHooks = { + getCart: GetCartHook + addItem: AddItemHook + updateItem: UpdateItemHook + removeItem: RemoveItemHook } -export type CartHooks = { - getCart: GetCartHook - addItem: AddItemHook - updateItem: UpdateItemHook - removeItem: RemoveItemHook -} - -export type GetCartHook = { - data: T['cart'] | null +export type GetCartHook = { + data: Cart | null input: {} fetcherInput: { cartId?: string } swrState: { isEmpty: boolean } } -export type AddItemHook = { - data: T['cart'] - input?: T['itemBody'] - fetcherInput: T['itemBody'] - body: { item: T['itemBody'] } - actionInput: T['itemBody'] +export type AddItemHook = { + data: Cart + input?: CartItemBody + fetcherInput: CartItemBody + body: { item: CartItemBody } + actionInput: CartItemBody } -export type UpdateItemHook = { - data: T['cart'] | null - input: { item?: T['item']; wait?: number } - fetcherInput: { itemId: string; item: T['itemBody'] } - body: { itemId: string; item: T['itemBody'] } - actionInput: T['itemBody'] & { id: string } +export type UpdateItemHook = { + data: Cart | null | undefined + input: { item?: LineItem; wait?: number } + fetcherInput: { itemId: string; item: CartItemBody } + body: { itemId: string; item: CartItemBody } + actionInput: CartItemBody & { id: string } } -export type RemoveItemHook = { - data: T['cart'] | null - input: { item?: T['item'] } +export type RemoveItemHook = { + data: Cart | null | undefined + input: { item?: LineItem } fetcherInput: { itemId: string } body: { itemId: string } actionInput: { id: string } } /** - * API Schema + * Cart API endpoitns & handlers for add, update and remove items from the cart */ - -export type CartSchema = { +export type CartSchema = { endpoint: { options: {} - handlers: CartHandlers + handlers: CartHandlers } } -export type CartHandlers = { - getCart: GetCartHandler - addItem: AddItemHandler - updateItem: UpdateItemHandler - removeItem: RemoveItemHandler +export type CartHandlers = { + getCart: GetCartHandler + addItem: AddItemHandler + updateItem: UpdateItemHandler + removeItem: RemoveItemHandler } -export type GetCartHandler = GetCartHook & { +export type GetCartHandler = GetCartHook & { body: { cartId?: string } } -export type AddItemHandler = AddItemHook & { +export type AddItemHandler = AddItemHook & { body: { cartId: string } } -export type UpdateItemHandler = - UpdateItemHook & { - data: T['cart'] - body: { cartId: string } - } +export type UpdateItemHandler = UpdateItemHook & { + data: Cart + body: { cartId: string } +} -export type RemoveItemHandler = - RemoveItemHook & { - body: { cartId: string } - } +export type RemoveItemHandler = RemoveItemHook & { + body: { cartId: string } +} diff --git a/packages/commerce/src/types/checkout.ts b/packages/commerce/src/types/checkout.ts index 417604fdb8..8b5d428fc6 100644 --- a/packages/commerce/src/types/checkout.ts +++ b/packages/commerce/src/types/checkout.ts @@ -1,57 +1,89 @@ import type { UseSubmitCheckout } from '../checkout/use-submit-checkout' -import type { Address, AddressFields } from './customer/address' +import type { AddressFields } from './customer/address' import type { Card, CardFields } from './customer/card' +import type { LineItem } from './cart' -// Index -export type Checkout = any +export interface Checkout { + /** + * Indicates if the checkout has payment iformation collected. + */ + hasPayment: boolean + /** + * Indicates if the checkout has shipping information collected. + */ + hasShipping: boolean + /** + * The unique identifier for the address that the customer has selected for shipping. + */ + addressId: string + /** + * The list of payment cards that the customer has available. + */ + payments?: Card[] + /** + * The unique identifier of the card that the customer has selected for payment. + */ + cardId?: string + /** + * List of items in the checkout. + */ + lineItems?: LineItem[] +} -export type CheckoutTypes = { - card?: Card | CardFields - address?: Address | AddressFields - checkout?: Checkout - hasPayment?: boolean - hasShipping?: boolean +export interface CheckoutBody { + /** + * The unique identifier for the cart. + */ + cartId?: string + /** + * The Card information. + * @see CardFields + */ + card: CardFields + /** + * The Address information. + * @see AddressFields + */ + address: AddressFields } -export type SubmitCheckoutHook = { - data: T - input?: T - fetcherInput: T - body: { item: T } - actionInput: T +export type SubmitCheckoutHook = { + data: Checkout + input?: CheckoutBody + fetcherInput: CheckoutBody + body: { item: CheckoutBody } + actionInput: CheckoutBody } -export type GetCheckoutHook = { - data: T['checkout'] | null +export type GetCheckoutHook = { + data: Checkout | null input: {} fetcherInput: { cartId?: string } swrState: { isEmpty: boolean } mutations: { submit: UseSubmitCheckout } } -export type CheckoutHooks = { - submitCheckout?: SubmitCheckoutHook - getCheckout: GetCheckoutHook +export type CheckoutHooks = { + submitCheckout?: SubmitCheckoutHook + getCheckout: GetCheckoutHook } -export type GetCheckoutHandler = - GetCheckoutHook & { - body: { cartId: string } - } +export type GetCheckoutHandler = GetCheckoutHook & { + body: { cartId: string } +} -export type SubmitCheckoutHandler = - SubmitCheckoutHook & { - body: { cartId: string } - } +export type SubmitCheckoutHandler = SubmitCheckoutHook & { + body: { cartId: string } +} -export type CheckoutHandlers = { - getCheckout: GetCheckoutHandler - submitCheckout?: SubmitCheckoutHandler +export type CheckoutHandlers = { + getCheckout: GetCheckoutHandler + submitCheckout?: SubmitCheckoutHandler } -export type CheckoutSchema = { +export type CheckoutSchema = { endpoint: { options: {} - handlers: CheckoutHandlers + handlers: CheckoutHandlers } } diff --git a/packages/commerce/src/types/common.ts b/packages/commerce/src/types/common.ts index 06908c464a..d63dfc0b98 100644 --- a/packages/commerce/src/types/common.ts +++ b/packages/commerce/src/types/common.ts @@ -1,16 +1,36 @@ -export type Discount = { - // The value of the discount, can be an amount or percentage +export interface Discount { + /** + * The value of the discount, can be an amount or percentage. + */ value: number } -export type Measurement = { +export interface Measurement { + /** + * The measurement's value. + */ value: number + /** + * The measurement's unit, such as "KILOGRAMS", "GRAMS", "POUNDS" & "OOUNCES". + */ unit: 'KILOGRAMS' | 'GRAMS' | 'POUNDS' | 'OUNCES' } -export type Image = { +export interface Image { + /** + * The URL of the image. + */ url: string - altText?: string + /** + * A word or phrase that describes the content of an image. + */ + alt?: string + /** + * The image's width. + */ width?: number + /** + * The image's height. + */ height?: number } diff --git a/packages/commerce/src/types/customer/address.ts b/packages/commerce/src/types/customer/address.ts index 8dc6ffc0d7..ec4aace501 100644 --- a/packages/commerce/src/types/customer/address.ts +++ b/packages/commerce/src/types/customer/address.ts @@ -1,111 +1,123 @@ export interface Address { + /** + * The unique identifier for the address. + */ id: string + /** + * The customer's first name. + */ mask: string } export interface AddressFields { + /** + * The type of address. + * @example "billing, shipping" + */ type: string + /** + * The customer's first name. + */ firstName: string + /** + * The customer's last name. + */ lastName: string + /** + * Company name. + */ company: string + /** + * The customer's billing address street number. + */ streetNumber: string + /** + * The customer's billing address apartment number. + */ apartments: string + /** + * The customer's billing address zip code. + */ zipCode: string + /** + * The customer's billing address city. + */ city: string + /** + * The customer's billing address country. + */ country: string } -export type CustomerAddressTypes = { - address?: Address - fields: AddressFields -} +/** + * Hooks for managing a customer's addresses. + */ -export type GetAddressesHook< - T extends CustomerAddressTypes = CustomerAddressTypes -> = { - data: T['address'][] | null +export type GetAddressesHook = { + data: Address[] | null input: {} fetcherInput: { cartId?: string } swrState: { isEmpty: boolean } } -export type AddItemHook = - { - data: T['address'] - input?: T['fields'] - fetcherInput: T['fields'] - body: { item: T['fields'] } - actionInput: T['fields'] - } +export type AddItemHook = { + data: Address + input?: AddressFields + fetcherInput: AddressFields + body: { item: AddressFields } + actionInput: AddressFields +} -export type UpdateItemHook< - T extends CustomerAddressTypes = CustomerAddressTypes -> = { - data: T['address'] | null - input: { item?: T['fields']; wait?: number } - fetcherInput: { itemId: string; item: T['fields'] } - body: { itemId: string; item: T['fields'] } - actionInput: T['fields'] & { id: string } +export type UpdateItemHook = { + data: Address | null + input: { item?: AddressFields; wait?: number } + fetcherInput: { itemId: string; item: AddressFields } + body: { itemId: string; item: AddressFields } + actionInput: AddressFields & { id: string } } -export type RemoveItemHook< - T extends CustomerAddressTypes = CustomerAddressTypes -> = { - data: T['address'] | null - input: { item?: T['address'] } +export type RemoveItemHook = { + data: Address | null | undefined + input: { item?: Address } fetcherInput: { itemId: string } body: { itemId: string } actionInput: { id: string } } -export type CustomerAddressHooks< - T extends CustomerAddressTypes = CustomerAddressTypes -> = { - getAddresses: GetAddressesHook - addItem: AddItemHook - updateItem: UpdateItemHook - removeItem: RemoveItemHook +export type CustomerAddressHooks = { + getAddresses: GetAddressesHook + addItem: AddItemHook + updateItem: UpdateItemHook + removeItem: RemoveItemHook } -export type AddressHandler< - T extends CustomerAddressTypes = CustomerAddressTypes -> = GetAddressesHook & { - body: { cartId?: string } -} +/** + * API endpoints for managing a customer's addresses. + */ -export type AddItemHandler< - T extends CustomerAddressTypes = CustomerAddressTypes -> = AddItemHook & { +export type AddItemHandler = AddItemHook & { body: { cartId: string } } -export type UpdateItemHandler< - T extends CustomerAddressTypes = CustomerAddressTypes -> = UpdateItemHook & { - data: T['address'] +export type UpdateItemHandler = UpdateItemHook & { + data: Address body: { cartId: string } } -export type RemoveItemHandler< - T extends CustomerAddressTypes = CustomerAddressTypes -> = RemoveItemHook & { +export type RemoveItemHandler = RemoveItemHook & { body: { cartId: string } } -export type CustomerAddressHandlers< - T extends CustomerAddressTypes = CustomerAddressTypes -> = { - getAddresses: GetAddressesHook - addItem: AddItemHandler - updateItem: UpdateItemHandler - removeItem: RemoveItemHandler +export type CustomerAddressHandlers = { + getAddresses: GetAddressesHook + addItem: AddItemHandler + updateItem: UpdateItemHandler + removeItem: RemoveItemHandler } -export type CustomerAddressSchema< - T extends CustomerAddressTypes = CustomerAddressTypes -> = { +export type CustomerAddressSchema = { endpoint: { options: {} - handlers: CustomerAddressHandlers + handlers: CustomerAddressHandlers } } diff --git a/packages/commerce/src/types/customer/card.ts b/packages/commerce/src/types/customer/card.ts index e9b220dcca..11956ffccc 100644 --- a/packages/commerce/src/types/customer/card.ts +++ b/packages/commerce/src/types/customer/card.ts @@ -1,102 +1,139 @@ export interface Card { + /** + * Unique identifier for the card. + */ id: string + /** + * Masked card number. Contains only the last 4 digits. + * @example "4242" + */ mask: string + /** + * The card's brand. + * @example "Visa, Mastercard, etc." + */ provider: string } +/** + * The fields required to create a new card. + */ export interface CardFields { + /** + * Name on the card. + */ cardHolder: string + /** + * The card's number, consisting of 16 digits. + */ cardNumber: string + /** + * The card's expiry month and year, in the format MM/YY. + * @example "01/25" + */ cardExpireDate: string + /** + * The card's security code, consisting of 3 digits. + */ cardCvc: string + /** + * The customer's first name. + */ firstName: string + /** + * The customer's last name. + */ lastName: string + /** + * Company name. + */ company: string + /** + * The customer's billing address street number. + */ streetNumber: string + /** + * The customer's billing address zip code. + */ zipCode: string + /** + * The customer's billing address city. + */ city: string + /** + * The customer's billing address country. + */ country: string } -export type CustomerCardTypes = { - card?: Card - fields: CardFields -} +/** + * Hooks for managing a customer's cards. + */ -export type GetCardsHook = { - data: T['card'][] | null +export type GetCardsHook = { + data: Card[] | null input: {} fetcherInput: { cartId?: string } swrState: { isEmpty: boolean } } -export type AddItemHook = { - data: T['card'] - input?: T['fields'] - fetcherInput: T['fields'] - body: { item: T['fields'] } - actionInput: T['fields'] +export type AddItemHook = { + data: Card + input?: CardFields + fetcherInput: CardFields + body: { item: CardFields } + actionInput: CardFields } -export type UpdateItemHook = { - data: T['card'] | null - input: { item?: T['fields']; wait?: number } - fetcherInput: { itemId: string; item: T['fields'] } - body: { itemId: string; item: T['fields'] } - actionInput: T['fields'] & { id: string } +export type UpdateItemHook = { + data: Card | null | undefined + input: { item?: CardFields; wait?: number } + fetcherInput: { itemId: string; item: CardFields } + body: { itemId: string; item: CardFields } + actionInput: CardFields & { id: string } } -export type RemoveItemHook = { - data: T['card'] | null - input: { item?: T['card'] } +export type RemoveItemHook = { + data: Card | null | undefined + input: { item?: Card } fetcherInput: { itemId: string } body: { itemId: string } actionInput: { id: string } } -export type CustomerCardHooks = - { - getCards: GetCardsHook - addItem: AddItemHook - updateItem: UpdateItemHook - removeItem: RemoveItemHook - } - -export type CardsHandler = - GetCardsHook & { - body: { cartId?: string } - } +export interface CustomerCardHooks { + getCards: GetCardsHook + addItem: AddItemHook + updateItem: UpdateItemHook + removeItem: RemoveItemHook +} -export type AddItemHandler = - AddItemHook & { - body: { cartId: string } - } +/** + * Customer card API handlers. + */ +export type AddItemHandler = AddItemHook & { + body: { cartId: string } +} -export type UpdateItemHandler = - UpdateItemHook & { - data: T['card'] - body: { cartId: string } - } +export type UpdateItemHandler = UpdateItemHook & { + data: Card + body: { cartId: string } +} -export type RemoveItemHandler = - RemoveItemHook & { - body: { cartId: string } - } +export type RemoveItemHandler = RemoveItemHook & { + body: { cartId: string } +} -export type CustomerCardHandlers< - T extends CustomerCardTypes = CustomerCardTypes -> = { - getCards: GetCardsHook - addItem: AddItemHandler - updateItem: UpdateItemHandler - removeItem: RemoveItemHandler +export type CustomerCardHandlers = { + getCards: GetCardsHook + addItem: AddItemHandler + updateItem: UpdateItemHandler + removeItem: RemoveItemHandler } -export type CustomerCardSchema< - T extends CustomerCardTypes = CustomerCardTypes -> = { +export type CustomerCardSchema = { endpoint: { options: {} - handlers: CustomerCardHandlers + handlers: CustomerCardHandlers } } diff --git a/packages/commerce/src/types/customer/index.ts b/packages/commerce/src/types/customer/index.ts index f0b210f625..89a963a296 100644 --- a/packages/commerce/src/types/customer/index.ts +++ b/packages/commerce/src/types/customer/index.ts @@ -1,24 +1,53 @@ export * as Card from './card' export * as Address from './address' -// TODO: define this type -export type Customer = any - -export type CustomerTypes = { - customer: Customer +export interface Customer { + /** + * The unique identifier for the customer. + */ + id: string + /** + * The customer's first name. + */ + firstName: string + /** + * The customer's last name. + */ + lastName: string + /** + * The customer's email address. + */ + email?: string + /** + * The customer's phone number. + * @optional + */ + phone?: string + /** + * The customer's company name. + */ + company?: string + /** + * The customer's notes. + */ + notes?: string + /** + * Indicates wathever the customer accepts marketing, such as email newsletters. + */ + acceptsMarketing?: boolean } -export type CustomerHook = { - data: T['customer'] | null - fetchData: { customer: T['customer'] } | null +export type CustomerHook = { + data: Customer | null | undefined + fetchData: { customer: Customer } | null } -export type CustomerSchema = { +export type CustomerSchema = { endpoint: { options: {} handlers: { getLoggedInCustomer: { - data: { customer: T['customer'] } | null + data: { customer: Customer } | null } } } diff --git a/packages/commerce/src/types/login.ts b/packages/commerce/src/types/login.ts index b6ef228e09..e032b18279 100644 --- a/packages/commerce/src/types/login.ts +++ b/packages/commerce/src/types/login.ts @@ -1,24 +1,26 @@ -export type LoginBody = { +export interface LoginBody { + /** + * The user's email address. + */ email: string + /** + * The user's password. + */ password: string } -export type LoginTypes = { - body: LoginBody -} - -export type LoginHook = { +export type LoginHook = { data: null actionInput: LoginBody fetcherInput: LoginBody - body: T['body'] + body: LoginBody } -export type LoginSchema = { +export type LoginSchema = { endpoint: { options: {} handlers: { - login: LoginHook + login: LoginHook } } } diff --git a/packages/commerce/src/types/logout.ts b/packages/commerce/src/types/logout.ts index a7240052f8..df981b06e5 100644 --- a/packages/commerce/src/types/logout.ts +++ b/packages/commerce/src/types/logout.ts @@ -1,17 +1,15 @@ -export type LogoutTypes = { - body: { redirectTo?: string } -} - -export type LogoutHook = { +export type LogoutHook = { data: null - body: T['body'] + body: { + redirectTo?: string + } } -export type LogoutSchema = { +export type LogoutSchema = { endpoint: { options: {} handlers: { - logout: LogoutHook + logout: LogoutHook } } } diff --git a/packages/commerce/src/types/page.ts b/packages/commerce/src/types/page.ts index 89f82c1a6e..24c6ae8c1d 100644 --- a/packages/commerce/src/types/page.ts +++ b/packages/commerce/src/types/page.ts @@ -1,28 +1,43 @@ -// TODO: define this type export type Page = { - // ID of the Web page. + /** + * The unique identifier for the page. + */ id: string - // Page name, as displayed on the storefront. + /** + * Page name, as displayed on the storefront. + */ name: string - // Relative URL on the storefront for this page. + /** + * Relative URL on the storefront for this page. + */ url?: string - // HTML or variable that populates this page’s `` element, in default/desktop view. Required in POST if page type is `raw`. + /** + * HTML or variable that populates this page’s `` element, in default/desktop view. Required in POST if page type is `raw`. + */ body: string - // If true, this page appears in the storefront’s navigation menu. + /** + * If true, this page appears in the storefront’s navigation menu. + */ is_visible?: boolean - // Order in which this page should display on the storefront. (Lower integers specify earlier display.) + /** + * Order in which this page should display on the storefront. (Lower integers specify earlier display.) + */ sort_order?: number } -export type PageTypes = { - page: Page +/** + * Operation to get all pages. + */ +export type GetAllPagesOperation = { + data: { pages: Page[] } } -export type GetAllPagesOperation = { - data: { pages: T['page'][] } -} - -export type GetPageOperation = { - data: { page?: T['page'] } - variables: { id: string } +export type GetPageOperation = { + data: { page?: Page } + variables: { + /** + * The unique identifier of the page. + */ + id: string + } } diff --git a/packages/commerce/src/types/product.ts b/packages/commerce/src/types/product.ts index fb48ba00b4..2f6c34acb8 100644 --- a/packages/commerce/src/types/product.ts +++ b/packages/commerce/src/types/product.ts @@ -1,91 +1,207 @@ -export type ProductImage = { - url: string - alt?: string -} +import { Image } from './common' -export type ProductPrice = { +export interface ProductPrice { + /** + * The price after all discounts are applied. + */ value: number + /** + * The currency code for the price. This is a 3-letter ISO 4217 code. + * @example USD + */ currencyCode?: 'USD' | 'EUR' | 'ARS' | 'GBP' | string + /** + * The retail price of the product. This can be used to mark a product as on sale, when `retailPrice` is higher than the price a.k.a `value`. + */ retailPrice?: number - salePrice?: number - listPrice?: number - extendedSalePrice?: number - extendedListPrice?: number } -export type ProductOption = { +export interface ProductOption { __typename?: 'MultipleChoiceOption' + /** + * The unique identifier for the option. + */ id: string + /** + * The product option’s name. + * @example `Color` or `Size` + */ displayName: string + /** + * List of option values. + * @example `["Red", "Green", "Blue"]` + */ values: ProductOptionValues[] } -export type ProductOptionValues = { +export interface ProductOptionValues { + /** + * A string that uniquely identifies the option value. + */ label: string + /** + * List of hex colors used to display the actual colors in the swatches instead of the name. + */ hexColors?: string[] } -export type ProductVariant = { - id: string | number +export interface ProductVariant { + /** + * The unique identifier for the variant. + */ + id: string + /** + * The SKU (stock keeping unit) associated with the product variant. + */ + sku?: string + /** + * The product variant’s name, or the product's name. + */ + name?: string + /** + * List of product options. + */ options: ProductOption[] + /** + * The product variant’s price after all discounts are applied. + */ + price?: ProductPrice + /** + * The retail price of the product. This can be used to mark a product as on sale, when `retailPrice` is higher than the `price`. + */ + retailPrice?: ProductPrice + /** + * Indicates if the variant is available for sale. + */ availableForSale?: boolean + /** + * Whether a customer needs to provide a shipping address when placing an order for the product variant. + */ + requiresShipping?: boolean + /** + * The image associated with the variant. + */ + image?: Image } -export type Product = { +export interface Product { + /** + * The unique identifier for the product. + */ id: string + /** + * The name of the product. + */ name: string + /** + * Stripped description of the product, single line. + */ description: string + /** + * The description of the product, complete with HTML formatting. + */ descriptionHtml?: string + /** + * The SKU (stock keeping unit) associated with the product. + */ sku?: string + /** + * A human-friendly unique string for the product, automatically generated from its title. + */ slug?: string + /** + * Relative URL on the storefront for the product. + */ path?: string - images: ProductImage[] + /** + * List of images associated with the product. + */ + images: Image[] + /** + * List of the product’s variants. + */ variants: ProductVariant[] + /** + * The product's base price. Could be the minimum value, or default variant price. + */ price: ProductPrice + /** + * List of product's options. + */ options: ProductOption[] + /** + * The product’s vendor name. + */ vendor?: string } -export type SearchProductsBody = { +export interface SearchProductsBody { + /** + * The search query string to filter the products by. + */ search?: string - categoryId?: string | number - brandId?: string | number + /** + * The category ID to filter the products by. + */ + categoryId?: string + /** + * The brand ID to filter the products by. + */ + brandId?: string + /** + * The sort key to sort the products by. + * @example 'trending-desc' | 'latest-desc' | 'price-asc' | 'price-desc' + */ sort?: string + /** + * The locale code, used to localize the product data (if the provider supports it). + */ locale?: string } -export type ProductTypes = { - product: Product - searchBody: SearchProductsBody -} - -export type SearchProductsHook = { +/** + * Fetches a list of products based on the given search criteria. + */ +export type SearchProductsHook = { data: { - products: T['product'][] + /** + * List of products matching the query. + */ + products: Product[] + /** + * Indicates if there are any products matching the query. + */ found: boolean } - body: T['searchBody'] - input: T['searchBody'] - fetcherInput: T['searchBody'] + body: SearchProductsBody + input: SearchProductsBody + fetcherInput: SearchProductsBody } -export type ProductsSchema = { +/** + * Product API schema + */ + +export type ProductsSchema = { endpoint: { options: {} handlers: { - getProducts: SearchProductsHook + getProducts: SearchProductsHook } } } -export type GetAllProductPathsOperation = - { - data: { products: Pick[] } - variables: { first?: number } - } +/** + * Product operations + */ + +export type GetAllProductPathsOperation = { + data: { products: Pick[] } + variables: { first?: number } +} -export type GetAllProductsOperation = { - data: { products: T['product'][] } +export type GetAllProductsOperation = { + data: { products: Product[] } variables: { relevance?: 'featured' | 'best_selling' | 'newest' ids?: string[] @@ -93,7 +209,7 @@ export type GetAllProductsOperation = { } } -export type GetProductOperation = { - data: { product?: T['product'] } +export type GetProductOperation = { + data: { product?: Product } variables: { path: string; slug?: never } | { path?: never; slug: string } } diff --git a/packages/commerce/src/types/signup.ts b/packages/commerce/src/types/signup.ts index 4e23da6c05..17754cf150 100644 --- a/packages/commerce/src/types/signup.ts +++ b/packages/commerce/src/types/signup.ts @@ -1,26 +1,34 @@ -export type SignupBody = { +export interface SignupBody { + /** + * The user's first name. + */ firstName: string + /** + * The user's last name. + */ lastName: string + /** + * The user's email address. + */ email: string + /** + * The user's password. + */ password: string } -export type SignupTypes = { - body: SignupBody -} - -export type SignupHook = { +export type SignupHook = { data: null - body: T['body'] - actionInput: T['body'] - fetcherInput: T['body'] + body: SignupBody + actionInput: SignupBody + fetcherInput: SignupBody } -export type SignupSchema = { +export type SignupSchema = { endpoint: { options: {} handlers: { - signup: SignupHook + signup: SignupHook } } } diff --git a/packages/commerce/src/types/site.ts b/packages/commerce/src/types/site.ts index 73c7dddd2c..3552db08f0 100644 --- a/packages/commerce/src/types/site.ts +++ b/packages/commerce/src/types/site.ts @@ -1,20 +1,51 @@ -export type Category = { +export interface Category { + /** + * Unique identifier for the category. + */ id: string + /** + * Name of the category. + */ name: string + /** + * A human-friendly unique string for the category, automatically generated from its name. + * @example "t-shirts" + */ slug: string + /** + * Relative URL on the storefront for the category. + * @example /t-shirts + */ path: string } -export type Brand = any - -export type SiteTypes = { - category: Category - brand: Brand +export interface Brand { + /** + * Unique identifier for the brand. + */ + id: string + /** + * Name of the brand. + */ + name: string + /** + * A human-friendly unique string for the category, automatically generated from its name. + * @example "acme" + */ + slug: string + /** + * Relative URL on the storefront for this brand. + * @example "/acme" + */ + path: string } -export type GetSiteInfoOperation = { +/** + * Operation to get site information. This includes categories and brands. + */ +export type GetSiteInfoOperation = { data: { - categories: T['category'][] - brands: T['brand'][] + categories: Category[] + brands: Brand[] } } diff --git a/packages/commerce/src/types/wishlist.ts b/packages/commerce/src/types/wishlist.ts index b3759849c5..5c5e0d1ea1 100644 --- a/packages/commerce/src/types/wishlist.ts +++ b/packages/commerce/src/types/wishlist.ts @@ -1,60 +1,97 @@ -// TODO: define this type -export type Wishlist = any +import { Product } from './product' -export type WishlistItemBody = { - variantId: string | number +export interface WishlistItem { + /** + * The unique identifier for the item. + */ + id: string + /** + * The unique identifier for the product associated with the wishlist item. + */ productId: string + /** + * The unique identifier for the product variant associated with the wishlist item. + */ + variantId: string + /** + * The product associated with the wishlist item. + */ + product: Product } -export type WishlistTypes = { - wishlist: Wishlist - itemBody: WishlistItemBody +export interface Wishlist { + /** + * The unique identifier for the wishlist. + */ + id: string + /** + * List of items in the wishlist. + */ + items: WishlistItem[] + + /** + * Some providers require a token to add an item to a wishlist + */ + token?: string +} + +export interface WishlistItemBody { + /** + * The unique identifier for the product variant to associate with the wishlist. + */ + variantId: string + /** + * The unique identifier for the product to associate with the wishlist. + */ + productId: string + /** + * Some providers require to provide a token to make a request + */ + wishlistToken?: string } -export type GetWishlistHook = { - data: T['wishlist'] | null +export type GetWishlistHook = { + data: Wishlist | null | undefined body: { includeProducts?: boolean } input: { includeProducts?: boolean } fetcherInput: { customerId: string; includeProducts?: boolean } swrState: { isEmpty: boolean } } -export type AddItemHook = { - data: T['wishlist'] - body: { item: T['itemBody'] } - fetcherInput: { item: T['itemBody'] } - actionInput: T['itemBody'] +export type AddItemHook = { + data: Wishlist | null | undefined + body: { item: WishlistItemBody } + fetcherInput: { item: WishlistItemBody } + actionInput: WishlistItemBody } -export type RemoveItemHook = { - data: T['wishlist'] | null - body: { itemId: string } - fetcherInput: { itemId: string } +export type RemoveItemHook = { + data: Wishlist | null | undefined + body: { itemId: string; wishlistToken?: string } + fetcherInput: { itemId: string; wishlistToken?: string } actionInput: { id: string } input: { wishlist?: { includeProducts?: boolean } } } -export type WishlistSchema = { +export type WishlistSchema = { endpoint: { options: {} handlers: { - getWishlist: GetWishlistHook & { - data: T['wishlist'] | null + getWishlist: GetWishlistHook & { + data: Wishlist | null body: { customerToken?: string } } - addItem: AddItemHook & { + addItem: AddItemHook & { body: { customerToken?: string } } - removeItem: RemoveItemHook & { + removeItem: RemoveItemHook & { body: { customerToken?: string } } } } } -export type GetCustomerWishlistOperation< - T extends WishlistTypes = WishlistTypes -> = { - data: { wishlist?: T['wishlist'] } +export type GetCustomerWishlistOperation = { + data: { wishlist?: Wishlist } variables: { customerId: string } } diff --git a/packages/commerce/src/wishlist/use-add-item.tsx b/packages/commerce/src/wishlist/use-add-item.tsx index f464be1ca6..3debffe42e 100644 --- a/packages/commerce/src/wishlist/use-add-item.tsx +++ b/packages/commerce/src/wishlist/use-add-item.tsx @@ -5,7 +5,7 @@ import type { AddItemHook } from '../types/wishlist' import type { Provider } from '..' export type UseAddItem< - H extends MutationHook> = MutationHook + H extends MutationHook = MutationHook > = ReturnType export const fetcher = mutationFetcher diff --git a/packages/commerce/src/wishlist/use-remove-item.tsx b/packages/commerce/src/wishlist/use-remove-item.tsx index 4419c17af1..2592011f7f 100644 --- a/packages/commerce/src/wishlist/use-remove-item.tsx +++ b/packages/commerce/src/wishlist/use-remove-item.tsx @@ -5,7 +5,7 @@ import type { RemoveItemHook } from '../types/wishlist' import type { Provider } from '..' export type UseRemoveItem< - H extends MutationHook> = MutationHook + H extends MutationHook = MutationHook > = ReturnType export const fetcher: HookFetcherFn = mutationFetcher diff --git a/packages/commerce/src/wishlist/use-wishlist.tsx b/packages/commerce/src/wishlist/use-wishlist.tsx index 672203f79f..3d3eede0ff 100644 --- a/packages/commerce/src/wishlist/use-wishlist.tsx +++ b/packages/commerce/src/wishlist/use-wishlist.tsx @@ -5,7 +5,7 @@ import type { GetWishlistHook } from '../types/wishlist' import type { Provider } from '..' export type UseWishlist< - H extends SWRHook> = SWRHook + H extends SWRHook = SWRHook > = ReturnType export const fetcher: HookFetcherFn = SWRFetcher diff --git a/packages/commercejs/src/api/endpoints/checkout/index.ts b/packages/commercejs/src/api/endpoints/checkout/index.ts index 1072902e6d..6a4eb4864b 100644 --- a/packages/commercejs/src/api/endpoints/checkout/index.ts +++ b/packages/commercejs/src/api/endpoints/checkout/index.ts @@ -1,6 +1,6 @@ import { GetAPISchema, createEndpoint } from '@vercel/commerce/api' import checkoutEndpoint from '@vercel/commerce/api/endpoints/checkout' -import type { CheckoutSchema } from '../../../types/checkout' +import type { CheckoutSchema } from '@vercel/commerce/types/checkout' import type { CommercejsAPI } from '../..' import submitCheckout from './submit-checkout' diff --git a/packages/commercejs/src/api/endpoints/login/index.ts b/packages/commercejs/src/api/endpoints/login/index.ts index a6dbb44322..a47d8e63f4 100644 --- a/packages/commercejs/src/api/endpoints/login/index.ts +++ b/packages/commercejs/src/api/endpoints/login/index.ts @@ -1,6 +1,6 @@ import { GetAPISchema, createEndpoint } from '@vercel/commerce/api' import loginEndpoint from '@vercel/commerce/api/endpoints/login' -import type { LoginSchema } from '../../../types/login' +import type { LoginSchema } from '@vercel/commerce/types/login' import type { CommercejsAPI } from '../..' import login from './login' diff --git a/packages/commercejs/src/api/operations/get-all-pages.ts b/packages/commercejs/src/api/operations/get-all-pages.ts index c8c9e41b22..ae6e6c0040 100644 --- a/packages/commercejs/src/api/operations/get-all-pages.ts +++ b/packages/commercejs/src/api/operations/get-all-pages.ts @@ -1,5 +1,5 @@ import type { CommercejsConfig } from '..' -import { GetAllPagesOperation } from '../../types/page' +import { GetAllPagesOperation } from '@vercel/commerce/types/page' export type Page = { url: string } export type GetAllPagesResult = { pages: Page[] } diff --git a/packages/commercejs/src/api/operations/get-all-product-paths.ts b/packages/commercejs/src/api/operations/get-all-product-paths.ts index 03b7eee964..2d81e9ad63 100644 --- a/packages/commercejs/src/api/operations/get-all-product-paths.ts +++ b/packages/commercejs/src/api/operations/get-all-product-paths.ts @@ -1,9 +1,5 @@ import type { OperationContext } from '@vercel/commerce/api/operations' -import type { - GetAllProductPathsOperation, - CommercejsProduct, -} from '../../types/product' - +import type { GetAllProductPathsOperation } from '@vercel/commerce/types/product' import type { CommercejsConfig, Provider } from '..' export type GetAllProductPathsResult = { @@ -22,7 +18,7 @@ export default function getAllProductPathsOperation({ const { data } = await sdkFetch('products', 'list') // Match a path for every product retrieved - const productPaths = data.map(({ permalink }: CommercejsProduct) => ({ + const productPaths = data.map(({ permalink }: { permalink: string }) => ({ path: `/${permalink}`, })) diff --git a/packages/commercejs/src/api/operations/get-all-products.ts b/packages/commercejs/src/api/operations/get-all-products.ts index 485ea22eeb..244a590b82 100644 --- a/packages/commercejs/src/api/operations/get-all-products.ts +++ b/packages/commercejs/src/api/operations/get-all-products.ts @@ -1,5 +1,5 @@ import type { OperationContext } from '@vercel/commerce/api/operations' -import type { GetAllProductsOperation } from '../../types/product' +import type { GetAllProductsOperation } from '@vercel/commerce/types/product' import type { CommercejsConfig, Provider } from '../index' import { normalizeProduct } from '../../utils/normalize-product' diff --git a/packages/commercejs/src/api/operations/get-page.ts b/packages/commercejs/src/api/operations/get-page.ts index f4b69c90df..e403d16605 100644 --- a/packages/commercejs/src/api/operations/get-page.ts +++ b/packages/commercejs/src/api/operations/get-page.ts @@ -1,4 +1,4 @@ -import { GetPageOperation } from '../../types/page' +import { GetPageOperation } from '@vercel/commerce/types/page' export type Page = any export type GetPageResult = { page?: Page } diff --git a/packages/commercejs/src/api/operations/get-product.ts b/packages/commercejs/src/api/operations/get-product.ts index c8fa5901bd..7f11310f98 100644 --- a/packages/commercejs/src/api/operations/get-product.ts +++ b/packages/commercejs/src/api/operations/get-product.ts @@ -1,5 +1,5 @@ import type { OperationContext } from '@vercel/commerce/api/operations' -import type { GetProductOperation } from '../../types/product' +import type { GetProductOperation } from '@vercel/commerce/types/product' import type { CommercejsConfig, Provider } from '../index' import { normalizeProduct } from '../../utils/normalize-product' diff --git a/packages/commercejs/src/api/operations/get-site-info.ts b/packages/commercejs/src/api/operations/get-site-info.ts index 0b4046d7cc..3b768e6111 100644 --- a/packages/commercejs/src/api/operations/get-site-info.ts +++ b/packages/commercejs/src/api/operations/get-site-info.ts @@ -1,5 +1,8 @@ import type { OperationContext } from '@vercel/commerce/api/operations' -import type { Category, GetSiteInfoOperation } from '../../types/site' +import type { + Category, + GetSiteInfoOperation, +} from '@vercel/commerce/types/site' import { normalizeCategory } from '../../utils/normalize-category' import type { CommercejsConfig, Provider } from '../index' diff --git a/packages/commercejs/src/cart/use-add-item.tsx b/packages/commercejs/src/cart/use-add-item.tsx index 3bbad1147f..b8fb8cb1c1 100644 --- a/packages/commercejs/src/cart/use-add-item.tsx +++ b/packages/commercejs/src/cart/use-add-item.tsx @@ -2,7 +2,7 @@ import type { AddItemHook } from '@vercel/commerce/types/cart' import type { MutationHook } from '@vercel/commerce/utils/types' import { useCallback } from 'react' import useAddItem, { UseAddItem } from '@vercel/commerce/cart/use-add-item' -import type { CommercejsCart } from '../types/cart' +import type { CommercejsCart } from '../types' import { normalizeCart } from '../utils/normalize-cart' import useCart from './use-cart' diff --git a/packages/commercejs/src/cart/use-cart.tsx b/packages/commercejs/src/cart/use-cart.tsx index 57592ec378..7938c27f9f 100644 --- a/packages/commercejs/src/cart/use-cart.tsx +++ b/packages/commercejs/src/cart/use-cart.tsx @@ -2,7 +2,7 @@ import { useMemo } from 'react' import type { GetCartHook } from '@vercel/commerce/types/cart' import { SWRHook } from '@vercel/commerce/utils/types' import useCart, { UseCart } from '@vercel/commerce/cart/use-cart' -import type { CommercejsCart } from '../types/cart' +import type { CommercejsCart } from '../types' import { normalizeCart } from '../utils/normalize-cart' export default useCart as UseCart diff --git a/packages/commercejs/src/cart/use-remove-item.tsx b/packages/commercejs/src/cart/use-remove-item.tsx index c9e57872d4..c06ac6d78b 100644 --- a/packages/commercejs/src/cart/use-remove-item.tsx +++ b/packages/commercejs/src/cart/use-remove-item.tsx @@ -1,8 +1,10 @@ import { useCallback } from 'react' import type { MutationHook } from '@vercel/commerce/utils/types' import type { RemoveItemHook } from '@vercel/commerce/types/cart' -import useRemoveItem, { UseRemoveItem } from '@vercel/commerce/cart/use-remove-item' -import type { CommercejsCart } from '../types/cart' +import useRemoveItem, { + UseRemoveItem, +} from '@vercel/commerce/cart/use-remove-item' +import type { CommercejsCart } from '../types' import { normalizeCart } from '../utils/normalize-cart' import useCart from './use-cart' diff --git a/packages/commercejs/src/cart/use-update-item.tsx b/packages/commercejs/src/cart/use-update-item.tsx index 1546be036b..d9c38c60b4 100644 --- a/packages/commercejs/src/cart/use-update-item.tsx +++ b/packages/commercejs/src/cart/use-update-item.tsx @@ -1,4 +1,8 @@ -import type { UpdateItemHook, LineItem } from '@vercel/commerce/types/cart' +import type { + UpdateItemHook, + LineItem, + Cart, +} from '@vercel/commerce/types/cart' import type { HookFetcherContext, MutationHookContext, @@ -6,8 +10,10 @@ import type { import { ValidationError } from '@vercel/commerce/utils/errors' import debounce from 'lodash.debounce' import { useCallback } from 'react' -import useUpdateItem, { UseUpdateItem } from '@vercel/commerce/cart/use-update-item' -import type { CommercejsCart } from '../types/cart' +import useUpdateItem, { + UseUpdateItem, +} from '@vercel/commerce/cart/use-update-item' +import type { CommercejsCart } from '../types' import { normalizeCart } from '../utils/normalize-cart' import useCart from './use-cart' diff --git a/packages/commercejs/src/customer/address/use-add-item.tsx b/packages/commercejs/src/customer/address/use-add-item.tsx index 0f02059b1f..4f85c84726 100644 --- a/packages/commercejs/src/customer/address/use-add-item.tsx +++ b/packages/commercejs/src/customer/address/use-add-item.tsx @@ -1,25 +1,17 @@ -import type { AddItemHook } from '@vercel/commerce/types/customer/address' -import type { MutationHook } from '@vercel/commerce/utils/types' -import { useCallback } from 'react' -import useAddItem, { UseAddItem } from '@vercel/commerce/customer/address/use-add-item' -import { useCheckoutContext } from '@components/checkout/context' +import useAddItem, { + UseAddItem, +} from '@vercel/commerce/customer/address/use-add-item' +import { MutationHook } from '@vercel/commerce/utils/types' export default useAddItem as UseAddItem -export const handler: MutationHook = { +export const handler: MutationHook = { fetchOptions: { - query: '_', - method: '_', + query: '', }, - useHook: () => - function useHook() { - const { setAddressFields } = useCheckoutContext() - return useCallback( - async function addItem(input) { - setAddressFields(input) - return undefined - }, - [setAddressFields] - ) - }, + async fetcher({ input, options, fetch }) {}, + useHook: + ({ fetch }) => + () => + async () => ({}), } diff --git a/packages/commercejs/src/customer/card/use-add-item.tsx b/packages/commercejs/src/customer/card/use-add-item.tsx index d4c179b185..77d149eff7 100644 --- a/packages/commercejs/src/customer/card/use-add-item.tsx +++ b/packages/commercejs/src/customer/card/use-add-item.tsx @@ -1,25 +1,17 @@ -import type { AddItemHook } from '@vercel/commerce/types/customer/card' -import type { MutationHook } from '@vercel/commerce/utils/types' -import { useCallback } from 'react' -import useAddItem, { UseAddItem } from '@vercel/commerce/customer/card/use-add-item' -import { useCheckoutContext } from '@components/checkout/context' +import useAddItem, { + UseAddItem, +} from '@vercel/commerce/customer/card/use-add-item' +import { MutationHook } from '@vercel/commerce/utils/types' export default useAddItem as UseAddItem -export const handler: MutationHook = { +export const handler: MutationHook = { fetchOptions: { - url: '_', - method: '_', + query: '', }, - useHook: () => - function useHook() { - const { setCardFields } = useCheckoutContext() - return useCallback( - async function addItem(input) { - setCardFields(input) - return undefined - }, - [setCardFields] - ) - }, + async fetcher({ input, options, fetch }) {}, + useHook: + ({ fetch }) => + () => + async () => ({}), } diff --git a/packages/commercejs/src/customer/use-customer.tsx b/packages/commercejs/src/customer/use-customer.tsx index 4906223fd9..57d8f702bd 100644 --- a/packages/commercejs/src/customer/use-customer.tsx +++ b/packages/commercejs/src/customer/use-customer.tsx @@ -1,9 +1,11 @@ import Cookies from 'js-cookie' import { decode } from 'jsonwebtoken' import { SWRHook } from '@vercel/commerce/utils/types' -import useCustomer, { UseCustomer } from '@vercel/commerce/customer/use-customer' +import useCustomer, { + UseCustomer, +} from '@vercel/commerce/customer/use-customer' import { CUSTOMER_COOKIE, API_URL } from '../constants' -import type { CustomerHook } from '../types/customer' +import type { CustomerHook } from '@vercel/commerce/types/customer' export default useCustomer as UseCustomer export const handler: SWRHook = { @@ -13,12 +15,13 @@ export const handler: SWRHook = { }, async fetcher({ options, fetch }) { const token = Cookies.get(CUSTOMER_COOKIE) + if (!token) { return null } const decodedToken = decode(token) as { cid: string } - const customer = await fetch({ + const customer = await fetch({ query: options.query, method: options.method, variables: [ @@ -29,7 +32,16 @@ export const handler: SWRHook = { token, ], }) + return customer + ? { + id: customer.id, + firstName: customer.firstname, + lastName: customer.lastname, + email: customer.email, + phone: customer.phone, + } + : null }, useHook: ({ useData }) => diff --git a/packages/commercejs/src/product/use-search.tsx b/packages/commercejs/src/product/use-search.tsx index ec8ad618fe..4b43d5aa05 100644 --- a/packages/commercejs/src/product/use-search.tsx +++ b/packages/commercejs/src/product/use-search.tsx @@ -1,7 +1,7 @@ import { SWRHook } from '@vercel/commerce/utils/types' import useSearch, { UseSearch } from '@vercel/commerce/product/use-search' import { SearchProductsHook } from '@vercel/commerce/types/product' -import type { CommercejsProduct } from '../types/product' +import type { CommercejsProduct } from '../types' import { getProductSearchVariables } from '../utils/product-search' import { normalizeProduct } from '../utils/normalize-product' diff --git a/packages/commercejs/src/types.ts b/packages/commercejs/src/types.ts new file mode 100644 index 0000000000..c041acc0d9 --- /dev/null +++ b/packages/commercejs/src/types.ts @@ -0,0 +1,6 @@ +export type { Cart as CommercejsCart } from '@chec/commerce.js/types/cart' +export type { LineItem as CommercejsLineItem } from '@chec/commerce.js/types/line-item' +export type { CheckoutCapture as CommercejsCheckoutCapture } from '@chec/commerce.js/types/checkout-capture' +export type { Product as CommercejsProduct } from '@chec/commerce.js/types/product' +export type { Variant as CommercejsVariant } from '@chec/commerce.js/types/variant' +export type { Category as CommercejsCategory } from '@chec/commerce.js/types/category' diff --git a/packages/commercejs/src/types/cart.ts b/packages/commercejs/src/types/cart.ts deleted file mode 100644 index 9de68397be..0000000000 --- a/packages/commercejs/src/types/cart.ts +++ /dev/null @@ -1,4 +0,0 @@ -export * from '@vercel/commerce/types/cart' - -export type { Cart as CommercejsCart } from '@chec/commerce.js/types/cart' -export type { LineItem as CommercejsLineItem } from '@chec/commerce.js/types/line-item' diff --git a/packages/commercejs/src/types/checkout.ts b/packages/commercejs/src/types/checkout.ts deleted file mode 100644 index 970d5cfad4..0000000000 --- a/packages/commercejs/src/types/checkout.ts +++ /dev/null @@ -1,3 +0,0 @@ -export * from '@vercel/commerce/types/checkout' - -export type { CheckoutCapture as CommercejsCheckoutCapture } from '@chec/commerce.js/types/checkout-capture' diff --git a/packages/commercejs/src/types/common.ts b/packages/commercejs/src/types/common.ts deleted file mode 100644 index 23b8daa11c..0000000000 --- a/packages/commercejs/src/types/common.ts +++ /dev/null @@ -1 +0,0 @@ -export * from '@vercel/commerce/types/common' diff --git a/packages/commercejs/src/types/customer.ts b/packages/commercejs/src/types/customer.ts deleted file mode 100644 index c637055b94..0000000000 --- a/packages/commercejs/src/types/customer.ts +++ /dev/null @@ -1 +0,0 @@ -export * from '@vercel/commerce/types/customer' diff --git a/packages/commercejs/src/types/index.ts b/packages/commercejs/src/types/index.ts deleted file mode 100644 index 7ab0b7f64f..0000000000 --- a/packages/commercejs/src/types/index.ts +++ /dev/null @@ -1,25 +0,0 @@ -import * as Cart from './cart' -import * as Checkout from './checkout' -import * as Common from './common' -import * as Customer from './customer' -import * as Login from './login' -import * as Logout from './logout' -import * as Page from './page' -import * as Product from './product' -import * as Signup from './signup' -import * as Site from './site' -import * as Wishlist from './wishlist' - -export type { - Cart, - Checkout, - Common, - Customer, - Login, - Logout, - Page, - Product, - Signup, - Site, - Wishlist, -} diff --git a/packages/commercejs/src/types/login.ts b/packages/commercejs/src/types/login.ts deleted file mode 100644 index 0706a2f1fe..0000000000 --- a/packages/commercejs/src/types/login.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { LoginBody, LoginTypes } from '@vercel/commerce/types/login' -export * from '@vercel/commerce/types/login' - -export type LoginHook = { - data: null - actionInput: LoginBody - fetcherInput: LoginBody - body: T['body'] -} diff --git a/packages/commercejs/src/types/logout.ts b/packages/commercejs/src/types/logout.ts deleted file mode 100644 index 1de06f8dc8..0000000000 --- a/packages/commercejs/src/types/logout.ts +++ /dev/null @@ -1 +0,0 @@ -export * from '@vercel/commerce/types/logout' diff --git a/packages/commercejs/src/types/page.ts b/packages/commercejs/src/types/page.ts deleted file mode 100644 index 12f6b02d71..0000000000 --- a/packages/commercejs/src/types/page.ts +++ /dev/null @@ -1 +0,0 @@ -export * from '@vercel/commerce/types/page' diff --git a/packages/commercejs/src/types/product.ts b/packages/commercejs/src/types/product.ts deleted file mode 100644 index 7cdab703e6..0000000000 --- a/packages/commercejs/src/types/product.ts +++ /dev/null @@ -1,4 +0,0 @@ -export * from '@vercel/commerce/types/product' - -export type { Product as CommercejsProduct } from '@chec/commerce.js/types/product' -export type { Variant as CommercejsVariant } from '@chec/commerce.js/types/variant' diff --git a/packages/commercejs/src/types/signup.ts b/packages/commercejs/src/types/signup.ts deleted file mode 100644 index 3f0d1af5ac..0000000000 --- a/packages/commercejs/src/types/signup.ts +++ /dev/null @@ -1 +0,0 @@ -export * from '@vercel/commerce/types/signup' diff --git a/packages/commercejs/src/types/site.ts b/packages/commercejs/src/types/site.ts deleted file mode 100644 index 346278b43b..0000000000 --- a/packages/commercejs/src/types/site.ts +++ /dev/null @@ -1,3 +0,0 @@ -export * from '@vercel/commerce/types/site' - -export type { Category as CommercejsCategory } from '@chec/commerce.js/types/category' diff --git a/packages/commercejs/src/types/wishlist.ts b/packages/commercejs/src/types/wishlist.ts deleted file mode 100644 index af92d9f63e..0000000000 --- a/packages/commercejs/src/types/wishlist.ts +++ /dev/null @@ -1 +0,0 @@ -export * from '@vercel/commerce/types/wishlist' diff --git a/packages/commercejs/src/utils/normalize-cart.ts b/packages/commercejs/src/utils/normalize-cart.ts index c01ea6dea5..6bb7334be7 100644 --- a/packages/commercejs/src/utils/normalize-cart.ts +++ b/packages/commercejs/src/utils/normalize-cart.ts @@ -1,9 +1,5 @@ -import type { - Cart, - LineItem, - CommercejsCart, - CommercejsLineItem, -} from '../types/cart' +import type { Cart, LineItem } from '@vercel/commerce/types/cart' +import type { CommercejsCart, CommercejsLineItem } from '../types' type CommercejsLineItemType = CommercejsLineItem & { image: { url: string } } diff --git a/packages/commercejs/src/utils/normalize-category.ts b/packages/commercejs/src/utils/normalize-category.ts index 41900928e4..9c2c6bd91a 100644 --- a/packages/commercejs/src/utils/normalize-category.ts +++ b/packages/commercejs/src/utils/normalize-category.ts @@ -9,6 +9,6 @@ export function normalizeCategory( id, name, slug, - path: slug, + path: `/${slug}`, } } diff --git a/packages/commercejs/src/utils/normalize-checkout.ts b/packages/commercejs/src/utils/normalize-checkout.ts index db136e0b89..5120bee2e9 100644 --- a/packages/commercejs/src/utils/normalize-checkout.ts +++ b/packages/commercejs/src/utils/normalize-checkout.ts @@ -1,6 +1,6 @@ import type { CardFields } from '@vercel/commerce/types/customer/card' import type { AddressFields } from '@vercel/commerce/types/customer/address' -import type { CommercejsCheckoutCapture } from '../types/checkout' +import type { CommercejsCheckoutCapture } from '../types' /** * Creates a checkout payload suitable for test checkouts. diff --git a/packages/commercejs/src/utils/normalize-product.ts b/packages/commercejs/src/utils/normalize-product.ts index 86c42d9224..2bd45921f3 100644 --- a/packages/commercejs/src/utils/normalize-product.ts +++ b/packages/commercejs/src/utils/normalize-product.ts @@ -1,8 +1,5 @@ -import type { - Product, - CommercejsProduct, - CommercejsVariant, -} from '../types/product' +import type { Product } from '@vercel/commerce/types/product' +import type { CommercejsProduct, CommercejsVariant } from '../types' function getOptionsFromVariantGroups( variantGroups: CommercejsProduct['variant_groups'] @@ -26,6 +23,7 @@ function normalizeVariants( if (!Array.isArray(variants)) return [] return variants?.map((variant) => ({ id: variant.id, + sku: variant.sku ?? variant.id, options: Object.entries(variant.options).map( ([variantGroupId, variantOptionId]) => { const variantGroupFromId = variantGroups.find( @@ -62,7 +60,7 @@ export function normalizeProduct( description, descriptionHtml: description, slug: permalink, - path: permalink, + path: `/${permalink}`, images: assets.map(({ url, description, filename }) => ({ url, alt: description || filename, diff --git a/packages/commercejs/src/wishlist/use-wishlist.tsx b/packages/commercejs/src/wishlist/use-wishlist.tsx index 7816143943..2175a8c8e7 100644 --- a/packages/commercejs/src/wishlist/use-wishlist.tsx +++ b/packages/commercejs/src/wishlist/use-wishlist.tsx @@ -1,16 +1,6 @@ +import type { Wishlist } from '@vercel/commerce/types/wishlist' import { HookFetcher } from '@vercel/commerce/utils/types' -export type Wishlist = { - items: [ - { - product_id: number - variant_id: number - id: number - product: any - } - ] -} - export interface UseWishlistOptions { includeProducts?: boolean } diff --git a/packages/kibocommerce/src/api/endpoints/customer/index.ts b/packages/kibocommerce/src/api/endpoints/customer/index.ts index 20bd44da91..a329f66b87 100644 --- a/packages/kibocommerce/src/api/endpoints/customer/index.ts +++ b/packages/kibocommerce/src/api/endpoints/customer/index.ts @@ -1,6 +1,6 @@ import { GetAPISchema, createEndpoint } from '@vercel/commerce/api' import customerEndpoint from '@vercel/commerce/api/endpoints/customer' -import type { CustomerSchema } from '../../../types/customer' +import type { CustomerSchema } from '@vercel/commerce/types/customer' import type { KiboCommerceAPI } from '../..' import getLoggedInCustomer from './customer' diff --git a/packages/kibocommerce/src/api/endpoints/login/index.ts b/packages/kibocommerce/src/api/endpoints/login/index.ts index 679a92d90c..73e89ebdd3 100644 --- a/packages/kibocommerce/src/api/endpoints/login/index.ts +++ b/packages/kibocommerce/src/api/endpoints/login/index.ts @@ -1,6 +1,6 @@ import { GetAPISchema, createEndpoint } from '@vercel/commerce/api' import loginEndpoint from '@vercel/commerce/api/endpoints/login' -import type { LoginSchema } from '../../../types/login' +import type { LoginSchema } from '@vercel/commerce/types/login' import type { KiboCommerceAPI } from '../..' import login from './login' @@ -15,6 +15,4 @@ const loginApi = createEndpoint({ handlers, }) -export default loginApi; - - +export default loginApi diff --git a/packages/kibocommerce/src/api/endpoints/logout/index.ts b/packages/kibocommerce/src/api/endpoints/logout/index.ts index 00804afb3b..55f68fcbf3 100644 --- a/packages/kibocommerce/src/api/endpoints/logout/index.ts +++ b/packages/kibocommerce/src/api/endpoints/logout/index.ts @@ -1,6 +1,6 @@ import { GetAPISchema, createEndpoint } from '@vercel/commerce/api' import logoutEndpoint from '@vercel/commerce/api/endpoints/logout' -import type { LogoutSchema } from '../../../types/logout' +import type { LogoutSchema } from '@vercel/commerce/types/logout' import type { KiboCommerceAPI } from '../..' import logout from './logout' diff --git a/packages/kibocommerce/src/api/endpoints/signup/index.ts b/packages/kibocommerce/src/api/endpoints/signup/index.ts index 8b2fec006c..4b9bd9a0e3 100644 --- a/packages/kibocommerce/src/api/endpoints/signup/index.ts +++ b/packages/kibocommerce/src/api/endpoints/signup/index.ts @@ -1,6 +1,6 @@ import { GetAPISchema, createEndpoint } from '@vercel/commerce/api' import signupEndpoint from '@vercel/commerce/api/endpoints/signup' -import type { SignupSchema } from '../../../types/signup' +import type { SignupSchema } from '@vercel/commerce/types/signup' import type { KiboCommerceAPI } from '../..' import signup from './signup' diff --git a/packages/kibocommerce/src/api/operations/get-all-pages.ts b/packages/kibocommerce/src/api/operations/get-all-pages.ts index 7607e194e9..f6d4009d20 100644 --- a/packages/kibocommerce/src/api/operations/get-all-pages.ts +++ b/packages/kibocommerce/src/api/operations/get-all-pages.ts @@ -1,35 +1,29 @@ import type { OperationContext } from '@vercel/commerce/api/operations' import type { KiboCommerceConfig } from '../index' import { getAllPagesQuery } from '../queries/get-all-pages-query' -import { GetPagesQueryParams } from "../../types/page"; import { normalizePage } from '../../lib/normalize' -export type GetAllPagesResult< - T extends { pages: any[] } = { pages: any[] } - > = T +export type GetAllPagesResult = T export default function getAllPagesOperation({ commerce, }: OperationContext) { - async function getAllPages({ query = getAllPagesQuery, config, - variables, }: { url?: string config?: Partial - variables?: GetPagesQueryParams preview?: boolean query?: string } = {}): Promise { const cfg = commerce.getConfig(config) - variables = { - documentListName: cfg.documentListName + const variables = { + documentListName: cfg.documentListName, } - const { data } = await cfg.fetch(query, { variables }); + const { data } = await cfg.fetch(query, { variables }) - const pages = data.documentListDocuments.items.map(normalizePage); + const pages = data.documentListDocuments.items.map(normalizePage) return { pages } } diff --git a/packages/kibocommerce/src/api/operations/get-all-products.ts b/packages/kibocommerce/src/api/operations/get-all-products.ts index bddafbffac..3808ce8602 100644 --- a/packages/kibocommerce/src/api/operations/get-all-products.ts +++ b/packages/kibocommerce/src/api/operations/get-all-products.ts @@ -2,7 +2,7 @@ import { Product } from '@vercel/commerce/types/product' import { GetAllProductsOperation } from '@vercel/commerce/types/product' import type { OperationContext } from '@vercel/commerce/api/operations' import type { KiboCommerceConfig } from '../index' -import { getAllProductsQuery } from '../queries/get-all-products-query'; +import { getAllProductsQuery } from '../queries/get-all-products-query' import { normalizeProduct } from '../../lib/normalize' export default function getAllProductsOperation({ @@ -18,11 +18,12 @@ export default function getAllProductsOperation({ config?: Partial preview?: boolean } = {}): Promise<{ products: Product[] | any[] }> { - const cfg = commerce.getConfig(config) - const { data } = await cfg.fetch(query); + const { data } = await cfg.fetch(query) - let normalizedProducts = data.products.items ? data.products.items.map( (item:any) => normalizeProduct(item, cfg)) : []; + let normalizedProducts = data.products.items + ? data.products.items.map((item: any) => normalizeProduct(item, cfg)) + : [] return { products: normalizedProducts, diff --git a/packages/kibocommerce/src/api/operations/get-customer-wishlist.ts b/packages/kibocommerce/src/api/operations/get-customer-wishlist.ts index c2792ad324..1f51d9da14 100644 --- a/packages/kibocommerce/src/api/operations/get-customer-wishlist.ts +++ b/packages/kibocommerce/src/api/operations/get-customer-wishlist.ts @@ -2,14 +2,11 @@ import type { OperationContext, OperationOptions, } from '@vercel/commerce/api/operations' -import type { - GetCustomerWishlistOperation, - Wishlist, -} from '@vercel/commerce/types/wishlist' +import type { GetCustomerWishlistOperation } from '@vercel/commerce/types/wishlist' // import type { RecursivePartial, RecursiveRequired } from '../utils/types' import { KiboCommerceConfig } from '..' // import getAllProducts, { ProductEdge } from './get-all-products' -import {getCustomerWishlistQuery} from '../queries/get-customer-wishlist-query' +import { getCustomerWishlistQuery } from '../queries/get-customer-wishlist-query' export default function getCustomerWishlistOperation({ commerce, @@ -40,14 +37,15 @@ export default function getCustomerWishlistOperation({ config?: KiboCommerceConfig includeProducts?: boolean }): Promise { - let customerWishlist ={} + let customerWishlist = {} try { - config = commerce.getConfig(config) - const result= await config?.fetch(getCustomerWishlistQuery,{variables}) - customerWishlist= result?.data?.customerWishlist; - } catch(e) { - customerWishlist= {} + const result = await config?.fetch(getCustomerWishlistQuery, { + variables, + }) + customerWishlist = result?.data?.customerWishlist + } catch (e) { + customerWishlist = {} } return { wishlist: customerWishlist as any } diff --git a/packages/kibocommerce/src/api/operations/get-page.ts b/packages/kibocommerce/src/api/operations/get-page.ts index 69289cba0d..aed8e02c1b 100644 --- a/packages/kibocommerce/src/api/operations/get-page.ts +++ b/packages/kibocommerce/src/api/operations/get-page.ts @@ -1,15 +1,11 @@ -import type { - OperationContext, -} from '@vercel/commerce/api/operations' +import type { OperationContext } from '@vercel/commerce/api/operations' import type { KiboCommerceConfig, KiboCommerceProvider } from '..' import { normalizePage } from '../../lib/normalize' import { getPageQuery } from '../queries/get-page-query' -import type { Page, GetPageQueryParams } from "../../types/page"; +import type { Page, GetPageOperation } from '@vercel/commerce/types/page' import type { Document } from '../../../schema' -export default function getPageOperation({ - commerce, -}: OperationContext) { +export default function getPageOperation({ commerce }: OperationContext) { async function getPage({ url, variables, @@ -17,18 +13,21 @@ export default function getPageOperation({ preview, }: { url?: string - variables: GetPageQueryParams + variables: GetPageOperation['variables'] config?: Partial preview?: boolean }): Promise { // RecursivePartial forces the method to check for every prop in the data, which is // required in case there's a custom `url` const cfg = commerce.getConfig(config) - const pageVariables = { documentListName: cfg.documentListName, filter: `id eq ${variables.id}` } + const pageVariables = { + documentListName: cfg.documentListName, + filter: `id eq ${variables.id}`, + } const { data } = await cfg.fetch(getPageQuery, { variables: pageVariables }) - const firstPage = data.documentListDocuments.items?.[0]; + const firstPage = data.documentListDocuments.items?.[0] const page = firstPage as Document if (preview || page?.properties?.is_visible) { return { page: normalizePage(page as any) } diff --git a/packages/kibocommerce/src/api/operations/get-site-info.ts b/packages/kibocommerce/src/api/operations/get-site-info.ts index 6b72d3b47f..bb4b8bddf6 100644 --- a/packages/kibocommerce/src/api/operations/get-site-info.ts +++ b/packages/kibocommerce/src/api/operations/get-site-info.ts @@ -1,7 +1,7 @@ import { OperationContext } from '@vercel/commerce/api/operations' import { Category } from '@vercel/commerce/types/site' import { KiboCommerceConfig } from '../index' -import {categoryTreeQuery} from '../queries/get-categories-tree-query' +import { categoryTreeQuery } from '../queries/get-categories-tree-query' import { normalizeCategory } from '../../lib/normalize' export type GetSiteInfoResult< @@ -11,9 +11,11 @@ export type GetSiteInfoResult< } > = T -export default function getSiteInfoOperation({commerce}: OperationContext) { +export default function getSiteInfoOperation({ + commerce, +}: OperationContext) { async function getSiteInfo({ - query= categoryTreeQuery, + query = categoryTreeQuery, variables, config, }: { @@ -23,12 +25,13 @@ export default function getSiteInfoOperation({commerce}: OperationContext) preview?: boolean } = {}): Promise { const cfg = commerce.getConfig(config) - const { data } = await cfg.fetch(query); - const categories= data.categories.items.map(normalizeCategory); - return Promise.resolve({ + const { data } = await cfg.fetch(query) + const categories = data.categories.items.map(normalizeCategory) + + return { categories: categories ?? [], brands: [], - }) + } } return getSiteInfo diff --git a/packages/kibocommerce/src/auth/use-login.tsx b/packages/kibocommerce/src/auth/use-login.tsx index c9d1fac176..324c9d3fef 100644 --- a/packages/kibocommerce/src/auth/use-login.tsx +++ b/packages/kibocommerce/src/auth/use-login.tsx @@ -1,9 +1,9 @@ -import { MutationHook } from '@vercel/commerce/utils/types' -import useLogin, { UseLogin } from '@vercel/commerce/auth/use-login' +import type { MutationHook } from '@vercel/commerce/utils/types' +import useLogin, { type UseLogin } from '@vercel/commerce/auth/use-login' import { useCallback } from 'react' import { CommerceError } from '@vercel/commerce/utils/errors' -import type { LoginHook } from '../types/login' +import type { LoginHook } from '@vercel/commerce/types/login' import useCustomer from '../customer/use-customer' import useCart from '../cart/use-cart' export default useLogin as UseLogin diff --git a/packages/kibocommerce/src/auth/use-logout.tsx b/packages/kibocommerce/src/auth/use-logout.tsx index 83e5a4b0cd..ee6c78de79 100644 --- a/packages/kibocommerce/src/auth/use-logout.tsx +++ b/packages/kibocommerce/src/auth/use-logout.tsx @@ -1,7 +1,7 @@ import { useCallback } from 'react' import type { MutationHook } from '@vercel/commerce/utils/types' import useLogout, { UseLogout } from '@vercel/commerce/auth/use-logout' -import type { LogoutHook } from '../types/logout' +import type { LogoutHook } from '@vercel/commerce/types/logout' import useCustomer from '../customer/use-customer' import useCart from '../cart/use-cart' @@ -12,18 +12,20 @@ export const handler: MutationHook = { url: '/api/logout', method: 'GET', }, - useHook: ({ fetch }) => () => { - const { mutate } = useCustomer() - const { mutate: mutateCart } = useCart() + useHook: + ({ fetch }) => + () => { + const { mutate } = useCustomer() + const { mutate: mutateCart } = useCart() - return useCallback( - async function logout() { - const data = await fetch() - await mutate(null, false) - await mutateCart(null, false) - return data - }, - [fetch, mutate, mutateCart] - ) - }, + return useCallback( + async function logout() { + const data = await fetch() + await mutate(null, false) + await mutateCart(null, false) + return data + }, + [fetch, mutate, mutateCart] + ) + }, } diff --git a/packages/kibocommerce/src/auth/use-signup.tsx b/packages/kibocommerce/src/auth/use-signup.tsx index b06126df65..893b2beb28 100644 --- a/packages/kibocommerce/src/auth/use-signup.tsx +++ b/packages/kibocommerce/src/auth/use-signup.tsx @@ -1,8 +1,8 @@ import { useCallback } from 'react' import type { MutationHook } from '@vercel/commerce/utils/types' import { CommerceError } from '@vercel/commerce/utils/errors' -import useSignup, { UseSignup } from '@vercel/commerce/auth/use-signup' -import type { SignupHook } from '../types/signup' +import useSignup, { type UseSignup } from '@vercel/commerce/auth/use-signup' +import type { SignupHook } from '@vercel/commerce/types/signup' import useCustomer from '../customer/use-customer' export default useSignup as UseSignup diff --git a/packages/kibocommerce/src/customer/use-customer.tsx b/packages/kibocommerce/src/customer/use-customer.tsx index 73e804a4b9..be13e6cfa1 100644 --- a/packages/kibocommerce/src/customer/use-customer.tsx +++ b/packages/kibocommerce/src/customer/use-customer.tsx @@ -1,6 +1,8 @@ import { SWRHook } from '@vercel/commerce/utils/types' -import useCustomer, { UseCustomer } from '@vercel/commerce/customer/use-customer' -import type { CustomerHook } from '../types/customer' +import useCustomer, { + type UseCustomer, +} from '@vercel/commerce/customer/use-customer' +import type { CustomerHook } from '@vercel/commerce/types/customer' export default useCustomer as UseCustomer @@ -13,12 +15,14 @@ export const handler: SWRHook = { const data = await fetch(options) return data?.customer ?? null }, - useHook: ({ useData }) => (input) => { - return useData({ - swrOptions: { - revalidateOnFocus: false, - ...input?.swrOptions, - }, - }) - }, + useHook: + ({ useData }) => + (input) => { + return useData({ + swrOptions: { + revalidateOnFocus: false, + ...input?.swrOptions, + }, + }) + }, } diff --git a/packages/kibocommerce/src/lib/normalize.ts b/packages/kibocommerce/src/lib/normalize.ts index 363589f0f5..1c2e1dc460 100644 --- a/packages/kibocommerce/src/lib/normalize.ts +++ b/packages/kibocommerce/src/lib/normalize.ts @@ -1,50 +1,59 @@ -import type { PrCategory, CustomerAccountInput, Document } from '../../schema' -import { Page } from '../types/page'; -import { Customer } from '../types/customer' +import type { + PrCategory, + CustomerAccountInput, + Document, + Product as KiboProduct, +} from '../../schema' -export function normalizeProduct(productNode: any, config: any): any { +import type { Page } from '@vercel/commerce/types/page' +import type { Category } from '@vercel/commerce/types/site' +import type { Product } from '@vercel/commerce/types/product' +import type { Customer } from '@vercel/commerce/types/customer' +import type { Cart, LineItem } from '@vercel/commerce/types/cart' +import type { WishlistItem } from '@vercel/commerce/types/wishlist' + +export function normalizeProduct( + productNode: KiboProduct, + config: any +): Product { const product = { - id: productNode.productCode, - name: productNode.content.productName, + id: productNode.productCode || '', + name: productNode.content?.productName || '', vendor: '', path: `/${productNode.productCode}`, - slug: productNode.productCode, + slug: productNode.productCode || '', price: { - value: productNode?.price?.price, + value: productNode?.price?.price ?? 0, currencyCode: config.currencyCode, }, - descriptionHtml: productNode.content.productShortDescription, - - images: productNode.content.productImages.map((p: any) => ({ - url: `http:${p.imageUrl}`, - altText: p.imageLabel, - })), - - variants: productNode.variations?.map((v: any) => ({ - id: v.productCode, - options: v.options.map((o: any) => ({ - ['__typename']: 'MultipleChoiceOption', - id: o.attributeFQN, - displayName: - o.attributeFQN.split('~')[1][0].toUpperCase() + - o.attributeFQN.split('~')[1].slice(1).toLowerCase(), - values: [{ label: o.value.toString() }], - })), - })) || [ - { - id: '', - }, - ], - + description: productNode.content?.productFullDescription || '', + descriptionHtml: productNode.content?.productFullDescription || '', + images: + productNode.content?.productImages?.map((p: any) => ({ + url: `http:${p.imageUrl}`, + altText: p.imageLabel, + })) || [], + variants: + productNode.variations?.map((v: any) => ({ + id: v.productCode, + options: + v.options?.map((o: any) => ({ + ['__typename']: 'MultipleChoiceOption', + id: o.attributeFQN, + displayName: + o.attributeFQN.split('~')[1][0].toUpperCase() + + o.attributeFQN.split('~')[1].slice(1).toLowerCase(), + values: [{ label: o.value.toString() }], + })) ?? [], + })) ?? [], options: productNode.options?.map((o: any) => ({ id: o.attributeFQN, displayName: o.attributeDetail.name, values: o.values.map((v: any) => ({ label: v.value.toString(), - hexColors: '', })), - })) || [], + })) ?? [], } return product @@ -57,11 +66,11 @@ export function normalizePage(page: Document): Page { url: page.properties.url, body: page.properties.body, is_visible: page.properties.is_visible, - sort_order: page.properties.sort_order + sort_order: page.properties.sort_order, } } -export function normalizeCart(data: any): any { +export function normalizeCart(data: any): Cart { return { id: data.id, customerId: data.userId, @@ -86,16 +95,15 @@ export function normalizeCart(data: any): any { export function normalizeCustomer(customer: CustomerAccountInput): Customer { return { - id: customer.id, - firstName: customer.firstName, - lastName: customer.lastName, - email: customer.emailAddress, - userName: customer.userName, - isAnonymous: customer.isAnonymous + id: String(customer.id), + firstName: customer.firstName || '', + lastName: customer.lastName || '', + email: customer.emailAddress || '', + acceptsMarketing: !!customer.acceptsMarketing, } } -function normalizeLineItem(item: any): any { +function normalizeLineItem(item: any): LineItem { return { id: item.id, variantId: item.product.variationProductCode, @@ -113,7 +121,7 @@ function normalizeLineItem(item: any): any { price: item?.unitPrice.extendedAmount, listPrice: 0, }, - options: item.product.options, + options: item.product.options ?? [], path: `${item.product.productCode}`, discounts: item?.discounts?.map((discount: any) => ({ value: discount.discounted_amount, @@ -121,11 +129,11 @@ function normalizeLineItem(item: any): any { } } -export function normalizeCategory(category: PrCategory): any { +export function normalizeCategory(category: PrCategory): Category { return { - id: category?.categoryCode, - name: category?.content?.name, - slug: category?.content?.slug, + id: category?.categoryCode || '', + name: category?.content?.name || '', + slug: category?.content?.slug || '', path: `/${category?.content?.slug}`, } } @@ -133,11 +141,13 @@ export function normalizeCategory(category: PrCategory): any { export function normalizeWishlistItem( item: any, config: any, - includeProducts=false -): any { + includeProducts = false +): WishlistItem { if (includeProducts) { return { id: item.id, + productId: String(item.product.productCode), + variantId: item.product.variationProductCode, product: getProuducts(item, config), } } else { @@ -173,7 +183,7 @@ function getProuducts(item: any, config: any): any { }, }, ], - options: item.product.options, + options: item.product.options ?? [], path: `/${item.product.productCode}`, description: item.product.description, } diff --git a/packages/kibocommerce/src/types/customer.ts b/packages/kibocommerce/src/types/customer.ts deleted file mode 100644 index 29f68fef1a..0000000000 --- a/packages/kibocommerce/src/types/customer.ts +++ /dev/null @@ -1,27 +0,0 @@ -import * as Core from '@vercel/commerce/types/customer' -export type Maybe = T | null -export * from '@vercel/commerce/types/customer' -export type Scalars = { - ID: string - String: string - Boolean: boolean - Int: number - Float: number - /** The `AnyScalar` type allows any scalar value by examining the input and passing the serialize, parseValue, and parseLiteral operations to their respective types. */ - AnyScalar: any - /** DateTime custom scalar type */ - DateTime: any - /** Object custom scalar type */ - Object: any -} - -export type Customer = { - id: Scalars['Int'], - firstName?: Maybe, - lastName?: Maybe, - email?: Maybe, - userName?: Maybe, - isAnonymous?: Maybe -} - -export type CustomerSchema = Core.CustomerSchema diff --git a/packages/kibocommerce/src/types/login.ts b/packages/kibocommerce/src/types/login.ts deleted file mode 100644 index 2e7b198b27..0000000000 --- a/packages/kibocommerce/src/types/login.ts +++ /dev/null @@ -1,8 +0,0 @@ -import * as Core from '@vercel/commerce/types/login' -import type { CustomerUserAuthInfoInput } from '../../schema' - -export * from '@vercel/commerce/types/login' - -export type LoginOperation = Core.LoginOperation & { - variables: CustomerUserAuthInfoInput -} diff --git a/packages/kibocommerce/src/types/logout.ts b/packages/kibocommerce/src/types/logout.ts deleted file mode 100644 index 1de06f8dc8..0000000000 --- a/packages/kibocommerce/src/types/logout.ts +++ /dev/null @@ -1 +0,0 @@ -export * from '@vercel/commerce/types/logout' diff --git a/packages/kibocommerce/src/types/page.ts b/packages/kibocommerce/src/types/page.ts deleted file mode 100644 index f311eb8b81..0000000000 --- a/packages/kibocommerce/src/types/page.ts +++ /dev/null @@ -1,35 +0,0 @@ -import * as Core from '@vercel/commerce/types/page' -export type Maybe = T | null -export type Scalars = { - ID: string - String: string - Boolean: boolean - Int: number - Float: number - /** The `AnyScalar` type allows any scalar value by examining the input and passing the serialize, parseValue, and parseLiteral operations to their respective types. */ - AnyScalar: any - /** DateTime custom scalar type */ - DateTime: any - /** Object custom scalar type */ - Object: any -} - -export * from '@vercel/commerce/types/page' - -export type Page = Core.Page - -export type PageTypes = { - page: Page -} - -export type GetPagesQueryParams = { - documentListName: Maybe -} - -export type GetPageQueryParams = { - id: Maybe - documentListName: Maybe -} - -export type GetAllPagesOperation = Core.GetAllPagesOperation -export type GetPageOperation = Core.GetPageOperation diff --git a/packages/kibocommerce/src/types/signup.ts b/packages/kibocommerce/src/types/signup.ts deleted file mode 100644 index 3f0d1af5ac..0000000000 --- a/packages/kibocommerce/src/types/signup.ts +++ /dev/null @@ -1 +0,0 @@ -export * from '@vercel/commerce/types/signup' diff --git a/packages/local/src/api/operations/get-product.ts b/packages/local/src/api/operations/get-product.ts index b77be3acbb..b6ee0c3c8b 100644 --- a/packages/local/src/api/operations/get-product.ts +++ b/packages/local/src/api/operations/get-product.ts @@ -4,9 +4,7 @@ import { GetProductOperation } from '@vercel/commerce/types/product' import data from '../../data.json' import type { OperationContext } from '@vercel/commerce/api/operations' -export default function getProductOperation({ - commerce, -}: OperationContext) { +export default function getProductOperation(_p: OperationContext) { async function getProduct({ query = '', variables, diff --git a/packages/local/src/api/operations/get-site-info.ts b/packages/local/src/api/operations/get-site-info.ts index c07a479cb4..8425ee5c57 100644 --- a/packages/local/src/api/operations/get-site-info.ts +++ b/packages/local/src/api/operations/get-site-info.ts @@ -1,5 +1,5 @@ import { OperationContext } from '@vercel/commerce/api/operations' -import { Category } from '@vercel/commerce/types/site' +import { Category, GetSiteInfoOperation } from '@vercel/commerce/types/site' import { LocalConfig } from '../index' export type GetSiteInfoResult< diff --git a/packages/local/src/data.json b/packages/local/src/data.json index 18c8ee7181..5cde8d184a 100644 --- a/packages/local/src/data.json +++ b/packages/local/src/data.json @@ -7,7 +7,8 @@ "path": "/new-short-sleeve-t-shirt", "slug": "new-short-sleeve-t-shirt", "price": { "value": 25, "currencyCode": "USD" }, - "descriptionHtml": "

Show off your love for Next.js and Vercel with this unique, limited edition t-shirt. This design is part of a limited run, numbered drop at the June 2021 Next.js Conf. It features a unique, handcrafted triangle design. Get it while supplies last – only 200 of these shirts will be made! All proceeds will be donated to charity.

", + "description": "Show off your love for Next.js and Vercel with this unique, limited edition t-shirt. This design is part of a limited run, numbered drop at the June 2021 Next.js Conf. It features a unique, handcrafted triangle design. Get it while supplies last - only 200 of these shirts will be made! All proceeds will be donated to charity.", + "descriptionHtml": "

Show off your love for Next.js and Vercel with this unique, limited edition t-shirt. This design is part of a limited run, numbered drop at the June 2021 Next.js Conf. It features a unique, handcrafted triangle design. Get it while supplies last - only 200 of these shirts will be made! All proceeds will be donated to charity.

", "images": [ { "url": "/assets/drop-shirt-0.png", @@ -31,6 +32,8 @@ "variants": [ { "id": "Z2lkOi8vc2hvcGlmeS9Qcm9kdWN0LzU0NDczMjUwMjQ0MjAss=", + "name": "New Short Sleeve T-Shirt", + "sku": "new-short-sleeve-t-shirt", "options": [ { "__typename": "MultipleChoiceOption", @@ -80,6 +83,7 @@ "path": "/lightweight-jacket", "slug": "lightweight-jacket", "price": { "value": 249.99, "currencyCode": "USD" }, + "description": "Show off your love for Next.js and Vercel with this unique, limited edition t-shirt. This design is part of a limited run, numbered drop at the June 2021 Next.js Conf. It features a unique, handcrafted triangle design. Get it while supplies last - only 200 of these shirts will be made! All proceeds will be donated to charity.", "descriptionHtml": "

Show off your love for Next.js and Vercel with this unique, limited edition t-shirt. This design is part of a limited run, numbered drop at the June 2021 Next.js Conf. It features a unique, handcrafted triangle design. Get it while supplies last – only 200 of these shirts will be made! All proceeds will be donated to charity.

", "images": [ { @@ -104,6 +108,8 @@ "variants": [ { "id": "Z2lkOid8vc2hvcGlmeS9Qcm9kdWN0LzU0NDczMjUwMjQ0MjAss=", + "name": "Lightweight Jacket", + "sku": "lightweight-jacket", "options": [ { "__typename": "MultipleChoiceOption", @@ -153,6 +159,7 @@ "path": "/shirt", "slug": "shirt", "price": { "value": 25, "currencyCode": "USD" }, + "description": "Show off your love for Next.js and Vercel with this unique, limited edition t-shirt. This design is part of a limited run, numbered drop at the June 2021 Next.js Conf. It features a unique, handcrafted triangle design. Get it while supplies last - only 200 of these shirts will be made! All proceeds will be donated to charity.", "descriptionHtml": "

Show off your love for Next.js and Vercel with this unique, limited edition t-shirt. This design is part of a limited run, numbered drop at the June 2021 Next.js Conf. It features a unique, handcrafted triangle design. Get it while supplies last – only 200 of these shirts will be made! All proceeds will be donated to charity.

", "images": [ { @@ -189,6 +196,8 @@ "variants": [ { "id": "Z2lkOi8vc2hvcGlmeS9Qcms9kdWN0LzU0NDczMjUwMjQ0MjAss=", + "name": "Shirt", + "sku": "shirt", "options": [ { "__typename": "MultipleChoiceOption", diff --git a/packages/local/src/wishlist/use-wishlist.tsx b/packages/local/src/wishlist/use-wishlist.tsx index b2785d46f8..8751aa4ed6 100644 --- a/packages/local/src/wishlist/use-wishlist.tsx +++ b/packages/local/src/wishlist/use-wishlist.tsx @@ -1,19 +1,8 @@ import { HookFetcher } from '@vercel/commerce/utils/types' -import type { Product } from '@vercel/commerce/types/product' +import { Wishlist } from '@vercel/commerce/types/wishlist' const defaultOpts = {} -export type Wishlist = { - items: [ - { - product_id: number - variant_id: number - id: number - product: Product - } - ] -} - export interface UseWishlistOptions { includeProducts?: boolean } diff --git a/packages/ordercloud/src/api/endpoints/cart/add-item.ts b/packages/ordercloud/src/api/endpoints/cart/add-item.ts index 28d372bd05..8894d921de 100644 --- a/packages/ordercloud/src/api/endpoints/cart/add-item.ts +++ b/packages/ordercloud/src/api/endpoints/cart/add-item.ts @@ -1,6 +1,6 @@ import type { CartEndpoint } from '.' import type { RawVariant } from '../../../types/product' -import type { OrdercloudLineItem } from '../../../types/cart' +import type { LineItem } from '@vercel/commerce/types/cart' import { serialize } from 'cookie' @@ -86,7 +86,7 @@ const addItem: CartEndpoint['handlers']['addItem'] = async ({ restBuyerFetch('GET', `/orders/Outgoing/${cartId}`, null, { token }), restBuyerFetch('GET', `/orders/Outgoing/${cartId}/lineitems`, null, { token, - }).then((response: { Items: OrdercloudLineItem[] }) => response.Items), + }).then((response: { Items: LineItem[] }) => response.Items), ]) // Format cart diff --git a/packages/ordercloud/src/api/endpoints/cart/index.ts b/packages/ordercloud/src/api/endpoints/cart/index.ts index f36364c46a..e458964f9b 100644 --- a/packages/ordercloud/src/api/endpoints/cart/index.ts +++ b/packages/ordercloud/src/api/endpoints/cart/index.ts @@ -1,4 +1,4 @@ -import type { CartSchema } from '../../../types/cart' +import type { CartSchema } from '@vercel/commerce/types/cart' import type { OrdercloudAPI } from '../..' import { GetAPISchema, createEndpoint } from '@vercel/commerce/api' diff --git a/packages/ordercloud/src/api/endpoints/checkout/get-checkout.ts b/packages/ordercloud/src/api/endpoints/checkout/get-checkout.ts index c0ab1a40d6..eacf88e832 100644 --- a/packages/ordercloud/src/api/endpoints/checkout/get-checkout.ts +++ b/packages/ordercloud/src/api/endpoints/checkout/get-checkout.ts @@ -39,6 +39,8 @@ const getCheckout: CheckoutEndpoint['handlers']['getCheckout'] = async ({ data: { hasPayment: payments.length > 0, hasShipping: Boolean(address), + addressId: address, + cardId: payments[0]?.ID, }, errors: [], }) diff --git a/packages/ordercloud/src/api/endpoints/checkout/index.ts b/packages/ordercloud/src/api/endpoints/checkout/index.ts index 44a9a69330..49f10361ad 100644 --- a/packages/ordercloud/src/api/endpoints/checkout/index.ts +++ b/packages/ordercloud/src/api/endpoints/checkout/index.ts @@ -1,4 +1,4 @@ -import type { CheckoutSchema } from '../../../types/checkout' +import type { CheckoutSchema } from '@vercel/commerce/types/checkout' import type { OrdercloudAPI } from '../..' import { GetAPISchema, createEndpoint } from '@vercel/commerce/api' diff --git a/packages/ordercloud/src/api/endpoints/customer/address/index.ts b/packages/ordercloud/src/api/endpoints/customer/address/index.ts index f6ab7e3064..34e80c8ddb 100644 --- a/packages/ordercloud/src/api/endpoints/customer/address/index.ts +++ b/packages/ordercloud/src/api/endpoints/customer/address/index.ts @@ -1,4 +1,4 @@ -import type { CustomerAddressSchema } from '../../../../types/customer/address' +import type { CustomerAddressSchema } from '@vercel/commerce/types/customer/address' import type { OrdercloudAPI } from '../../..' import { GetAPISchema, createEndpoint } from '@vercel/commerce/api' diff --git a/packages/ordercloud/src/api/endpoints/customer/card/index.ts b/packages/ordercloud/src/api/endpoints/customer/card/index.ts index 7116e3cb54..302009a89a 100644 --- a/packages/ordercloud/src/api/endpoints/customer/card/index.ts +++ b/packages/ordercloud/src/api/endpoints/customer/card/index.ts @@ -1,4 +1,4 @@ -import type { CustomerCardSchema } from '../../../../types/customer/card' +import type { CustomerCardSchema } from '@vercel/commerce/types/customer/card' import type { OrdercloudAPI } from '../../..' import { GetAPISchema, createEndpoint } from '@vercel/commerce/api' diff --git a/packages/ordercloud/src/api/utils/cart.ts b/packages/ordercloud/src/api/utils/cart.ts index 716f3521ea..fd0c79bf32 100644 --- a/packages/ordercloud/src/api/utils/cart.ts +++ b/packages/ordercloud/src/api/utils/cart.ts @@ -1,4 +1,5 @@ -import type { Cart, OrdercloudCart, OrdercloudLineItem } from '../../types/cart' +import type { Cart } from '@vercel/commerce/types/cart' +import type { OrdercloudCart, OrdercloudLineItem } from '../../types/cart' export function formatCart( cart: OrdercloudCart, diff --git a/packages/ordercloud/src/checkout/use-checkout.tsx b/packages/ordercloud/src/checkout/use-checkout.tsx index f60ebfdd92..67d92708ff 100644 --- a/packages/ordercloud/src/checkout/use-checkout.tsx +++ b/packages/ordercloud/src/checkout/use-checkout.tsx @@ -2,7 +2,9 @@ import type { GetCheckoutHook } from '@vercel/commerce/types/checkout' import { useMemo } from 'react' import { SWRHook } from '@vercel/commerce/utils/types' -import useCheckout, { UseCheckout } from '@vercel/commerce/checkout/use-checkout' +import useCheckout, { + UseCheckout, +} from '@vercel/commerce/checkout/use-checkout' import useSubmitCheckout from './use-submit-checkout' export default useCheckout as UseCheckout @@ -24,7 +26,7 @@ export const handler: SWRHook = { Object.create(response, { isEmpty: { get() { - return (response.data?.lineItems?.length ?? 0) <= 0 + return response.data?.lineItems?.length ?? 0 }, enumerable: true, }, diff --git a/packages/ordercloud/src/types/cart.ts b/packages/ordercloud/src/types/cart.ts index 389a5a666d..1fbeb09b57 100644 --- a/packages/ordercloud/src/types/cart.ts +++ b/packages/ordercloud/src/types/cart.ts @@ -1,7 +1,3 @@ -import * as Core from '@vercel/commerce/types/cart' - -export * from '@vercel/commerce/types/cart' - export interface OrdercloudCart { ID: string FromUser: { @@ -97,30 +93,3 @@ export interface OrdercloudLineItem { Specs: [] xp: null } - -/** - * Extend core cart types - */ - -export type Cart = Core.Cart & { - lineItems: Core.LineItem[] - url?: string -} - -export type CartTypes = Core.CartTypes - -export type CartHooks = Core.CartHooks - -export type GetCartHook = CartHooks['getCart'] -export type AddItemHook = CartHooks['addItem'] -export type UpdateItemHook = CartHooks['updateItem'] -export type RemoveItemHook = CartHooks['removeItem'] - -export type CartSchema = Core.CartSchema - -export type CartHandlers = Core.CartHandlers - -export type GetCartHandler = CartHandlers['getCart'] -export type AddItemHandler = CartHandlers['addItem'] -export type UpdateItemHandler = CartHandlers['updateItem'] -export type RemoveItemHandler = CartHandlers['removeItem'] diff --git a/packages/ordercloud/src/types/checkout.ts b/packages/ordercloud/src/types/checkout.ts deleted file mode 100644 index 976d78e7a1..0000000000 --- a/packages/ordercloud/src/types/checkout.ts +++ /dev/null @@ -1,4 +0,0 @@ -import * as Core from '@vercel/commerce/types/checkout' - -export type CheckoutTypes = Core.CheckoutTypes -export type CheckoutSchema = Core.CheckoutSchema diff --git a/packages/ordercloud/src/types/customer/address.ts b/packages/ordercloud/src/types/customer/address.ts index 3576b676c9..ec7e5d74e5 100644 --- a/packages/ordercloud/src/types/customer/address.ts +++ b/packages/ordercloud/src/types/customer/address.ts @@ -1,9 +1,3 @@ -import * as Core from '@vercel/commerce/types/customer/address' - -export type CustomerAddressTypes = Core.CustomerAddressTypes -export type CustomerAddressSchema = - Core.CustomerAddressSchema - export interface OrdercloudAddress { ID: string FromCompanyID: string diff --git a/packages/ordercloud/src/types/customer/card.ts b/packages/ordercloud/src/types/customer/card.ts index 293d5041a1..8b4851cdb2 100644 --- a/packages/ordercloud/src/types/customer/card.ts +++ b/packages/ordercloud/src/types/customer/card.ts @@ -1,8 +1,3 @@ -import * as Core from '@vercel/commerce/types/customer/card' - -export type CustomerCardTypes = Core.CustomerCardTypes -export type CustomerCardSchema = Core.CustomerCardSchema - export interface OredercloudCreditCard { ID: string Editable: boolean diff --git a/packages/ordercloud/src/utils/product.ts b/packages/ordercloud/src/utils/product.ts index 6da3bf86bd..3e6b265b6a 100644 --- a/packages/ordercloud/src/utils/product.ts +++ b/packages/ordercloud/src/utils/product.ts @@ -8,6 +8,7 @@ export function normalize(product: RawProduct): Product { name: product.Name, description: product.Description, slug: product.ID, + path: `/${product.ID}`, images: product.xp.Images, price: { value: product.xp.Price, @@ -16,6 +17,8 @@ export function normalize(product: RawProduct): Product { variants: product.xp.Variants?.length ? product.xp.Variants.map((variant) => ({ id: variant.ID, + sku: variant.ID, + name: product.Name, options: variant.Specs.map((spec) => ({ id: spec.SpecID, __typename: 'MultipleChoiceOption', @@ -27,12 +30,7 @@ export function normalize(product: RawProduct): Product { ], })), })) - : [ - { - id: '', - options: [], - }, - ], + : [], options: product.xp.Specs?.length ? product.xp.Specs.map((spec) => ({ id: spec.ID, diff --git a/packages/ordercloud/src/wishlist/use-wishlist.tsx b/packages/ordercloud/src/wishlist/use-wishlist.tsx index b2785d46f8..9d15370ffc 100644 --- a/packages/ordercloud/src/wishlist/use-wishlist.tsx +++ b/packages/ordercloud/src/wishlist/use-wishlist.tsx @@ -1,19 +1,8 @@ import { HookFetcher } from '@vercel/commerce/utils/types' -import type { Product } from '@vercel/commerce/types/product' +import type { Wishlist } from '@vercel/commerce/types/wishlist' const defaultOpts = {} -export type Wishlist = { - items: [ - { - product_id: number - variant_id: number - id: number - product: Product - } - ] -} - export interface UseWishlistOptions { includeProducts?: boolean } diff --git a/packages/saleor/src/api/operations/get-all-pages.ts b/packages/saleor/src/api/operations/get-all-pages.ts index 37f2e3ab2d..e53cc8f319 100644 --- a/packages/saleor/src/api/operations/get-all-pages.ts +++ b/packages/saleor/src/api/operations/get-all-pages.ts @@ -6,9 +6,12 @@ import * as Query from '../../utils/queries' export type Page = any -export type GetAllPagesResult = T +export type GetAllPagesResult = + T -export default function getAllPagesOperation({ commerce }: OperationContext) { +export default function getAllPagesOperation({ + commerce, +}: OperationContext) { async function getAllPages({ query = Query.PageMany, config, @@ -34,11 +37,15 @@ export default function getAllPagesOperation({ commerce }: OperationContext ({ - ...node, - url: `/${locale}/${slug}`, - name, - })) + const pages = + data?.pages?.edges?.map( + ({ node: { title: name, slug, ...node } }: PageCountableEdge) => ({ + id: node.id, + url: `/${locale}/${slug}`, + body: node.content || '', + name, + }) + ) ?? [] return { pages } } diff --git a/packages/saleor/src/api/operations/get-all-product-paths.ts b/packages/saleor/src/api/operations/get-all-product-paths.ts index 66e8f95c91..6df489bae3 100644 --- a/packages/saleor/src/api/operations/get-all-product-paths.ts +++ b/packages/saleor/src/api/operations/get-all-product-paths.ts @@ -3,15 +3,16 @@ import { ProductCountableEdge } from '../../../schema' import type { Provider, SaleorConfig } from '..' import { getAllProductsPathsQuery } from '../../utils/queries' -import fetchAllProducts from '../utils/fetch-all-products' export type GetAllProductPathsResult = { products: Array<{ path: string }> } -export default function getAllProductPathsOperation({ commerce }: OperationContext) { +export default function getAllProductPathsOperation({ + commerce, +}: OperationContext) { async function getAllProductPaths({ - query, + query = getAllProductsPathsQuery, config, variables, }: { @@ -21,16 +22,15 @@ export default function getAllProductPathsOperation({ commerce }: OperationConte } = {}): Promise { config = commerce.getConfig(config) - const products = await fetchAllProducts({ - config, - query: getAllProductsPathsQuery, - variables, - }) + const { data }: any = await config.fetch(query, { variables }) return { - products: products?.map(({ node: { slug } }: ProductCountableEdge) => ({ - path: `/${slug}`, - })), + products: data?.products?.edges?.map( + ({ node: { slug } }: ProductCountableEdge) => + ({ + path: `/${slug}`, + } ?? []) + ), } } diff --git a/packages/saleor/src/api/operations/get-all-products.ts b/packages/saleor/src/api/operations/get-all-products.ts index f7982adee5..ae002d165d 100644 --- a/packages/saleor/src/api/operations/get-all-products.ts +++ b/packages/saleor/src/api/operations/get-all-products.ts @@ -12,7 +12,9 @@ type ReturnType = { products: Product[] } -export default function getAllProductsOperation({ commerce }: OperationContext) { +export default function getAllProductsOperation({ + commerce, +}: OperationContext) { async function getAllProducts({ query = Query.ProductMany, variables, @@ -46,13 +48,18 @@ export default function getAllProductsOperation({ commerce }: OperationContext

normalizeProduct(p)) ?? [] + data?.collection.products?.edges?.map( + ({ node: p }: ProductCountableEdge) => normalizeProduct(p) + ) ?? [] return { products, } } else { - const products = data.products?.edges?.map(({ node: p }: ProductCountableEdge) => normalizeProduct(p)) ?? [] + const products = + data?.products?.edges?.map(({ node: p }: ProductCountableEdge) => + normalizeProduct(p) + ) ?? [] return { products, diff --git a/packages/saleor/src/api/operations/get-page.ts b/packages/saleor/src/api/operations/get-page.ts index bab9d92c55..6fa4276914 100644 --- a/packages/saleor/src/api/operations/get-page.ts +++ b/packages/saleor/src/api/operations/get-page.ts @@ -8,7 +8,9 @@ export type Page = any export type GetPageResult = T -export default function getPageOperation({ commerce }: OperationContext) { +export default function getPageOperation({ + commerce, +}: OperationContext) { async function getPage({ query = Query.PageOne, variables, @@ -21,9 +23,7 @@ export default function getPageOperation({ commerce }: OperationContext { const { fetch, locale = 'en-US' } = commerce.getConfig(config) - const { - data: { page }, - } = await fetch( + const { data } = await fetch( query, { variables }, { @@ -36,13 +36,15 @@ export default function getPageOperation({ commerce }: OperationContext) { +export default function getProductOperation({ + commerce, +}: OperationContext) { async function getProduct({ query = Query.ProductOneBySlug, variables, @@ -38,7 +40,7 @@ export default function getProductOperation({ commerce }: OperationContext => { - const { data } = await config.fetch(query, { - variables: { ...variables, cursor }, - }) - - const edges: ProductCountableEdge[] = data.products?.edges ?? [] - const hasNextPage = data.products?.pageInfo?.hasNextPage - acc = acc.concat(edges) - - if (hasNextPage) { - const cursor = edges.pop()?.cursor - if (cursor) { - return fetchAllProducts({ - config, - query, - variables, - acc, - cursor, - }) - } - } - - return acc -} - -export default fetchAllProducts diff --git a/packages/saleor/src/cart/use-remove-item.tsx b/packages/saleor/src/cart/use-remove-item.tsx index b3969aeb8b..f3972c49b6 100644 --- a/packages/saleor/src/cart/use-remove-item.tsx +++ b/packages/saleor/src/cart/use-remove-item.tsx @@ -11,7 +11,7 @@ import useCart from './use-cart' import * as mutation from '../utils/mutations' import { getCheckoutId, checkoutToCart } from '../utils' import { Mutation, MutationCheckoutLineDeleteArgs } from '../../schema' -import { LineItem, RemoveItemHook } from '../types/cart' +import type { LineItem, RemoveItemHook } from '@vercel/commerce/types/cart' export default useRemoveItem as UseRemoveItem diff --git a/packages/saleor/src/cart/use-update-item.tsx b/packages/saleor/src/cart/use-update-item.tsx index ffca9b2f87..6fc6d2b102 100644 --- a/packages/saleor/src/cart/use-update-item.tsx +++ b/packages/saleor/src/cart/use-update-item.tsx @@ -1,19 +1,23 @@ import { useCallback } from 'react' import debounce from 'lodash.debounce' -import type { HookFetcherContext, MutationHookContext } from '@vercel/commerce/utils/types' +import type { + HookFetcherContext, + MutationHookContext, +} from '@vercel/commerce/utils/types' import { ValidationError } from '@vercel/commerce/utils/errors' -import useUpdateItem, { UseUpdateItem } from '@vercel/commerce/cart/use-update-item' +import useUpdateItem, { + UseUpdateItem, +} from '@vercel/commerce/cart/use-update-item' import useCart from './use-cart' import { handler as removeItemHandler } from './use-remove-item' -import type { LineItem } from '../types' import { checkoutToCart } from '../utils' import { getCheckoutId } from '../utils' -import { Mutation, MutationCheckoutLinesUpdateArgs } from '../../schema' import * as mutation from '../utils/mutations' -import type { UpdateItemHook } from '../types/cart' +import type { UpdateItemHook, LineItem } from '@vercel/commerce/types/cart' +import type { Mutation, MutationCheckoutLinesUpdateArgs } from '../../schema' export type UpdateItemActionInput = T extends LineItem ? Partial @@ -23,7 +27,11 @@ export default useUpdateItem as UseUpdateItem export const handler = { fetchOptions: { query: mutation.CheckoutLineUpdate }, - async fetcher({ input: { itemId, item }, options, fetch }: HookFetcherContext) { + async fetcher({ + input: { itemId, item }, + options, + fetch, + }: HookFetcherContext) { if (Number.isInteger(item.quantity)) { // Also allow the update hook to remove an item if the quantity is lower than 1 if (item.quantity! < 1) { @@ -40,7 +48,10 @@ export const handler = { } const checkoutId = getCheckoutId().checkoutId - const { checkoutLinesUpdate } = await fetch({ + const { checkoutLinesUpdate } = await fetch< + Mutation, + MutationCheckoutLinesUpdateArgs + >({ ...options, variables: { checkoutId, diff --git a/packages/saleor/src/product/use-search.tsx b/packages/saleor/src/product/use-search.tsx index 69212cba14..9ebb73a2ac 100644 --- a/packages/saleor/src/product/use-search.tsx +++ b/packages/saleor/src/product/use-search.tsx @@ -38,7 +38,7 @@ export const handler: SWRHook = { let edges if (categoryId) { - edges = data.collection?.products?.edges ?? [] + edges = data?.collection?.products?.edges ?? [] // FIXME @zaiste, no `vendor` in Saleor // if (brandId) { // edges = edges.filter( @@ -47,11 +47,13 @@ export const handler: SWRHook = { // ) // } } else { - edges = data.products?.edges ?? [] + edges = data?.products?.edges ?? [] } return { - products: edges.map(({ node }: ProductCountableEdge) => normalizeProduct(node)), + products: edges.map(({ node }: ProductCountableEdge) => + normalizeProduct(node) + ), found: !!edges.length, } }, diff --git a/packages/saleor/src/types/cart.ts b/packages/saleor/src/types/cart.ts deleted file mode 100644 index 9a4d29387b..0000000000 --- a/packages/saleor/src/types/cart.ts +++ /dev/null @@ -1,32 +0,0 @@ -import * as Core from '@vercel/commerce/types/cart' - -export * from '@vercel/commerce/types/cart' - -export type SaleorCart = {} - -/** - * Extend core cart types - */ - -export type Cart = Core.Cart & { - lineItems: Core.LineItem[] - url?: string -} - -export type CartTypes = Core.CartTypes - -export type CartHooks = Core.CartHooks - -export type GetCartHook = CartHooks['getCart'] -export type AddItemHook = CartHooks['addItem'] -export type UpdateItemHook = CartHooks['updateItem'] -export type RemoveItemHook = CartHooks['removeItem'] - -export type CartSchema = Core.CartSchema - -export type CartHandlers = Core.CartHandlers - -export type GetCartHandler = CartHandlers['getCart'] -export type AddItemHandler = CartHandlers['addItem'] -export type UpdateItemHandler = CartHandlers['updateItem'] -export type RemoveItemHandler = CartHandlers['removeItem'] diff --git a/packages/saleor/src/utils/get-categories.ts b/packages/saleor/src/utils/get-categories.ts index e2cc725338..13204a89d7 100644 --- a/packages/saleor/src/utils/get-categories.ts +++ b/packages/saleor/src/utils/get-categories.ts @@ -6,17 +6,19 @@ import * as query from './queries' const getCategories = async (config: SaleorConfig): Promise => { const { data } = await config.fetch(query.CollectionMany, { variables: { - first: 100, + first: 50, }, }) return ( - data.collections?.edges?.map(({ node: { id, name, slug } }: CollectionCountableEdge) => ({ - id, - name, - slug, - path: `/${slug}`, - })) ?? [] + data?.collections?.edges?.map( + ({ node: { id, name, slug } }: CollectionCountableEdge) => ({ + id, + name, + slug, + path: `/${slug}`, + }) + ) ?? [] ) } diff --git a/packages/saleor/src/utils/get-vendors.ts b/packages/saleor/src/utils/get-vendors.ts index caae555a88..3daf22e1db 100644 --- a/packages/saleor/src/utils/get-vendors.ts +++ b/packages/saleor/src/utils/get-vendors.ts @@ -30,7 +30,7 @@ const getVendors = async (config: SaleorConfig): Promise => { // node: { // entityId: id, // name: v, - // path: `brands/${id}`, + // path: `/${id}`, // }, // } // }) diff --git a/packages/saleor/src/utils/normalize.ts b/packages/saleor/src/utils/normalize.ts index a4ff4b52cb..1e2ae31dcb 100644 --- a/packages/saleor/src/utils/normalize.ts +++ b/packages/saleor/src/utils/normalize.ts @@ -1,6 +1,12 @@ import { Product } from '@vercel/commerce/types/product' -import { Product as SaleorProduct, Checkout, CheckoutLine, Money, ProductVariant } from '../../schema' +import { + Product as SaleorProduct, + Checkout, + CheckoutLine, + Money, + ProductVariant, +} from '../../schema' import type { Cart, LineItem } from '../types' @@ -19,11 +25,14 @@ const normalizeProductOptions = (options: ProductVariant[]) => { ?.map((option) => option?.attributes) .flat(1) .reduce((acc, x) => { - if (acc.find(({ displayName }: any) => displayName === x.attribute.name)) { + if ( + acc.find(({ displayName }: any) => displayName === x.attribute.name) + ) { return acc.map((opt: any) => { return opt.displayName === x.attribute.name ? { ...opt, + id: x.attribute.id, values: [ ...opt.values, ...x.values.map((value: any) => ({ @@ -37,6 +46,7 @@ const normalizeProductOptions = (options: ProductVariant[]) => { return acc.concat({ __typename: 'MultipleChoiceOption', + id: x.attribute.id, displayName: x.attribute.name, variant: 'size', values: x.values.map((value: any) => ({ @@ -54,7 +64,7 @@ const normalizeProductVariants = (variants: ProductVariant[]) => { return { id, name, - sku: sku ?? id, + ...(!!sku && { sku }), price, listPrice: price, requiresShipping: true, @@ -64,23 +74,41 @@ const normalizeProductVariants = (variants: ProductVariant[]) => { } export function normalizeProduct(productNode: SaleorProduct): Product { - const { id, name, media = [], variants, description, slug, pricing, ...rest } = productNode + const { + id, + name, + media = [], + variants, + description, + slug, + pricing, + ...rest + } = productNode const product = { id, name, vendor: '', - description: description ? JSON.parse(description)?.blocks[0]?.data.text : '', + description: description + ? JSON.parse(description)?.blocks[0]?.data.text + : '', path: `/${slug}`, slug: slug?.replace(/^\/+|\/+$/g, ''), - price: (pricing?.priceRange?.start?.net && money(pricing.priceRange.start.net)) || { + price: (pricing?.priceRange?.start?.net && + money(pricing.priceRange.start.net)) || { value: 0, currencyCode: 'USD', }, // TODO: Check nextjs-commerce bug if no images are added for a product images: media?.length ? media : [{ url: placeholderImg }], - variants: variants && variants.length > 0 ? normalizeProductVariants(variants as ProductVariant[]) : [], - options: variants && variants.length > 0 ? normalizeProductOptions(variants as ProductVariant[]) : [], + variants: + variants && variants.length > 0 + ? normalizeProductVariants(variants as ProductVariant[]) + : [], + options: + variants && variants.length > 0 + ? normalizeProductOptions(variants as ProductVariant[]) + : [], ...rest, } @@ -89,7 +117,8 @@ export function normalizeProduct(productNode: SaleorProduct): Product { export function normalizeCart(checkout: Checkout): Cart { const lines = checkout.lines as CheckoutLine[] - const lineItems: LineItem[] = lines.length > 0 ? lines?.map(normalizeLineItem) : [] + const lineItems: LineItem[] = + lines.length > 0 ? lines?.map(normalizeLineItem) : [] return { id: checkout.id, @@ -117,7 +146,7 @@ function normalizeLineItem({ id, variant, quantity }: CheckoutLine): LineItem { quantity, variant: { id: String(variant?.id), - sku: variant?.sku ?? '', + ...(variant?.sku && { sku: variant.sku }), name: variant?.name!, image: { url: variant?.media![0] ? variant?.media![0].url : placeholderImg, diff --git a/packages/saleor/src/utils/queries/collection-one.ts b/packages/saleor/src/utils/queries/collection-one.ts index c2e593f51e..57d9afd1e4 100644 --- a/packages/saleor/src/utils/queries/collection-one.ts +++ b/packages/saleor/src/utils/queries/collection-one.ts @@ -1,7 +1,11 @@ import * as fragment from '../fragments' export const CollectionOne = /* GraphQL */ ` - query getProductsFromCollection($categoryId: ID!, $first: Int = 100, $channel: String = "default-channel") { + query getProductsFromCollection( + $categoryId: ID! + $first: Int = 50 + $channel: String = "default-channel" + ) { collection(id: $categoryId, channel: $channel) { id products(first: $first) { diff --git a/packages/saleor/src/utils/queries/get-all-product-vendors-query.ts b/packages/saleor/src/utils/queries/get-all-product-vendors-query.ts index 7d0f01614f..3975668236 100644 --- a/packages/saleor/src/utils/queries/get-all-product-vendors-query.ts +++ b/packages/saleor/src/utils/queries/get-all-product-vendors-query.ts @@ -1,5 +1,5 @@ export const getAllProductVendors = /* GraphQL */ ` - query getAllProductVendors($first: Int = 250, $cursor: String) { + query getAllProductVendors($first: Int = 50, $cursor: String) { products(first: $first, after: $cursor) { pageInfo { hasNextPage diff --git a/packages/saleor/src/utils/queries/get-all-products-paths-query.ts b/packages/saleor/src/utils/queries/get-all-products-paths-query.ts index d9acb82cf4..6eb1c915a5 100644 --- a/packages/saleor/src/utils/queries/get-all-products-paths-query.ts +++ b/packages/saleor/src/utils/queries/get-all-products-paths-query.ts @@ -1,5 +1,9 @@ export const getAllProductsPathsQuery = /* GraphQL */ ` - query getAllProductPaths($first: Int = 100, $cursor: String, $channel: String = "default-channel") { + query getAllProductPaths( + $first: Int = 50 + $cursor: String + $channel: String = "default-channel" + ) { products(first: $first, after: $cursor, channel: $channel) { pageInfo { hasNextPage diff --git a/packages/saleor/src/utils/queries/page-many.ts b/packages/saleor/src/utils/queries/page-many.ts index 94bba696d5..4e5cd8bd08 100644 --- a/packages/saleor/src/utils/queries/page-many.ts +++ b/packages/saleor/src/utils/queries/page-many.ts @@ -1,5 +1,5 @@ export const PageMany = /* GraphQL */ ` - query PageMany($first: Int = 100) { + query PageMany($first: Int = 50) { pages(first: $first) { edges { node { diff --git a/packages/saleor/src/utils/queries/product-many.ts b/packages/saleor/src/utils/queries/product-many.ts index 7e0aa9a072..cea98eb262 100644 --- a/packages/saleor/src/utils/queries/product-many.ts +++ b/packages/saleor/src/utils/queries/product-many.ts @@ -2,12 +2,17 @@ import * as fragment from '../fragments' export const ProductMany = /* GraphQL */ ` query ProductMany( - $first: Int = 100 + $first: Int = 50 $filter: ProductFilterInput $sortBy: ProductOrder $channel: String = "default-channel" ) { - products(first: $first, channel: $channel, filter: $filter, sortBy: $sortBy) { + products( + first: $first + channel: $channel + filter: $filter + sortBy: $sortBy + ) { ...ProductConnection } } diff --git a/packages/saleor/src/utils/queries/product-one-by-slug.ts b/packages/saleor/src/utils/queries/product-one-by-slug.ts index e9169f05e5..669abbc068 100644 --- a/packages/saleor/src/utils/queries/product-one-by-slug.ts +++ b/packages/saleor/src/utils/queries/product-one-by-slug.ts @@ -19,6 +19,7 @@ export const ProductOneBySlug = /* GraphQL */ ` name attributes { attribute { + id name } values { diff --git a/packages/sfcc/src/api/utils/normalise-product.ts b/packages/sfcc/src/api/utils/normalise-product.ts index b8d0e2ed4f..c41dd45ab6 100644 --- a/packages/sfcc/src/api/utils/normalise-product.ts +++ b/packages/sfcc/src/api/utils/normalise-product.ts @@ -1,7 +1,6 @@ import { Product as SFCCProduct, Search } from 'commerce-sdk' import type { Product, - ProductImage, ProductOption, ProductVariant, } from '@vercel/commerce/types/product' @@ -58,15 +57,16 @@ export function normalizeProduct( // TODO: use `name-ID` as a virtual slug (for search 1:1) slug: product.id, // use product ID as a slug name: product.name!, + path: `/${product.id}`, description: product.longDescription!, price: { value: product.price!, currencyCode: product.currency, }, images: product.imageGroups![0].images.map((image) => ({ - url: image.disBaseLink, - altText: image.title, - })) as ProductImage[], + url: image.disBaseLink || image.link, + alt: image.title || '', + })), variants: normaliseVariants(product.variants), options: normaliseOptions(product.variationAttributes), } @@ -78,6 +78,7 @@ export function normalizeSearchProducts( return products.map((product) => ({ id: product.productId, slug: product.productId, // use product ID as a slug + path: `/${product.productId}`, name: product.productName!, description: '', price: { @@ -87,8 +88,8 @@ export function normalizeSearchProducts( images: [ { url: product.image!.link, - altText: product.productName, - } as ProductImage, + alt: product.productName, + }, ], variants: normaliseVariants(product.variants), options: normaliseOptions(product.variationAttributes), diff --git a/packages/shopify/src/api/endpoints/catalog/products.ts b/packages/shopify/src/api/endpoints/catalog/products.ts deleted file mode 100644 index d09c976c3b..0000000000 --- a/packages/shopify/src/api/endpoints/catalog/products.ts +++ /dev/null @@ -1 +0,0 @@ -export default function (_commerce: any) {} diff --git a/packages/shopify/src/api/endpoints/catalog/products/get-products.ts b/packages/shopify/src/api/endpoints/catalog/products/get-products.ts new file mode 100644 index 0000000000..1e8829e786 --- /dev/null +++ b/packages/shopify/src/api/endpoints/catalog/products/get-products.ts @@ -0,0 +1,26 @@ +import { ProductsEndpoint } from '.' + +const SORT: { [key: string]: string | undefined } = { + latest: 'id', + trending: 'total_sold', + price: 'price', +} + +const LIMIT = 12 + +// Return current cart info +const getProducts: ProductsEndpoint['handlers']['getProducts'] = async ({ + res, + body: { search, categoryId, brandId, sort }, + config, + commerce, +}) => { + res.status(200).json({ + data: { + products: [], + found: false, + }, + }) +} + +export default getProducts diff --git a/packages/shopify/src/api/endpoints/catalog/products/index.ts b/packages/shopify/src/api/endpoints/catalog/products/index.ts new file mode 100644 index 0000000000..df680453a1 --- /dev/null +++ b/packages/shopify/src/api/endpoints/catalog/products/index.ts @@ -0,0 +1,19 @@ +import { GetAPISchema, createEndpoint } from '@vercel/commerce/api' +import productsEndpoint from '@vercel/commerce/api/endpoints/catalog/products' +import type { ProductsSchema } from '@vercel/commerce/types/product' +import type { ShopifyAPI } from '../../..' + +import getProducts from './get-products' + +export type ProductsAPI = GetAPISchema + +export type ProductsEndpoint = ProductsAPI['endpoint'] + +export const handlers: ProductsEndpoint['handlers'] = { getProducts } + +const productsApi = createEndpoint({ + handler: productsEndpoint, + handlers, +}) + +export default productsApi diff --git a/packages/shopify/src/api/endpoints/checkout/index.ts b/packages/shopify/src/api/endpoints/checkout/index.ts index 64020810d6..bcccf150c0 100644 --- a/packages/shopify/src/api/endpoints/checkout/index.ts +++ b/packages/shopify/src/api/endpoints/checkout/index.ts @@ -1,6 +1,6 @@ import { GetAPISchema, createEndpoint } from '@vercel/commerce/api' import checkoutEndpoint from '@vercel/commerce/api/endpoints/checkout' -import type { CheckoutSchema } from '../../../types/checkout' +import type { CheckoutSchema } from '@vercel/commerce/types/checkout' import type { ShopifyAPI } from '../..' import getCheckout from './get-checkout' diff --git a/packages/shopify/src/api/index.ts b/packages/shopify/src/api/index.ts index 7ae6a42064..6412adaca3 100644 --- a/packages/shopify/src/api/index.ts +++ b/packages/shopify/src/api/index.ts @@ -13,7 +13,13 @@ import { import fetchGraphqlApi from './utils/fetch-graphql-api' -import * as operations from './operations' +import getAllPages from './operations/get-all-pages' +import getPage from './operations/get-page' +import getAllProducts from './operations/get-all-products' +import getAllProductPaths from './operations/get-all-product-paths' +import getProduct from './operations/get-product' +import getSiteInfo from './operations/get-site-info' +import login from './operations/login' if (!API_URL) { throw new Error( @@ -41,7 +47,15 @@ const config: ShopifyConfig = { export const provider = { config, - operations, + operations: { + login, + getSiteInfo, + getAllPages, + getPage, + getAllProducts, + getAllProductPaths, + getProduct, + }, } export type Provider = typeof provider diff --git a/packages/shopify/src/api/operations/get-all-pages.ts b/packages/shopify/src/api/operations/get-all-pages.ts index 2f6cc0916f..55c1d7d690 100644 --- a/packages/shopify/src/api/operations/get-all-pages.ts +++ b/packages/shopify/src/api/operations/get-all-pages.ts @@ -9,7 +9,7 @@ import { } from '../../../schema' import { normalizePages } from '../../utils' import type { ShopifyConfig, Provider } from '..' -import type { GetAllPagesOperation, Page } from '../../types/page' +import type { GetAllPagesOperation, Page } from '@vercel/commerce/types/page' import getAllPagesQuery from '../../utils/queries/get-all-pages-query' export default function getAllPagesOperation({ diff --git a/packages/shopify/src/api/operations/get-all-product-paths.ts b/packages/shopify/src/api/operations/get-all-product-paths.ts index e5a7d2d8ed..0155bf6cde 100644 --- a/packages/shopify/src/api/operations/get-all-product-paths.ts +++ b/packages/shopify/src/api/operations/get-all-product-paths.ts @@ -2,7 +2,7 @@ import type { OperationContext, OperationOptions, } from '@vercel/commerce/api/operations' -import { GetAllProductPathsOperation } from '../../types/product' +import { GetAllProductPathsOperation } from '@vercel/commerce/types/product' import { GetAllProductPathsQuery, GetAllProductPathsQueryVariables, diff --git a/packages/shopify/src/api/operations/get-all-products.ts b/packages/shopify/src/api/operations/get-all-products.ts index 003e27204b..fcab201287 100644 --- a/packages/shopify/src/api/operations/get-all-products.ts +++ b/packages/shopify/src/api/operations/get-all-products.ts @@ -2,7 +2,7 @@ import type { OperationContext, OperationOptions, } from '@vercel/commerce/api/operations' -import { GetAllProductsOperation } from '../../types/product' +import { GetAllProductsOperation } from '@vercel/commerce/types/product' import { GetAllProductsQuery, GetAllProductsQueryVariables, diff --git a/packages/shopify/src/api/operations/get-page.ts b/packages/shopify/src/api/operations/get-page.ts index 2cea521948..e6ba19ce53 100644 --- a/packages/shopify/src/api/operations/get-page.ts +++ b/packages/shopify/src/api/operations/get-page.ts @@ -9,7 +9,7 @@ import { GetPageQueryVariables, Page as ShopifyPage, } from '../../../schema' -import { GetPageOperation } from '../../types/page' +import { GetPageOperation } from '@vercel/commerce/types/page' import getPageQuery from '../../utils/queries/get-page-query' export default function getPageOperation({ diff --git a/packages/shopify/src/api/operations/get-product.ts b/packages/shopify/src/api/operations/get-product.ts index 1697b0feb0..76a3c865fa 100644 --- a/packages/shopify/src/api/operations/get-product.ts +++ b/packages/shopify/src/api/operations/get-product.ts @@ -2,7 +2,7 @@ import type { OperationContext, OperationOptions, } from '@vercel/commerce/api/operations' -import { GetProductOperation } from '../../types/product' +import { GetProductOperation } from '@vercel/commerce/types/product' import { normalizeProduct, getProductQuery } from '../../utils' import type { ShopifyConfig, Provider } from '..' import { diff --git a/packages/shopify/src/api/operations/get-site-info.ts b/packages/shopify/src/api/operations/get-site-info.ts index 6bb6de4b06..f7602025c8 100644 --- a/packages/shopify/src/api/operations/get-site-info.ts +++ b/packages/shopify/src/api/operations/get-site-info.ts @@ -4,9 +4,9 @@ import type { } from '@vercel/commerce/api/operations' import { GetSiteInfoQueryVariables } from '../../../schema' import type { ShopifyConfig, Provider } from '..' -import { GetSiteInfoOperation } from '../../types/site' +import { GetSiteInfoOperation } from '@vercel/commerce/types/site' -import { getCategories, getBrands, getSiteInfoQuery } from '../../utils' +import { getCategories, getBrands } from '../../utils' export default function getSiteInfoOperation({ commerce, @@ -24,9 +24,7 @@ export default function getSiteInfoOperation({ ): Promise async function getSiteInfo({ - query = getSiteInfoQuery, config, - variables, }: { query?: string config?: Partial @@ -37,24 +35,15 @@ export default function getSiteInfoOperation({ const categoriesPromise = getCategories(cfg) const brandsPromise = getBrands(cfg) - /* - const { fetch, locale } = cfg - const { data } = await fetch( - query, - { variables }, - { - ...(locale && { - headers: { - 'Accept-Language': locale, - }, - }), - } - ) - */ + + const [categories, brands] = await Promise.all([ + categoriesPromise, + brandsPromise, + ]) return { - categories: await categoriesPromise, - brands: await brandsPromise, + categories, + brands, } } diff --git a/packages/shopify/src/api/operations/index.ts b/packages/shopify/src/api/operations/index.ts deleted file mode 100644 index 7872a20b63..0000000000 --- a/packages/shopify/src/api/operations/index.ts +++ /dev/null @@ -1,7 +0,0 @@ -export { default as getAllPages } from './get-all-pages' -export { default as getPage } from './get-page' -export { default as getAllProducts } from './get-all-products' -export { default as getAllProductPaths } from './get-all-product-paths' -export { default as getProduct } from './get-product' -export { default as getSiteInfo } from './get-site-info' -export { default as login } from './login' diff --git a/packages/shopify/src/api/operations/login.ts b/packages/shopify/src/api/operations/login.ts index 5fad769bde..89f4022566 100644 --- a/packages/shopify/src/api/operations/login.ts +++ b/packages/shopify/src/api/operations/login.ts @@ -1,6 +1,6 @@ import type { ServerResponse } from 'http' import type { OperationContext } from '@vercel/commerce/api/operations' -import type { LoginOperation } from '../../types/login' +import type { LoginOperation } from '@vercel/commerce/types/login' import type { ShopifyConfig, Provider } from '..' import { customerAccessTokenCreateMutation, diff --git a/packages/shopify/src/api/utils/fetch-graphql-api.ts b/packages/shopify/src/api/utils/fetch-graphql-api.ts index 1970db5727..9f28d5218f 100644 --- a/packages/shopify/src/api/utils/fetch-graphql-api.ts +++ b/packages/shopify/src/api/utils/fetch-graphql-api.ts @@ -35,7 +35,7 @@ const fetchGraphqlApi: GraphQLFetcher = async ( throw getError( [ { - message: `${err} \n Most likely related to an unexpected output. e.g the store might be protected with password or not available.`, + message: `${err} \n Most likely related to an unexpected output. E.g: NEXT_PUBLIC_SHOPIFY_STORE_DOMAIN & NEXT_PUBLIC_SHOPIFY_STOREFRONT_ACCESS_TOKEN might be incorect.`, }, ], 500 diff --git a/packages/shopify/src/auth/use-login.tsx b/packages/shopify/src/auth/use-login.tsx index c9d183e337..81ec356361 100644 --- a/packages/shopify/src/auth/use-login.tsx +++ b/packages/shopify/src/auth/use-login.tsx @@ -1,8 +1,8 @@ import { useCallback } from 'react' import type { MutationHook } from '@vercel/commerce/utils/types' import { CommerceError } from '@vercel/commerce/utils/errors' -import useLogin, { UseLogin } from '@vercel/commerce/auth/use-login' -import type { LoginHook } from '../types/login' +import useLogin, { type UseLogin } from '@vercel/commerce/auth/use-login' +import type { LoginHook } from '@vercel/commerce/types/login' import useCustomer from '../customer/use-customer' import { diff --git a/packages/shopify/src/auth/use-logout.tsx b/packages/shopify/src/auth/use-logout.tsx index c37b0fcc9a..d434205259 100644 --- a/packages/shopify/src/auth/use-logout.tsx +++ b/packages/shopify/src/auth/use-logout.tsx @@ -1,7 +1,7 @@ import { useCallback } from 'react' import type { MutationHook } from '@vercel/commerce/utils/types' import useLogout, { UseLogout } from '@vercel/commerce/auth/use-logout' -import type { LogoutHook } from '../types/logout' +import type { LogoutHook } from '@vercel/commerce/types/logout' import useCustomer from '../customer/use-customer' import customerAccessTokenDeleteMutation from '../utils/mutations/customer-access-token-delete' import { getCustomerToken, setCustomerToken } from '../utils/customer-token' diff --git a/packages/shopify/src/auth/use-signup.tsx b/packages/shopify/src/auth/use-signup.tsx index 8af0fec7d1..90a4c443a2 100644 --- a/packages/shopify/src/auth/use-signup.tsx +++ b/packages/shopify/src/auth/use-signup.tsx @@ -1,8 +1,8 @@ import { useCallback } from 'react' import type { MutationHook } from '@vercel/commerce/utils/types' import { CommerceError } from '@vercel/commerce/utils/errors' -import useSignup, { UseSignup } from '@vercel/commerce/auth/use-signup' -import type { SignupHook } from '../types/signup' +import useSignup, { type UseSignup } from '@vercel/commerce/auth/use-signup' +import type { SignupHook } from '@vercel/commerce/types/signup' import useCustomer from '../customer/use-customer' import { Mutation, MutationCustomerCreateArgs } from '../../schema' diff --git a/packages/shopify/src/cart/use-add-item.tsx b/packages/shopify/src/cart/use-add-item.tsx index 5460bd726b..b485acfa56 100644 --- a/packages/shopify/src/cart/use-add-item.tsx +++ b/packages/shopify/src/cart/use-add-item.tsx @@ -2,7 +2,7 @@ import { useCallback } from 'react' import type { MutationHook } from '@vercel/commerce/utils/types' import { CommerceError } from '@vercel/commerce/utils/errors' import useAddItem, { UseAddItem } from '@vercel/commerce/cart/use-add-item' -import type { AddItemHook } from '../types/cart' +import type { AddItemHook } from '@vercel/commerce/types/cart' import useCart from './use-cart' import { diff --git a/packages/shopify/src/cart/use-cart.tsx b/packages/shopify/src/cart/use-cart.tsx index 2fe68beef9..2400debb1e 100644 --- a/packages/shopify/src/cart/use-cart.tsx +++ b/packages/shopify/src/cart/use-cart.tsx @@ -1,10 +1,11 @@ +import type { SWRHook } from '@vercel/commerce/utils/types' +import type { GetCartHook } from '@vercel/commerce/types/cart' + import { useMemo } from 'react' -import useCommerceCart, { UseCart } from '@vercel/commerce/cart/use-cart' +import useCommerceCart, { type UseCart } from '@vercel/commerce/cart/use-cart' -import { SWRHook } from '@vercel/commerce/utils/types' import { checkoutToCart } from '../utils' import getCheckoutQuery from '../utils/queries/get-checkout-query' -import { GetCartHook } from '../types/cart' import Cookies from 'js-cookie' import { diff --git a/packages/shopify/src/cart/use-remove-item.tsx b/packages/shopify/src/cart/use-remove-item.tsx index d04c7c5d2d..eefeed1354 100644 --- a/packages/shopify/src/cart/use-remove-item.tsx +++ b/packages/shopify/src/cart/use-remove-item.tsx @@ -7,7 +7,11 @@ import { ValidationError } from '@vercel/commerce/utils/errors' import useRemoveItem, { UseRemoveItem, } from '@vercel/commerce/cart/use-remove-item' -import type { Cart, LineItem, RemoveItemHook } from '../types/cart' +import type { + Cart, + LineItem, + RemoveItemHook, +} from '@vercel/commerce/types/cart' import useCart from './use-cart' export type RemoveItemFn = T extends LineItem diff --git a/packages/shopify/src/cart/use-update-item.tsx b/packages/shopify/src/cart/use-update-item.tsx index 0e8258a515..3767c61749 100644 --- a/packages/shopify/src/cart/use-update-item.tsx +++ b/packages/shopify/src/cart/use-update-item.tsx @@ -1,23 +1,26 @@ -import { useCallback } from 'react' -import debounce from 'lodash.debounce' +import type { UpdateItemHook, LineItem } from '@vercel/commerce/types/cart' +import type { + Mutation, + MutationCheckoutLineItemsUpdateArgs, +} from '../../schema' import type { HookFetcherContext, MutationHookContext, } from '@vercel/commerce/utils/types' + +import { useCallback } from 'react' +import debounce from 'lodash.debounce' import { ValidationError } from '@vercel/commerce/utils/errors' import useUpdateItem, { - UseUpdateItem, + type UseUpdateItem, } from '@vercel/commerce/cart/use-update-item' - import useCart from './use-cart' import { handler as removeItemHandler } from './use-remove-item' -import type { UpdateItemHook, LineItem } from '../types/cart' import { getCheckoutId, checkoutLineItemUpdateMutation, checkoutToCart, } from '../utils' -import { Mutation, MutationCheckoutLineItemsUpdateArgs } from '../../schema' export type UpdateItemActionInput = T extends LineItem ? Partial diff --git a/packages/shopify/src/customer/use-customer.tsx b/packages/shopify/src/customer/use-customer.tsx index 6fc9a53a7c..804d6a877a 100644 --- a/packages/shopify/src/customer/use-customer.tsx +++ b/packages/shopify/src/customer/use-customer.tsx @@ -1,10 +1,10 @@ +import type { SWRHook } from '@vercel/commerce/utils/types' +import type { CustomerHook } from '@vercel/commerce/types/customer' +import type { GetCustomerQuery, GetCustomerQueryVariables } from '../../schema' +import { getCustomerQuery, getCustomerToken } from '../utils' import useCustomer, { - UseCustomer, + type UseCustomer, } from '@vercel/commerce/customer/use-customer' -import type { CustomerHook } from '../types/customer' -import { SWRHook } from '@vercel/commerce/utils/types' -import { getCustomerQuery, getCustomerToken } from '../utils' -import { GetCustomerQuery, GetCustomerQueryVariables } from '../../schema' export default useCustomer as UseCustomer @@ -14,14 +14,28 @@ export const handler: SWRHook = { }, async fetcher({ options, fetch }) { const customerAccessToken = getCustomerToken() + if (customerAccessToken) { - const data = await fetch({ + const { customer } = await fetch< + GetCustomerQuery, + GetCustomerQueryVariables + >({ ...options, variables: { customerAccessToken: getCustomerToken() }, }) - return data.customer + + if (!customer) { + return null + } + + return { + id: customer.id, + firstName: customer.firstName ?? 'N/A', + lastName: customer.lastName ?? '', + ...(customer.email && { email: customer.email }), + ...(customer.phone && { phone: customer.phone }), + } } - return null }, useHook: ({ useData }) => diff --git a/packages/shopify/src/product/use-search.tsx b/packages/shopify/src/product/use-search.tsx index 582423e9f9..6d6b9add51 100644 --- a/packages/shopify/src/product/use-search.tsx +++ b/packages/shopify/src/product/use-search.tsx @@ -16,7 +16,7 @@ import { normalizeProduct, } from '../utils' -import type { SearchProductsHook } from '../types/product' +import type { SearchProductsHook } from '@vercel/commerce/types/product' export type SearchProductsInput = { search?: string diff --git a/packages/shopify/src/types/cart.ts b/packages/shopify/src/types/cart.ts deleted file mode 100644 index 243d369a56..0000000000 --- a/packages/shopify/src/types/cart.ts +++ /dev/null @@ -1,32 +0,0 @@ -import * as Core from '@vercel/commerce/types/cart' - -export * from '@vercel/commerce/types/cart' - -export type ShopifyCart = {} - -/** - * Extend core cart types - */ - -export type Cart = Core.Cart & { - lineItems: Core.LineItem[] - url?: string -} - -export type CartTypes = Core.CartTypes - -export type CartHooks = Core.CartHooks - -export type GetCartHook = CartHooks['getCart'] -export type AddItemHook = CartHooks['addItem'] -export type UpdateItemHook = CartHooks['updateItem'] -export type RemoveItemHook = CartHooks['removeItem'] - -export type CartSchema = Core.CartSchema - -export type CartHandlers = Core.CartHandlers - -export type GetCartHandler = CartHandlers['getCart'] -export type AddItemHandler = CartHandlers['addItem'] -export type UpdateItemHandler = CartHandlers['updateItem'] -export type RemoveItemHandler = CartHandlers['removeItem'] diff --git a/packages/shopify/src/types/checkout.ts b/packages/shopify/src/types/checkout.ts deleted file mode 100644 index d139db6859..0000000000 --- a/packages/shopify/src/types/checkout.ts +++ /dev/null @@ -1 +0,0 @@ -export * from '@vercel/commerce/types/checkout' diff --git a/packages/shopify/src/types/common.ts b/packages/shopify/src/types/common.ts deleted file mode 100644 index 23b8daa11c..0000000000 --- a/packages/shopify/src/types/common.ts +++ /dev/null @@ -1 +0,0 @@ -export * from '@vercel/commerce/types/common' diff --git a/packages/shopify/src/types/customer.ts b/packages/shopify/src/types/customer.ts deleted file mode 100644 index 6e66366be2..0000000000 --- a/packages/shopify/src/types/customer.ts +++ /dev/null @@ -1,5 +0,0 @@ -import * as Core from '@vercel/commerce/types/customer' - -export * from '@vercel/commerce/types/customer' - -export type CustomerSchema = Core.CustomerSchema diff --git a/packages/shopify/src/types/index.ts b/packages/shopify/src/types/index.ts deleted file mode 100644 index 7ab0b7f64f..0000000000 --- a/packages/shopify/src/types/index.ts +++ /dev/null @@ -1,25 +0,0 @@ -import * as Cart from './cart' -import * as Checkout from './checkout' -import * as Common from './common' -import * as Customer from './customer' -import * as Login from './login' -import * as Logout from './logout' -import * as Page from './page' -import * as Product from './product' -import * as Signup from './signup' -import * as Site from './site' -import * as Wishlist from './wishlist' - -export type { - Cart, - Checkout, - Common, - Customer, - Login, - Logout, - Page, - Product, - Signup, - Site, - Wishlist, -} diff --git a/packages/shopify/src/types/login.ts b/packages/shopify/src/types/login.ts deleted file mode 100644 index ab99bf8cd0..0000000000 --- a/packages/shopify/src/types/login.ts +++ /dev/null @@ -1,8 +0,0 @@ -import * as Core from '@vercel/commerce/types/login' -import type { CustomerAccessTokenCreateInput } from '../../schema' - -export * from '@vercel/commerce/types/login' - -export type LoginOperation = Core.LoginOperation & { - variables: CustomerAccessTokenCreateInput -} diff --git a/packages/shopify/src/types/logout.ts b/packages/shopify/src/types/logout.ts deleted file mode 100644 index 1de06f8dc8..0000000000 --- a/packages/shopify/src/types/logout.ts +++ /dev/null @@ -1 +0,0 @@ -export * from '@vercel/commerce/types/logout' diff --git a/packages/shopify/src/types/page.ts b/packages/shopify/src/types/page.ts deleted file mode 100644 index ccbc29f7b2..0000000000 --- a/packages/shopify/src/types/page.ts +++ /dev/null @@ -1,11 +0,0 @@ -import * as Core from '@vercel/commerce/types/page' -export * from '@vercel/commerce/types/page' - -export type Page = Core.Page - -export type PageTypes = { - page: Page -} - -export type GetAllPagesOperation = Core.GetAllPagesOperation -export type GetPageOperation = Core.GetPageOperation diff --git a/packages/shopify/src/types/product.ts b/packages/shopify/src/types/product.ts deleted file mode 100644 index 72ca02f02d..0000000000 --- a/packages/shopify/src/types/product.ts +++ /dev/null @@ -1 +0,0 @@ -export * from '@vercel/commerce/types/product' diff --git a/packages/shopify/src/types/signup.ts b/packages/shopify/src/types/signup.ts deleted file mode 100644 index 3f0d1af5ac..0000000000 --- a/packages/shopify/src/types/signup.ts +++ /dev/null @@ -1 +0,0 @@ -export * from '@vercel/commerce/types/signup' diff --git a/packages/shopify/src/types/site.ts b/packages/shopify/src/types/site.ts deleted file mode 100644 index 96a2e476e9..0000000000 --- a/packages/shopify/src/types/site.ts +++ /dev/null @@ -1 +0,0 @@ -export * from '@vercel/commerce/types/site' diff --git a/packages/shopify/src/types/wishlist.ts b/packages/shopify/src/types/wishlist.ts deleted file mode 100644 index af92d9f63e..0000000000 --- a/packages/shopify/src/types/wishlist.ts +++ /dev/null @@ -1 +0,0 @@ -export * from '@vercel/commerce/types/wishlist' diff --git a/packages/shopify/src/utils/checkout-to-cart.ts b/packages/shopify/src/utils/checkout-to-cart.ts index 97b3f0a21c..a487eeee51 100644 --- a/packages/shopify/src/utils/checkout-to-cart.ts +++ b/packages/shopify/src/utils/checkout-to-cart.ts @@ -1,4 +1,4 @@ -import type { Cart } from '../types/cart' +import type { Cart } from '@vercel/commerce/types/cart' import { CommerceError } from '@vercel/commerce/utils/errors' import { diff --git a/packages/shopify/src/utils/get-brands.ts b/packages/shopify/src/utils/get-brands.ts index eb87b519da..c8333458ff 100644 --- a/packages/shopify/src/utils/get-brands.ts +++ b/packages/shopify/src/utils/get-brands.ts @@ -5,19 +5,7 @@ import { import { ShopifyConfig } from '../api' import getAllProductVendors from './queries/get-all-product-vendors-query' -export type Brand = { - entityId: string - name: string - path: string -} - -export type BrandEdge = { - node: Brand -} - -export type Brands = BrandEdge[] - -const getBrands = async (config: ShopifyConfig): Promise => { +const getBrands = async (config: ShopifyConfig) => { const { data } = await config.fetch< GetAllProductVendorsQuery, GetAllProductVendorsQueryVariables @@ -32,11 +20,10 @@ const getBrands = async (config: ShopifyConfig): Promise => { return [...new Set(vendorsStrings)].map((v) => { const id = v.replace(/\s+/g, '-').toLowerCase() return { - node: { - entityId: id, - name: v, - path: `brands/${id}`, - }, + id, + name: v, + slug: id, + path: `/${id}`, } }) } diff --git a/packages/shopify/src/utils/get-categories.ts b/packages/shopify/src/utils/get-categories.ts index e5ca16dad8..2bae3c3b5b 100644 --- a/packages/shopify/src/utils/get-categories.ts +++ b/packages/shopify/src/utils/get-categories.ts @@ -1,6 +1,6 @@ -import type { Category } from '../types/site' -import { ShopifyConfig } from '../api' -import { CollectionEdge } from '../../schema' +import type { Category } from '@vercel/commerce/types/site' +import type { ShopifyConfig } from '../api' +import type { CollectionEdge } from '../../schema' import { normalizeCategory } from './normalize' import getSiteCollectionsQuery from './queries/get-all-collections-query' diff --git a/packages/shopify/src/utils/get-search-variables.ts b/packages/shopify/src/utils/get-search-variables.ts index f4863650dd..330465c87a 100644 --- a/packages/shopify/src/utils/get-search-variables.ts +++ b/packages/shopify/src/utils/get-search-variables.ts @@ -1,5 +1,5 @@ import getSortVariables from './get-sort-variables' -import { SearchProductsBody } from '../types/product' +import { SearchProductsBody } from '@vercel/commerce/types/product' export const getSearchVariables = ({ brandId, diff --git a/packages/shopify/src/utils/normalize.ts b/packages/shopify/src/utils/normalize.ts index 406c9b9cba..066daff335 100644 --- a/packages/shopify/src/utils/normalize.ts +++ b/packages/shopify/src/utils/normalize.ts @@ -1,9 +1,9 @@ -import type { Page } from '../types/page' -import type { Product } from '../types/product' -import type { Cart, LineItem } from '../types/cart' -import type { Category } from '../types/site' +import type { Page } from '@vercel/commerce/types/page' +import type { Product } from '@vercel/commerce/types/product' +import type { Cart, LineItem } from '@vercel/commerce/types/cart' +import type { Category } from '@vercel/commerce/types/site' -import { +import type { Product as ShopifyProduct, Checkout, CheckoutLineItemEdge, @@ -16,6 +16,7 @@ import { PageEdge, Collection, } from '../../schema' + import { colorMap } from './colors' const money = ({ amount, currencyCode }: MoneyV2) => { @@ -75,7 +76,7 @@ const normalizeProductVariants = ({ edges }: ProductVariantConnection) => { return { id, name: title, - sku: sku ?? id, + sku, price: +priceV2.amount, listPrice: +compareAtPriceV2?.amount, requiresShipping, @@ -122,7 +123,7 @@ export function normalizeProduct({ .filter((o) => o.name !== 'Title') // By default Shopify adds a 'Title' name when there's only one option. We don't need it. https://community.shopify.com/c/Shopify-APIs-SDKs/Adding-new-product-variant-is-automatically-adding-quot-Default/td-p/358095 .map((o) => normalizeProductOption(o)) : [], - ...(description && { description }), + description: description || '', ...(descriptionHtml && { descriptionHtml }), ...rest, } @@ -180,6 +181,7 @@ export const normalizePage = ( ...page, url: `/${locale}/${handle}`, name, + body: page.body ?? '', }) export const normalizePages = (edges: PageEdge[], locale?: string): Page[] => diff --git a/packages/spree/src/api/operations/get-site-info.ts b/packages/spree/src/api/operations/get-site-info.ts index 13b11e4a49..a389a666d1 100644 --- a/packages/spree/src/api/operations/get-site-info.ts +++ b/packages/spree/src/api/operations/get-site-info.ts @@ -111,7 +111,7 @@ export default function getSiteInfoOperation({ id: spreeTaxon.id, name: spreeTaxon.attributes.name, slug: spreeTaxon.id, - path: spreeTaxon.id, + path: `/${spreeTaxon.id}`, } }) @@ -120,11 +120,10 @@ export default function getSiteInfoOperation({ .sort(taxonsSort) .map((spreeTaxon: TaxonAttr) => { return { - node: { - entityId: spreeTaxon.id, - path: `brands/${spreeTaxon.id}`, - name: spreeTaxon.attributes.name, - }, + id: spreeTaxon.id, + path: `/${spreeTaxon.id}`, + slug: spreeTaxon.id, + name: spreeTaxon.attributes.name, } }) diff --git a/packages/spree/src/types/index.ts b/packages/spree/src/types/index.ts index 74ddeb52a1..9142be9423 100644 --- a/packages/spree/src/types/index.ts +++ b/packages/spree/src/types/index.ts @@ -8,10 +8,9 @@ import type { ResultResponse } from '@spree/storefront-api-v2-sdk/types/interfac import type { Response } from '@vercel/fetch' import type { ProductOption, Product } from '@vercel/commerce/types/product' import type { - AddItemHook, - RemoveItemHook, - WishlistItemBody, - WishlistTypes, + Wishlist as CoreWishlist, + WishlistItemBody as CoreWishlistItemBody, + RemoveItemHook as CoreRemoveItemHook, } from '@vercel/commerce/types/wishlist' export type UnknownObjectValues = Record @@ -134,31 +133,22 @@ export type UserOAuthTokens = { accessToken: string } -// TODO: ExplicitCommerceWishlist is a temporary type -// derived from tsx views. It will be removed once -// Wishlist in @vercel/commerce/types/wishlist is updated -// to a more specific type than `any`. -export type ExplicitCommerceWishlist = { - id: string +export interface Wishlist extends CoreWishlist { token: string - items: { - id: string - product_id: number - variant_id: number - product: Product - }[] } -export type ExplicitWishlistAddItemHook = AddItemHook< - WishlistTypes & { - wishlist: ExplicitCommerceWishlist - itemBody: WishlistItemBody & { - wishlistToken?: string - } - } -> +export interface WishlistItemBody extends CoreWishlistItemBody { + wishlistToken: string +} + +export type AddItemHook = { + data: Wishlist | null | undefined + body: { item: WishlistItemBody } + fetcherInput: { item: WishlistItemBody } + actionInput: WishlistItemBody +} -export type ExplicitWishlistRemoveItemHook = RemoveItemHook & { - fetcherInput: { wishlistToken?: string } - body: { wishlistToken?: string } +export type RemoveItemHook = CoreRemoveItemHook & { + fetcherInput: { itemId: string; wishlistToken?: string } + body: { temId: string; wishlistToken?: string } } diff --git a/packages/spree/src/utils/get-media-gallery.ts b/packages/spree/src/utils/get-media-gallery.ts index dd2dacb291..32f73540fa 100644 --- a/packages/spree/src/utils/get-media-gallery.ts +++ b/packages/spree/src/utils/get-media-gallery.ts @@ -1,6 +1,6 @@ // Based on https://github.com/spark-solutions/spree2vuestorefront/blob/d88d85ae1bcd2ec99b13b81cd2e3c25600a0216e/src/utils/index.ts -import type { ProductImage } from '@vercel/commerce/types/product' +import type { Image } from '@vercel/commerce/types/common' import type { SpreeProductImage } from '../types' const getMediaGallery = ( @@ -11,7 +11,7 @@ const getMediaGallery = ( minHeight: number ) => string | null ) => { - return images.reduce((productImages, _, imageIndex) => { + return images.reduce((productImages, _, imageIndex) => { const url = getImageUrl(images[imageIndex], 800, 800) if (url) { diff --git a/packages/spree/src/utils/normalizations/normalize-cart.ts b/packages/spree/src/utils/normalizations/normalize-cart.ts index c5597fd893..a8c0bce98f 100644 --- a/packages/spree/src/utils/normalizations/normalize-cart.ts +++ b/packages/spree/src/utils/normalizations/normalize-cart.ts @@ -88,7 +88,6 @@ const normalizeVariant = ( price: parseFloat(spreeVariant.attributes.price), listPrice: parseFloat(spreeVariant.attributes.price), image, - isInStock: spreeVariant.attributes.in_stock, availableForSale: spreeVariant.attributes.purchasable, ...(spreeVariant.attributes.weight === '0.0' ? {} diff --git a/packages/spree/src/utils/normalizations/normalize-page.ts b/packages/spree/src/utils/normalizations/normalize-page.ts index a2464ffd93..0d92a4a4de 100644 --- a/packages/spree/src/utils/normalizations/normalize-page.ts +++ b/packages/spree/src/utils/normalizations/normalize-page.ts @@ -35,7 +35,7 @@ const normalizePage = ( id: spreePage.id, name: spreePage.attributes.title, url: `/${usedCommerceLocale}/${spreePage.attributes.slug}`, - body: spreePage.attributes.content, + body: spreePage.attributes.content ?? '', } } diff --git a/packages/spree/src/utils/normalizations/normalize-product.ts b/packages/spree/src/utils/normalizations/normalize-product.ts index 6965f01970..f45e858955 100644 --- a/packages/spree/src/utils/normalizations/normalize-product.ts +++ b/packages/spree/src/utils/normalizations/normalize-product.ts @@ -1,9 +1,9 @@ import type { Product, - ProductImage, ProductPrice, ProductVariant, } from '@vercel/commerce/types/product' +import type { Image } from '@vercel/commerce/types/common' import type { ProductAttr } from '@spree/storefront-api-v2-sdk/types/interfaces/Product' import type { RelationType } from '@spree/storefront-api-v2-sdk/types/interfaces/Relationships' import { jsonApi } from '@spree/storefront-api-v2-sdk' @@ -105,6 +105,7 @@ const normalizeProduct = ( return { id: spreeVariantRecord.id, + sku: spreeVariantRecord.attributes.sku || spreeVariantRecord.id, options: variantOptions, } } @@ -213,7 +214,7 @@ const normalizeProduct = ( createGetAbsoluteImageUrl(requireConfigValue('imageHost') as string) ) - const images: ProductImage[] = + const images: Image[] = productImages.length === 0 ? placeholderImage === false ? [] diff --git a/packages/spree/src/utils/normalizations/normalize-user.ts b/packages/spree/src/utils/normalizations/normalize-user.ts index 8b738fbafc..0bc94d995f 100644 --- a/packages/spree/src/utils/normalizations/normalize-user.ts +++ b/packages/spree/src/utils/normalizations/normalize-user.ts @@ -6,10 +6,11 @@ const normalizeUser = ( _spreeSuccessResponse: SpreeSdkResponse, spreeUser: AccountAttr ): Customer => { - const email = spreeUser.attributes.email - return { - email, + id: spreeUser.id, + email: spreeUser.attributes.email, + firstName: spreeUser.attributes.firstname, + lastName: spreeUser.attributes.lastname, } } diff --git a/packages/spree/src/utils/normalizations/normalize-wishlist.ts b/packages/spree/src/utils/normalizations/normalize-wishlist.ts index c9cfee2dbf..4910b4765e 100644 --- a/packages/spree/src/utils/normalizations/normalize-wishlist.ts +++ b/packages/spree/src/utils/normalizations/normalize-wishlist.ts @@ -4,59 +4,54 @@ import { jsonApi } from '@spree/storefront-api-v2-sdk' import type { ProductAttr } from '@spree/storefront-api-v2-sdk/types/interfaces/Product' import type { WishedItemAttr } from '@spree/storefront-api-v2-sdk/types/interfaces/WishedItem' import type { WishlistAttr } from '@spree/storefront-api-v2-sdk/types/interfaces/Wishlist' -import type { - ExplicitCommerceWishlist, - SpreeSdkResponse, - VariantAttr, -} from '../../types' +import type { SpreeSdkResponse, VariantAttr } from '../../types' import normalizeProduct from './normalize-product' +import { Wishlist } from '@vercel/commerce/types/wishlist' const normalizeWishlist = ( spreeSuccessResponse: SpreeSdkResponse, spreeWishlist: WishlistAttr -): ExplicitCommerceWishlist => { +): Wishlist => { const spreeWishedItems = jsonApi.findRelationshipDocuments( spreeSuccessResponse, spreeWishlist, 'wished_items' ) - const items: ExplicitCommerceWishlist['items'] = spreeWishedItems.map( - (spreeWishedItem) => { - const spreeWishedVariant = - jsonApi.findSingleRelationshipDocument( - spreeSuccessResponse, - spreeWishedItem, - 'variant' - ) - - if (spreeWishedVariant === null) { - throw new MissingVariantError( - `Couldn't find variant for wished item with id ${spreeWishedItem.id}.` - ) - } - - const spreeWishedProduct = - jsonApi.findSingleRelationshipDocument( - spreeSuccessResponse, - spreeWishedVariant, - 'product' - ) + const items: Wishlist['items'] = spreeWishedItems.map((spreeWishedItem) => { + const spreeWishedVariant = + jsonApi.findSingleRelationshipDocument( + spreeSuccessResponse, + spreeWishedItem, + 'variant' + ) + + if (spreeWishedVariant === null) { + throw new MissingVariantError( + `Couldn't find variant for wished item with id ${spreeWishedItem.id}.` + ) + } - if (spreeWishedProduct === null) { - throw new MissingProductError( - `Couldn't find product for variant with id ${spreeWishedVariant.id}.` - ) - } + const spreeWishedProduct = + jsonApi.findSingleRelationshipDocument( + spreeSuccessResponse, + spreeWishedVariant, + 'product' + ) + + if (spreeWishedProduct === null) { + throw new MissingProductError( + `Couldn't find product for variant with id ${spreeWishedVariant.id}.` + ) + } - return { - id: spreeWishedItem.id, - product_id: parseInt(spreeWishedProduct.id, 10), - variant_id: parseInt(spreeWishedVariant.id, 10), - product: normalizeProduct(spreeSuccessResponse, spreeWishedProduct), - } + return { + id: spreeWishedItem.id, + productId: spreeWishedProduct.id, + variantId: spreeWishedVariant.id, + product: normalizeProduct(spreeSuccessResponse, spreeWishedProduct), } - ) + }) return { id: spreeWishlist.id, diff --git a/packages/spree/src/wishlist/use-add-item.tsx b/packages/spree/src/wishlist/use-add-item.tsx index 010a71e7d1..b806ac0fee 100644 --- a/packages/spree/src/wishlist/use-add-item.tsx +++ b/packages/spree/src/wishlist/use-add-item.tsx @@ -2,8 +2,9 @@ import { useCallback } from 'react' import type { MutationHook } from '@vercel/commerce/utils/types' import useAddItem from '@vercel/commerce/wishlist/use-add-item' import type { UseAddItem } from '@vercel/commerce/wishlist/use-add-item' +import type { AddItemHook } from '@vercel/commerce/types/wishlist' import useWishlist from './use-wishlist' -import type { ExplicitWishlistAddItemHook } from '../types' + import type { WishedItem, WishlistsAddWishedItem, @@ -11,12 +12,12 @@ import type { import type { GraphQLFetcherResult } from '@vercel/commerce/api' import ensureIToken from '../utils/tokens/ensure-itoken' import type { IToken } from '@spree/storefront-api-v2-sdk/types/interfaces/Token' -import type { AddItemHook } from '@vercel/commerce/types/wishlist' + import isLoggedIn from '../utils/tokens/is-logged-in' export default useAddItem as UseAddItem -export const handler: MutationHook = { +export const handler: MutationHook = { fetchOptions: { url: 'wishlists', query: 'addWishedItem', @@ -31,7 +32,7 @@ export const handler: MutationHook = { ) const { - item: { productId, variantId, wishlistToken }, + item: { variantId, wishlistToken }, } = input if (!isLoggedIn() || !wishlistToken) { diff --git a/packages/spree/src/wishlist/use-remove-item.tsx b/packages/spree/src/wishlist/use-remove-item.tsx index d8481f5a32..6273ef4289 100644 --- a/packages/spree/src/wishlist/use-remove-item.tsx +++ b/packages/spree/src/wishlist/use-remove-item.tsx @@ -2,8 +2,8 @@ import { useCallback } from 'react' import type { MutationHook } from '@vercel/commerce/utils/types' import useRemoveItem from '@vercel/commerce/wishlist/use-remove-item' import type { UseRemoveItem } from '@vercel/commerce/wishlist/use-remove-item' +import type { RemoveItemHook } from '@vercel/commerce/types/wishlist' import useWishlist from './use-wishlist' -import type { ExplicitWishlistRemoveItemHook } from '../types' import isLoggedIn from '../utils/tokens/is-logged-in' import ensureIToken from '../utils/tokens/ensure-itoken' import type { IToken } from '@spree/storefront-api-v2-sdk/types/interfaces/Token' @@ -12,7 +12,7 @@ import type { WishedItem } from '@spree/storefront-api-v2-sdk/types/interfaces/W export default useRemoveItem as UseRemoveItem -export const handler: MutationHook = { +export const handler: MutationHook = { fetchOptions: { url: 'wishlists', query: 'removeWishedItem', @@ -45,7 +45,7 @@ export const handler: MutationHook = { }, useHook: ({ fetch }) => { const useWrappedHook: ReturnType< - MutationHook['useHook'] + MutationHook['useHook'] > = () => { const wishlist = useWishlist() diff --git a/packages/spree/src/wishlist/use-wishlist.tsx b/packages/spree/src/wishlist/use-wishlist.tsx index 9f258625ed..dfd264aada 100644 --- a/packages/spree/src/wishlist/use-wishlist.tsx +++ b/packages/spree/src/wishlist/use-wishlist.tsx @@ -9,6 +9,7 @@ import type { Wishlist } from '@spree/storefront-api-v2-sdk/types/interfaces/Wis import ensureIToken from '../utils/tokens/ensure-itoken' import normalizeWishlist from '../utils/normalizations/normalize-wishlist' import isLoggedIn from '../utils/tokens/is-logged-in' +import { ValidationError } from '@vercel/commerce/utils/errors' export default useWishlist as UseWishlist @@ -28,7 +29,9 @@ export const handler: SWRHook = { ) if (!isLoggedIn()) { - return null + throw new ValidationError({ + message: 'Not logged in', + }) } // TODO: Optimize with includeProducts. diff --git a/packages/swell/src/api/operations/get-all-pages.ts b/packages/swell/src/api/operations/get-all-pages.ts index 7097d68590..13ae77b833 100644 --- a/packages/swell/src/api/operations/get-all-pages.ts +++ b/packages/swell/src/api/operations/get-all-pages.ts @@ -1,6 +1,6 @@ -import { Provider, SwellConfig } from '..' +import type { Provider, SwellConfig } from '..' import type { OperationContext } from '@vercel/commerce/api/operations' -import type { Page } from '../../types/page' +import type { Page } from '@vercel/commerce/types/page' export type GetAllPagesResult = T @@ -31,10 +31,13 @@ export default function getAllPagesOperation({ const { locale, fetch } = config const data = await fetch('content', 'list', ['pages']) const pages = - data?.results?.map(({ slug, ...rest }: { slug: string }) => ({ - url: `/${locale}/${slug}`, - ...rest, - })) ?? [] + data?.results?.map( + ({ slug, body, ...rest }: { slug: string; body: string }) => ({ + ...rest, + url: `/${locale}/${slug}`, + body: body ?? '', + }) + ) ?? [] return { pages, } diff --git a/packages/swell/src/api/operations/get-page.ts b/packages/swell/src/api/operations/get-page.ts index 7e71f75751..5fc4d282e5 100644 --- a/packages/swell/src/api/operations/get-page.ts +++ b/packages/swell/src/api/operations/get-page.ts @@ -1,10 +1,10 @@ -import { Page } from '../../../schema' -import { SwellConfig, Provider } from '..' -import { +import type { Page } from '../../../schema' +import type { SwellConfig, Provider } from '..' +import type { OperationContext, OperationOptions, } from '@vercel/commerce/api/operations' -import { GetPageOperation } from '../../types/page' +import type { GetPageOperation } from '@vercel/commerce/types/page' export type GetPageResult = T @@ -48,6 +48,7 @@ export default function getPageOperation({ ? { ...page, url: `/${locale}/${page.slug}`, + body: page.body ?? '', } : null, } diff --git a/packages/swell/src/api/operations/get-site-info.ts b/packages/swell/src/api/operations/get-site-info.ts index 88386ad3e5..44f8d200ce 100644 --- a/packages/swell/src/api/operations/get-site-info.ts +++ b/packages/swell/src/api/operations/get-site-info.ts @@ -1,13 +1,13 @@ import getCategories from '../../utils/get-categories' -import getVendors, { Brands } from '../../utils/get-vendors' +import getVendors from '../../utils/get-vendors' import { Provider, SwellConfig } from '../' import type { OperationContext } from '@vercel/commerce/api/operations' -import type { Category } from '@vercel/commerce/types/site' +import type { Brand, Category } from '@vercel/commerce/types/site' export type GetSiteInfoResult< T extends { categories: any[]; brands: any[] } = { categories: Category[] - brands: Brands + brands: Brand[] } > = T diff --git a/packages/swell/src/api/operations/login.ts b/packages/swell/src/api/operations/login.ts index 44ff37a537..cd1c776559 100644 --- a/packages/swell/src/api/operations/login.ts +++ b/packages/swell/src/api/operations/login.ts @@ -3,7 +3,7 @@ import type { OperationContext, OperationOptions, } from '@vercel/commerce/api/operations' -import type { LoginOperation } from '../../types/login' +import type { LoginOperation } from '@vercel/commerce/types/login' import { Provider, SwellConfig } from '..' export default function loginOperation({ diff --git a/packages/swell/src/auth/use-login.tsx b/packages/swell/src/auth/use-login.tsx index b3fe9f52d7..ea7110aca4 100644 --- a/packages/swell/src/auth/use-login.tsx +++ b/packages/swell/src/auth/use-login.tsx @@ -1,14 +1,15 @@ -import { useCallback } from 'react' +import type { LoginHook } from '@vercel/commerce/types/login' import type { MutationHook } from '@vercel/commerce/utils/types' -import { CommerceError, ValidationError } from '@vercel/commerce/utils/errors' -import useCustomer from '../customer/use-customer' -import { +import type { CustomerUserError, Mutation, MutationCheckoutCreateArgs, } from '../../schema' -import useLogin, { UseLogin } from '@vercel/commerce/auth/use-login' -import { LoginHook } from '../types/login' + +import { useCallback } from 'react' +import { CommerceError, ValidationError } from '@vercel/commerce/utils/errors' +import useCustomer from '../customer/use-customer' +import useLogin, { type UseLogin } from '@vercel/commerce/auth/use-login' import { setCustomerToken } from '../utils' export default useLogin as UseLogin diff --git a/packages/swell/src/auth/use-logout.tsx b/packages/swell/src/auth/use-logout.tsx index 08eec0bac7..e0fdb8ff6d 100644 --- a/packages/swell/src/auth/use-logout.tsx +++ b/packages/swell/src/auth/use-logout.tsx @@ -1,9 +1,10 @@ -import { useCallback } from 'react' +import type { LogoutHook } from '@vercel/commerce/types/logout' import type { MutationHook } from '@vercel/commerce/utils/types' + +import { useCallback } from 'react' import useLogout, { UseLogout } from '@vercel/commerce/auth/use-logout' import useCustomer from '../customer/use-customer' import { getCustomerToken, setCustomerToken } from '../utils/customer-token' -import { LogoutHook } from '../types/logout' export default useLogout as UseLogout diff --git a/packages/swell/src/auth/use-signup.tsx b/packages/swell/src/auth/use-signup.tsx index 581312db96..080302791c 100644 --- a/packages/swell/src/auth/use-signup.tsx +++ b/packages/swell/src/auth/use-signup.tsx @@ -1,9 +1,10 @@ -import { useCallback } from 'react' +import type { SignupHook } from '@vercel/commerce/types/signup' import type { MutationHook } from '@vercel/commerce/utils/types' + +import { useCallback } from 'react' import { CommerceError } from '@vercel/commerce/utils/errors' -import useSignup, { UseSignup } from '@vercel/commerce/auth/use-signup' +import useSignup, { type UseSignup } from '@vercel/commerce/auth/use-signup' import useCustomer from '../customer/use-customer' -import { SignupHook } from '../types/signup' import handleLogin from '../utils/handle-login' export default useSignup as UseSignup diff --git a/packages/swell/src/cart/use-add-item.tsx b/packages/swell/src/cart/use-add-item.tsx index 048a1f45d2..e80c716242 100644 --- a/packages/swell/src/cart/use-add-item.tsx +++ b/packages/swell/src/cart/use-add-item.tsx @@ -1,11 +1,12 @@ +import type { AddItemHook } from '@vercel/commerce/types/cart' import type { MutationHook } from '@vercel/commerce/utils/types' + import { CommerceError } from '@vercel/commerce/utils/errors' -import useAddItem, { UseAddItem } from '@vercel/commerce/cart/use-add-item' +import useAddItem, { type UseAddItem } from '@vercel/commerce/cart/use-add-item' import useCart from './use-cart' import { checkoutToCart } from './utils' import { getCheckoutId } from '../utils' import { useCallback } from 'react' -import { AddItemHook } from '../types/cart' export default useAddItem as UseAddItem diff --git a/packages/swell/src/cart/use-update-item.tsx b/packages/swell/src/cart/use-update-item.tsx index c741250c28..8a3a5191b4 100644 --- a/packages/swell/src/cart/use-update-item.tsx +++ b/packages/swell/src/cart/use-update-item.tsx @@ -1,23 +1,25 @@ -import { useCallback } from 'react' -import debounce from 'lodash.debounce' import type { HookFetcherContext, - MutationHook, MutationHookContext, } from '@vercel/commerce/utils/types' + +import type { UpdateItemHook, LineItem } from '@vercel/commerce/types/cart' + +import { useCallback } from 'react' +import debounce from 'lodash.debounce' + import { ValidationError } from '@vercel/commerce/utils/errors' // import useUpdateItem, { // UpdateItemInput as UpdateItemInputBase, // UseUpdateItem, // } from '@vercel/commerce/cart/use-update-item' import useUpdateItem, { - UseUpdateItem, + type UseUpdateItem, } from '@vercel/commerce/cart/use-update-item' import useCart from './use-cart' import { handler as removeItemHandler } from './use-remove-item' -import { CartItemBody, LineItem } from '@vercel/commerce/types/cart' import { checkoutToCart } from './utils' -import { UpdateItemHook } from '../types/cart' + // export type UpdateItemInput = T extends LineItem // ? Partial> // : UpdateItemInputBase diff --git a/packages/swell/src/cart/utils/checkout-to-cart.ts b/packages/swell/src/cart/utils/checkout-to-cart.ts index c9becb1047..af7d896022 100644 --- a/packages/swell/src/cart/utils/checkout-to-cart.ts +++ b/packages/swell/src/cart/utils/checkout-to-cart.ts @@ -1,4 +1,4 @@ -import { Cart } from '../../types' +import type { Cart } from '@vercel/commerce/types/cart' import { CommerceError } from '@vercel/commerce/utils/errors' import { diff --git a/packages/swell/src/customer/use-customer.tsx b/packages/swell/src/customer/use-customer.tsx index 0875310fdd..45b81b2ff5 100644 --- a/packages/swell/src/customer/use-customer.tsx +++ b/packages/swell/src/customer/use-customer.tsx @@ -1,9 +1,10 @@ +import type { SWRHook } from '@vercel/commerce/utils/types' +import type { CustomerHook } from '@vercel/commerce/types/customer' + import useCustomer, { - UseCustomer, + type UseCustomer, } from '@vercel/commerce/customer/use-customer' -import { SWRHook } from '@vercel/commerce/utils/types' import { normalizeCustomer } from '../utils/normalize' -import type { CustomerHook } from '../types/customer' export default useCustomer as UseCustomer diff --git a/packages/swell/src/product/use-search.tsx b/packages/swell/src/product/use-search.tsx index b996099a44..81f8596d94 100644 --- a/packages/swell/src/product/use-search.tsx +++ b/packages/swell/src/product/use-search.tsx @@ -1,8 +1,9 @@ +import type { SwellProduct } from '../types' +import type { SearchProductsHook } from '@vercel/commerce/types/product' + import { SWRHook } from '@vercel/commerce/utils/types' -import useSearch, { UseSearch } from '@vercel/commerce/product/use-search' +import useSearch, { type UseSearch } from '@vercel/commerce/product/use-search' import { normalizeProduct } from '../utils' -import { SwellProduct } from '../types' -import type { SearchProductsHook } from '../types/product' export default useSearch as UseSearch diff --git a/packages/swell/src/types.ts b/packages/swell/src/types.ts index b02bbd8cac..5d3e7507ea 100644 --- a/packages/swell/src/types.ts +++ b/packages/swell/src/types.ts @@ -1,6 +1,4 @@ -import * as Core from '@vercel/commerce/types/cart' -import { Customer } from '@vercel/commerce/types' -import { CheckoutLineItem } from '../schema' +import type { CheckoutLineItem } from '../schema' export type SwellImage = { file: { @@ -88,15 +86,6 @@ export type SwellCheckout = { lineItems: CheckoutLineItem[] } -export interface Cart extends Core.Cart { - id: string - lineItems: LineItem[] -} - -export interface LineItem extends Core.LineItem { - options?: any[] -} - /** * Cart mutations */ @@ -105,8 +94,3 @@ export type OptionSelections = { option_id: number option_value: number | string } - -export type CartItemBody = Core.CartItemBody & { - productId: string // The product id is always required for BC - optionSelections?: OptionSelections -} diff --git a/packages/swell/src/types/login.ts b/packages/swell/src/types/login.ts index 44b017dcd2..438d541b2c 100644 --- a/packages/swell/src/types/login.ts +++ b/packages/swell/src/types/login.ts @@ -1,11 +1 @@ -import * as Core from '@vercel/commerce/types/login' -import { LoginBody, LoginTypes } from '@vercel/commerce/types/login' - export * from '@vercel/commerce/types/login' - -export type LoginHook = { - data: null - actionInput: LoginBody - fetcherInput: LoginBody - body: T['body'] -} diff --git a/packages/swell/src/utils/get-categories.ts b/packages/swell/src/utils/get-categories.ts index ab38bae961..ee951b3357 100644 --- a/packages/swell/src/utils/get-categories.ts +++ b/packages/swell/src/utils/get-categories.ts @@ -1,5 +1,5 @@ import { SwellConfig } from '../api' -import { Category } from '../types/site' +import type { Category } from '@vercel/commerce/types/site' const getCategories = async (config: SwellConfig): Promise => { const data = await config.fetch('categories', 'get') diff --git a/packages/swell/src/utils/get-vendors.ts b/packages/swell/src/utils/get-vendors.ts index 1ede68835a..cef70fa917 100644 --- a/packages/swell/src/utils/get-vendors.ts +++ b/packages/swell/src/utils/get-vendors.ts @@ -1,26 +1,14 @@ import { SwellConfig } from '../api' -export type BrandNode = { - name: string - path: string -} - -export type BrandEdge = { - node: BrandNode -} - -export type Brands = BrandEdge[] - const getVendors = async (config: SwellConfig) => { const vendors: [string] = (await config.fetch('attributes', 'get', ['brand']))?.values ?? [] return [...new Set(vendors)].map((v) => ({ - node: { - entityId: v, - name: v, - path: `brands/${v}`, - }, + id: v, + name: v, + slug: v.replace(/\s+/g, '-').toLowerCase(), + path: `/${v}`, })) } diff --git a/packages/swell/src/utils/normalize.ts b/packages/swell/src/utils/normalize.ts index 9bbad5961c..89bcd06f07 100644 --- a/packages/swell/src/utils/normalize.ts +++ b/packages/swell/src/utils/normalize.ts @@ -1,9 +1,9 @@ -import { Customer } from '../types/customer' -import { Product, ProductOption } from '../types/product' -import { MoneyV2 } from '../../schema' +import type { Cart, LineItem } from '@vercel/commerce/types/cart' +import type { Customer } from '@vercel/commerce/types/customer' +import type { Product, ProductOption } from '@vercel/commerce/types/product' +import type { MoneyV2 } from '../../schema' import type { - Cart, CartLineItem, SwellCustomer, SwellProduct, @@ -12,7 +12,6 @@ import type { ProductOptionValue, SwellProductOptionValue, SwellCart, - LineItem, } from '../types' const money = ({ amount, currencyCode }: MoneyV2) => { @@ -121,7 +120,6 @@ export function normalizeProduct(swellProduct: SwellProduct): Product { currency: currencyCode, } = swellProduct // ProductView accesses variants for each product - const emptyVariants = [{ options: [], id, name }] const productOptions = options ? options.map((o) => normalizeProductOption(o)) @@ -138,10 +136,7 @@ export function normalizeProduct(swellProduct: SwellProduct): Product { vendor: '', path: `/${slug}`, images: productImages, - variants: - productVariants && productVariants.length - ? productVariants - : emptyVariants, + variants: productVariants && productVariants.length ? productVariants : [], options: productOptions, price: { value, @@ -214,11 +209,12 @@ function normalizeLineItem({ price: price, listPrice: price, }, - path: '', + path: `/${product.slug}`, discounts: [], options: [ { - value: variant?.name, + name: variant?.name!, + value: variant?.name!, }, ], } diff --git a/packages/swell/src/wishlist/use-wishlist.tsx b/packages/swell/src/wishlist/use-wishlist.tsx index 0506ae9d45..4d99aca1d4 100644 --- a/packages/swell/src/wishlist/use-wishlist.tsx +++ b/packages/swell/src/wishlist/use-wishlist.tsx @@ -1,22 +1,11 @@ // TODO: replace this hook and other wishlist hooks with a handler, or remove them if // Swell doesn't have a wishlist +import type { Wishlist } from '@vercel/commerce/types/wishlist' import { HookFetcher } from '@vercel/commerce/utils/types' -import { Product } from '../../schema' const defaultOpts = {} -export type Wishlist = { - items: [ - { - product_id: number - variant_id: number - id: number - product: Product - } - ] -} - export interface UseWishlistOptions { includeProducts?: boolean } diff --git a/packages/vendure/src/api/operations/get-product.ts b/packages/vendure/src/api/operations/get-product.ts index 6b58e96941..93fb50f1eb 100644 --- a/packages/vendure/src/api/operations/get-product.ts +++ b/packages/vendure/src/api/operations/get-product.ts @@ -33,6 +33,7 @@ export default function getProductOperation({ name: product.name, description: product.description, slug: product.slug, + path: `/${product.slug}`, images: product.assets.map((a) => ({ url: a.preview, alt: a.name, diff --git a/packages/vendure/src/api/operations/get-site-info.ts b/packages/vendure/src/api/operations/get-site-info.ts index ce2f5fa3fb..b3dcc48e73 100644 --- a/packages/vendure/src/api/operations/get-site-info.ts +++ b/packages/vendure/src/api/operations/get-site-info.ts @@ -33,8 +33,8 @@ export default function getSiteInfoOperation({ }) const collections = data.collections?.items.map((i) => ({ ...i, - entityId: i.id, - path: i.slug, + id: i.id, + path: `/${i.id}`, productCount: i.productVariants.totalItems, })) const categories = arrayToTree(collections).children diff --git a/packages/vendure/src/api/operations/login.ts b/packages/vendure/src/api/operations/login.ts index 07ee5fa1df..494af1f75c 100644 --- a/packages/vendure/src/api/operations/login.ts +++ b/packages/vendure/src/api/operations/login.ts @@ -4,7 +4,7 @@ import type { OperationOptions, } from '@vercel/commerce/api/operations' import { ValidationError } from '@vercel/commerce/utils/errors' -import type { LoginOperation } from '../../types/login' +import type { LoginOperation } from '@vercel/commerce/types/login' import type { LoginMutation } from '../../../schema' import { Provider, VendureConfig } from '..' import { loginMutation } from '../../utils/mutations/log-in-mutation' diff --git a/packages/vendure/src/api/utils/fetch-graphql-api.ts b/packages/vendure/src/api/utils/fetch-graphql-api.ts index 7c0fbc7925..97aaba178e 100644 --- a/packages/vendure/src/api/utils/fetch-graphql-api.ts +++ b/packages/vendure/src/api/utils/fetch-graphql-api.ts @@ -9,6 +9,7 @@ const fetchGraphqlApi: GraphQLFetcher = async ( fetchOptions ) => { const config = getCommerceApi().getConfig() + const res = await fetch(config.commerceUrl, { ...fetchOptions, method: 'POST', @@ -23,6 +24,7 @@ const fetchGraphqlApi: GraphQLFetcher = async ( }) const json = await res.json() + if (json.errors) { throw new FetcherError({ errors: json.errors ?? [{ message: 'Failed to fetch Vendure API' }], diff --git a/packages/vendure/src/auth/use-login.tsx b/packages/vendure/src/auth/use-login.tsx index ce1a454566..56c701119b 100644 --- a/packages/vendure/src/auth/use-login.tsx +++ b/packages/vendure/src/auth/use-login.tsx @@ -1,10 +1,10 @@ import { useCallback } from 'react' import { MutationHook } from '@vercel/commerce/utils/types' -import useLogin, { UseLogin } from '@vercel/commerce/auth/use-login' -import { LoginHook } from '../types/login' +import useLogin, { type UseLogin } from '@vercel/commerce/auth/use-login' +import type { LoginHook } from '@vercel/commerce/types/login' import { CommerceError, ValidationError } from '@vercel/commerce/utils/errors' import useCustomer from '../customer/use-customer' -import { LoginMutation, LoginMutationVariables } from '../../schema' +import type { LoginMutation, LoginMutationVariables } from '../../schema' import { loginMutation } from '../utils/mutations/log-in-mutation' export default useLogin as UseLogin diff --git a/packages/vendure/src/auth/use-logout.tsx b/packages/vendure/src/auth/use-logout.tsx index 8a099cf77e..e24976a94b 100644 --- a/packages/vendure/src/auth/use-logout.tsx +++ b/packages/vendure/src/auth/use-logout.tsx @@ -1,10 +1,10 @@ import { useCallback } from 'react' -import { MutationHook } from '@vercel/commerce/utils/types' -import useLogout, { UseLogout } from '@vercel/commerce/auth/use-logout' +import type { MutationHook } from '@vercel/commerce/utils/types' +import useLogout, { type UseLogout } from '@vercel/commerce/auth/use-logout' import useCustomer from '../customer/use-customer' -import { LogoutMutation } from '../../schema' +import type { LogoutMutation } from '../../schema' import { logoutMutation } from '../utils/mutations/log-out-mutation' -import { LogoutHook } from '../types/logout' +import type { LogoutHook } from '@vercel/commerce/types/logout' export default useLogout as UseLogout diff --git a/packages/vendure/src/auth/use-signup.tsx b/packages/vendure/src/auth/use-signup.tsx index 0c19c91bb4..3586ca66bc 100644 --- a/packages/vendure/src/auth/use-signup.tsx +++ b/packages/vendure/src/auth/use-signup.tsx @@ -1,15 +1,11 @@ import { useCallback } from 'react' import { MutationHook } from '@vercel/commerce/utils/types' import { CommerceError, ValidationError } from '@vercel/commerce/utils/errors' -import useSignup, { UseSignup } from '@vercel/commerce/auth/use-signup' +import useSignup, { type UseSignup } from '@vercel/commerce/auth/use-signup' import useCustomer from '../customer/use-customer' -import { - RegisterCustomerInput, - SignupMutation, - SignupMutationVariables, -} from '../../schema' +import type { SignupMutation, SignupMutationVariables } from '../../schema' import { signupMutation } from '../utils/mutations/sign-up-mutation' -import { SignupHook } from '../types/signup' +import type { SignupHook } from '@vercel/commerce/types/signup' export default useSignup as UseSignup diff --git a/packages/vendure/src/cart/use-add-item.tsx b/packages/vendure/src/cart/use-add-item.tsx index d7bb0bf667..1b6f85040f 100644 --- a/packages/vendure/src/cart/use-add-item.tsx +++ b/packages/vendure/src/cart/use-add-item.tsx @@ -1,12 +1,12 @@ import useAddItem, { UseAddItem } from '@vercel/commerce/cart/use-add-item' import { CommerceError } from '@vercel/commerce/utils/errors' -import { MutationHook } from '@vercel/commerce/utils/types' +import type { MutationHook } from '@vercel/commerce/utils/types' import { useCallback } from 'react' import useCart from './use-cart' import { AddItemToOrderMutation } from '../../schema' import { normalizeCart } from '../utils/normalize' import { addItemToOrderMutation } from '../utils/mutations/add-item-to-order-mutation' -import { AddItemHook } from '../types/cart' +import type { AddItemHook } from '@vercel/commerce/types/cart' export default useAddItem as UseAddItem diff --git a/packages/vendure/src/cart/use-cart.tsx b/packages/vendure/src/cart/use-cart.tsx index 750f110407..e298bf9f4e 100644 --- a/packages/vendure/src/cart/use-cart.tsx +++ b/packages/vendure/src/cart/use-cart.tsx @@ -1,10 +1,10 @@ import { SWRHook } from '@vercel/commerce/utils/types' -import useCart, { UseCart } from '@vercel/commerce/cart/use-cart' +import useCart, { type UseCart } from '@vercel/commerce/cart/use-cart' import { ActiveOrderQuery, CartFragment } from '../../schema' import { normalizeCart } from '../utils/normalize' import { useMemo } from 'react' import { getCartQuery } from '../utils/queries/get-cart-query' -import { GetCartHook } from '../types/cart' +import type { GetCartHook } from '@vercel/commerce/types/cart' export type CartResult = { activeOrder?: CartFragment diff --git a/packages/vendure/src/cart/use-remove-item.tsx b/packages/vendure/src/cart/use-remove-item.tsx index 2aa316505b..fbd07a31e5 100644 --- a/packages/vendure/src/cart/use-remove-item.tsx +++ b/packages/vendure/src/cart/use-remove-item.tsx @@ -1,22 +1,17 @@ import { useCallback } from 'react' -import { - HookFetcherContext, - MutationHook, - MutationHookContext, - SWRHook, -} from '@vercel/commerce/utils/types' +import type { MutationHook } from '@vercel/commerce/utils/types' import useRemoveItem, { UseRemoveItem, } from '@vercel/commerce/cart/use-remove-item' import { CommerceError } from '@vercel/commerce/utils/errors' -import { Cart } from '@vercel/commerce/types/cart' + import useCart from './use-cart' import { RemoveOrderLineMutation, RemoveOrderLineMutationVariables, } from '../../schema' import { normalizeCart } from '../utils/normalize' -import { RemoveItemHook } from '../types/cart' +import type { RemoveItemHook } from '@vercel/commerce/types/cart' import { removeOrderLineMutation } from '../utils/mutations/remove-order-line-mutation' export default useRemoveItem as UseRemoveItem diff --git a/packages/vendure/src/cart/use-update-item.tsx b/packages/vendure/src/cart/use-update-item.tsx index 2f3c8d47b3..f97f15d1d0 100644 --- a/packages/vendure/src/cart/use-update-item.tsx +++ b/packages/vendure/src/cart/use-update-item.tsx @@ -8,7 +8,6 @@ import { CommerceError, ValidationError } from '@vercel/commerce/utils/errors' import useUpdateItem, { UseUpdateItem, } from '@vercel/commerce/cart/use-update-item' -import { CartItemBody, LineItem } from '@vercel/commerce/types/cart' import useCart from './use-cart' import { AdjustOrderLineMutation, @@ -16,7 +15,7 @@ import { } from '../../schema' import { normalizeCart } from '../utils/normalize' import { adjustOrderLineMutation } from '../utils/mutations/adjust-order-line-mutation' -import { UpdateItemHook } from '../types/cart' +import type { UpdateItemHook, LineItem } from '@vercel/commerce/types/cart' export type UpdateItemActionInput = T extends LineItem ? Partial diff --git a/packages/vendure/src/customer/use-customer.tsx b/packages/vendure/src/customer/use-customer.tsx index 80da077ff5..00b14a46ab 100644 --- a/packages/vendure/src/customer/use-customer.tsx +++ b/packages/vendure/src/customer/use-customer.tsx @@ -4,7 +4,7 @@ import useCustomer, { } from '@vercel/commerce/customer/use-customer' import { ActiveCustomerQuery } from '../../schema' import { activeCustomerQuery } from '../utils/queries/active-customer-query' -import { CustomerHook } from '../types/customer' +import { CustomerHook } from '@vercel/commerce/types/customer' export default useCustomer as UseCustomer diff --git a/packages/vendure/src/fetcher.ts b/packages/vendure/src/fetcher.ts index ad0d4bc66f..e98b25c4ea 100644 --- a/packages/vendure/src/fetcher.ts +++ b/packages/vendure/src/fetcher.ts @@ -44,7 +44,7 @@ export const fetcher: Fetcher = async ({ if (res.ok) { const { data, errors } = await res.json() if (errors) { - throw await new FetcherError({ status: res.status, errors }) + throw new FetcherError({ status: res.status, errors }) } return data } diff --git a/packages/vendure/src/product/use-search.tsx b/packages/vendure/src/product/use-search.tsx index 86c6467d13..bd380cf41b 100644 --- a/packages/vendure/src/product/use-search.tsx +++ b/packages/vendure/src/product/use-search.tsx @@ -4,7 +4,7 @@ import { Product } from '@vercel/commerce/types/product' import { SearchQuery, SearchQueryVariables } from '../../schema' import { normalizeSearchResult } from '../utils/normalize' import { searchQuery } from '../utils/queries/search-query' -import { SearchProductsHook } from '../types/product' +import type { SearchProductsHook } from '@vercel/commerce/types/product' export default useSearch as UseSearch diff --git a/packages/vendure/src/types/cart.ts b/packages/vendure/src/types/cart.ts deleted file mode 100644 index e6838fb456..0000000000 --- a/packages/vendure/src/types/cart.ts +++ /dev/null @@ -1 +0,0 @@ -export * from '@vercel/commerce/types/cart' diff --git a/packages/vendure/src/types/checkout.ts b/packages/vendure/src/types/checkout.ts deleted file mode 100644 index d139db6859..0000000000 --- a/packages/vendure/src/types/checkout.ts +++ /dev/null @@ -1 +0,0 @@ -export * from '@vercel/commerce/types/checkout' diff --git a/packages/vendure/src/types/common.ts b/packages/vendure/src/types/common.ts deleted file mode 100644 index 23b8daa11c..0000000000 --- a/packages/vendure/src/types/common.ts +++ /dev/null @@ -1 +0,0 @@ -export * from '@vercel/commerce/types/common' diff --git a/packages/vendure/src/types/customer.ts b/packages/vendure/src/types/customer.ts deleted file mode 100644 index c637055b94..0000000000 --- a/packages/vendure/src/types/customer.ts +++ /dev/null @@ -1 +0,0 @@ -export * from '@vercel/commerce/types/customer' diff --git a/packages/vendure/src/types/index.ts b/packages/vendure/src/types/index.ts deleted file mode 100644 index 7ab0b7f64f..0000000000 --- a/packages/vendure/src/types/index.ts +++ /dev/null @@ -1,25 +0,0 @@ -import * as Cart from './cart' -import * as Checkout from './checkout' -import * as Common from './common' -import * as Customer from './customer' -import * as Login from './login' -import * as Logout from './logout' -import * as Page from './page' -import * as Product from './product' -import * as Signup from './signup' -import * as Site from './site' -import * as Wishlist from './wishlist' - -export type { - Cart, - Checkout, - Common, - Customer, - Login, - Logout, - Page, - Product, - Signup, - Site, - Wishlist, -} diff --git a/packages/vendure/src/types/login.ts b/packages/vendure/src/types/login.ts deleted file mode 100644 index 283a5751c6..0000000000 --- a/packages/vendure/src/types/login.ts +++ /dev/null @@ -1,12 +0,0 @@ -import * as Core from '@vercel/commerce/types/login' -import type { LoginMutationVariables } from '../../schema' -import { LoginBody, LoginTypes } from '@vercel/commerce/types/login' - -export * from '@vercel/commerce/types/login' - -export type LoginHook = { - data: null - actionInput: LoginBody - fetcherInput: LoginBody - body: T['body'] -} diff --git a/packages/vendure/src/types/logout.ts b/packages/vendure/src/types/logout.ts deleted file mode 100644 index 1de06f8dc8..0000000000 --- a/packages/vendure/src/types/logout.ts +++ /dev/null @@ -1 +0,0 @@ -export * from '@vercel/commerce/types/logout' diff --git a/packages/vendure/src/types/page.ts b/packages/vendure/src/types/page.ts deleted file mode 100644 index 12f6b02d71..0000000000 --- a/packages/vendure/src/types/page.ts +++ /dev/null @@ -1 +0,0 @@ -export * from '@vercel/commerce/types/page' diff --git a/packages/vendure/src/types/product.ts b/packages/vendure/src/types/product.ts deleted file mode 100644 index 72ca02f02d..0000000000 --- a/packages/vendure/src/types/product.ts +++ /dev/null @@ -1 +0,0 @@ -export * from '@vercel/commerce/types/product' diff --git a/packages/vendure/src/types/signup.ts b/packages/vendure/src/types/signup.ts deleted file mode 100644 index 3f0d1af5ac..0000000000 --- a/packages/vendure/src/types/signup.ts +++ /dev/null @@ -1 +0,0 @@ -export * from '@vercel/commerce/types/signup' diff --git a/packages/vendure/src/types/site.ts b/packages/vendure/src/types/site.ts deleted file mode 100644 index 96a2e476e9..0000000000 --- a/packages/vendure/src/types/site.ts +++ /dev/null @@ -1 +0,0 @@ -export * from '@vercel/commerce/types/site' diff --git a/packages/vendure/src/types/wishlist.ts b/packages/vendure/src/types/wishlist.ts deleted file mode 100644 index af92d9f63e..0000000000 --- a/packages/vendure/src/types/wishlist.ts +++ /dev/null @@ -1 +0,0 @@ -export * from '@vercel/commerce/types/wishlist' diff --git a/packages/vendure/src/utils/normalize.ts b/packages/vendure/src/utils/normalize.ts index adde43674a..9275ec2bf2 100644 --- a/packages/vendure/src/utils/normalize.ts +++ b/packages/vendure/src/utils/normalize.ts @@ -8,7 +8,7 @@ export function normalizeSearchResult(item: SearchResultFragment): Product { name: item.productName, description: item.description, slug: item.slug, - path: item.slug, + path: `/${item.slug}`, images: [ { url: item.productAsset?.preview @@ -45,7 +45,7 @@ export function normalizeCart(order: CartFragment): Cart { productId: l.productVariant.productId, images: [{ url: l.featuredAsset?.preview + '?preset=thumb' || '' }], discounts: l.discounts.map((d) => ({ value: d.amount / 100 })), - path: '', + path: `/${l.productVariant.product.slug}`, variant: { id: l.productVariant.id, name: l.productVariant.name, diff --git a/packages/vendure/src/wishlist/use-wishlist.tsx b/packages/vendure/src/wishlist/use-wishlist.tsx index ab4192171c..cb9dcc815b 100644 --- a/packages/vendure/src/wishlist/use-wishlist.tsx +++ b/packages/vendure/src/wishlist/use-wishlist.tsx @@ -1,22 +1,11 @@ // TODO: replace this hook and other wishlist hooks with a handler, or remove them if // Vendure doesn't have a built-in wishlist -import { HookFetcher } from '@vercel/commerce/utils/types' -import { Product } from '../../schema' +import type { HookFetcher } from '@vercel/commerce/utils/types' +import type { Wishlist } from '@vercel/commerce/types/wishlist' const defaultOpts = {} -export type Wishlist = { - items: [ - { - product_id: number - variant_id: number - id: number - product: Product - } - ] -} - export interface UseWishlistOptions { includeProducts?: boolean } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index f7de6016d4..d6135ebc33 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -90,6 +90,7 @@ importers: taskr: ^1.1.0 taskr-swc: ^0.0.1 typescript: ^4.7.4 + zod: ^3.19.0 dependencies: '@vercel/fetch': 6.2.0_wbqoqouw2iimn65bqgaw3lwmza deepmerge: 4.2.2 @@ -97,6 +98,7 @@ importers: js-cookie: 3.0.1 node-fetch: 2.6.7 swr: 1.3.0_react@18.2.0 + zod: 3.19.1 devDependencies: '@taskr/clear': 1.1.0 '@taskr/esnext': 1.1.0 @@ -710,7 +712,7 @@ importers: react-merge-refs: 2.0.1 react-use-measure: 2.1.1_biqbaboplfbrettd7655fr4n2y tabbable: 5.3.3 - tailwindcss: 3.1.8 + tailwindcss: 3.1.8_postcss@8.4.16 devDependencies: '@next/bundle-analyzer': 12.3.0 '@types/body-scroll-lock': 3.1.0 @@ -9044,10 +9046,12 @@ packages: resolution: {integrity: sha512-QD9qKY3StfbZqWOPLp0++pOrAVb/HbUi5xCc8cUo4XjP19808oaMiDzn0leBY5mCespIBM0CIZePzZjgzR83kA==} dev: false - /tailwindcss/3.1.8: + /tailwindcss/3.1.8_postcss@8.4.16: resolution: {integrity: sha512-YSneUCZSFDYMwk+TGq8qYFdCA3yfBRdBlS7txSq0LUmzyeqRe3a8fBQzbz9M3WS/iFT4BNf/nmw9mEzrnSaC0g==} engines: {node: '>=12.13.0'} hasBin: true + peerDependencies: + postcss: ^8.0.9 dependencies: arg: 5.0.2 chokidar: 3.5.3 @@ -9844,3 +9848,7 @@ packages: resolution: {integrity: sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==} engines: {node: '>=10'} dev: true + + /zod/3.19.1: + resolution: {integrity: sha512-LYjZsEDhCdYET9ikFu6dVPGp2YH9DegXjdJToSzD9rO6fy4qiRYFoyEYwps88OseJlPyl2NOe2iJuhEhL7IpEA==} + dev: false diff --git a/site/components/cart/CartItem/CartItem.tsx b/site/components/cart/CartItem/CartItem.tsx index ecd3e39ae5..d76ccbaeeb 100644 --- a/site/components/cart/CartItem/CartItem.tsx +++ b/site/components/cart/CartItem/CartItem.tsx @@ -93,7 +93,7 @@ const CartItem = ({ width={150} height={150} src={item.variant.image?.url || placeholderImg} - alt={item.variant.image?.altText || "Product Image"} + alt={item.variant.image?.alt || 'Product Image'} unoptimized /> diff --git a/site/components/common/HomeAllProductsGrid/HomeAllProductsGrid.tsx b/site/components/common/HomeAllProductsGrid/HomeAllProductsGrid.tsx index 0a40bff2e5..63ec5698cd 100644 --- a/site/components/common/HomeAllProductsGrid/HomeAllProductsGrid.tsx +++ b/site/components/common/HomeAllProductsGrid/HomeAllProductsGrid.tsx @@ -5,10 +5,11 @@ import { Grid } from '@components/ui' import { ProductCard } from '@components/product' import s from './HomeAllProductsGrid.module.css' import { getCategoryPath, getDesignerPath } from '@lib/search' +import { Brand, Category } from '@commerce/types/site' interface Props { - categories?: any - brands?: any + categories?: Category[] + brands?: Brand[] products?: Product[] } @@ -27,7 +28,7 @@ const HomeAllProductsGrid: FC = ({ All Categories - {categories.map((cat: any) => ( + {categories?.map((cat: any) => (

  • {cat.name} @@ -41,10 +42,10 @@ const HomeAllProductsGrid: FC = ({ All Designers
  • - {brands.flatMap(({ node }: any) => ( -
  • - - {node.name} + {brands?.map(({ path, name }) => ( +
  • + + {name}
  • ))} diff --git a/site/components/search.tsx b/site/components/search.tsx index 664085e5b4..c57f094d13 100644 --- a/site/components/search.tsx +++ b/site/components/search.tsx @@ -4,9 +4,11 @@ import Link from 'next/link' import { useState } from 'react' import { useRouter } from 'next/router' +import type { Brand } from '@commerce/types/site' +import type { Product } from '@commerce/types/product' + import { Layout } from '@components/common' import { ProductCard } from '@components/product' -import type { Product } from '@commerce/types/product' import { Container, Skeleton } from '@components/ui' import useSearch from '@framework/product/use-search' @@ -41,19 +43,22 @@ export default function Search({ categories, brands }: SearchPropsType) { const query = filterQuery({ sort }) const { pathname, category, brand } = useSearchMeta(asPath) + const activeCategory = categories.find((cat: any) => cat.slug === category) - const activeBrand = brands.find( - (b: any) => getSlug(b.node.path) === `brands/${brand}` - )?.node + const activeBrand = brands.find((b: Brand) => b.slug === brand) - const { data } = useSearch({ + const { data, error } = useSearch({ search: typeof q === 'string' ? q : '', categoryId: activeCategory?.id, - brandId: (activeBrand as any)?.entityId, + brandId: (activeBrand as any)?.id, sort: typeof sort === 'string' ? sort : '', locale, }) + if (error) { + return
    Failed to load
    + } + const handleClick = (event: any, filter: string) => { if (filter !== activeFilter) { setToggleFilter(true) @@ -233,20 +238,19 @@ export default function Search({ categories, brands }: SearchPropsType) { - {brands.flatMap(({ node }: { node: any }) => ( + {brands.map(({ path, name, id }: Brand) => (
  • @@ -256,7 +260,7 @@ export default function Search({ categories, brands }: SearchPropsType) { 'block lg:inline-block px-4 py-2 lg:p-0 lg:my-2 lg:mx-4' } > - {node.name} + {name}
  • diff --git a/site/components/wishlist/WishlistButton/WishlistButton.tsx b/site/components/wishlist/WishlistButton/WishlistButton.tsx index f4e0fb31f5..0bd5c188ac 100644 --- a/site/components/wishlist/WishlistButton/WishlistButton.tsx +++ b/site/components/wishlist/WishlistButton/WishlistButton.tsx @@ -30,9 +30,7 @@ const WishlistButton: FC = ({ // @ts-ignore Wishlist is not always enabled const itemInWishlist = data?.items?.find( // @ts-ignore Wishlist is not always enabled - (item) => - item.product_id === Number(productId) && - item.variant_id === Number(variant.id) + (item) => item.product_id === productId && item.variant_id === variant.id ) const handleWishlistChange = async (e: any) => { diff --git a/site/components/wishlist/WishlistCard/WishlistCard.tsx b/site/components/wishlist/WishlistCard/WishlistCard.tsx index 6af6c914e5..7ead46b238 100644 --- a/site/components/wishlist/WishlistCard/WishlistCard.tsx +++ b/site/components/wishlist/WishlistCard/WishlistCard.tsx @@ -11,12 +11,12 @@ import type { Product } from '@commerce/types/product' import usePrice from '@framework/product/use-price' import useAddItem from '@framework/cart/use-add-item' import useRemoveItem from '@framework/wishlist/use-remove-item' -import type { Wishlist } from '@commerce/types/wishlist' +import type { WishlistItem } from '@commerce/types/wishlist' const placeholderImg = '/product-img-placeholder.svg' const WishlistCard: React.FC<{ - item: Wishlist + item: WishlistItem }> = ({ item }) => { const product: Product = item.product const { price } = usePrice({ diff --git a/site/lib/search.tsx b/site/lib/search.tsx index eaeaf66fc8..98ec2d06c8 100644 --- a/site/lib/search.tsx +++ b/site/lib/search.tsx @@ -44,9 +44,7 @@ export const getCategoryPath = (path: string, brand?: string) => { } export const getDesignerPath = (path: string, category?: string) => { - const designer = getSlug(path).replace(/^brands/, 'designers') - - return `/search${designer ? `/${designer}` : ''}${ + return `/search${path ? `/designers${path}` : ''}${ category ? `/${category}` : '' }` } diff --git a/site/pages/product/[slug].tsx b/site/pages/product/[slug].tsx index bb1ecbee3b..439de6d1d1 100644 --- a/site/pages/product/[slug].tsx +++ b/site/pages/product/[slug].tsx @@ -28,6 +28,7 @@ export async function getStaticProps({ config, preview, }) + const { pages } = await pagesPromise const { categories } = await siteInfoPromise const { product } = await productPromise diff --git a/site/pages/wishlist.tsx b/site/pages/wishlist.tsx index 1b8edb31f7..94f7a70492 100644 --- a/site/pages/wishlist.tsx +++ b/site/pages/wishlist.tsx @@ -69,7 +69,7 @@ export default function Wishlist() { {data && // @ts-ignore - Wishlist Item Type data.items?.map((item) => ( - + ))} )}