From c88da63a1dcde084eafce9a7afc4998fba05b7d7 Mon Sep 17 00:00:00 2001 From: Greg Hoskin Date: Fri, 4 Jun 2021 18:23:40 -0700 Subject: [PATCH] update types --- framework/swell/api/customers/login.ts | 1 - framework/swell/api/index.ts | 59 +++++++++--------- .../operations}/get-all-collections.ts | 4 +- .../swell/api/operations/get-all-pages.ts | 45 ++++++++++++++ .../api/operations/get-all-product-paths.ts | 48 +++++++++++++++ .../swell/api/operations/get-all-products.ts | 42 +++++++++++++ framework/swell/api/operations/get-page.ts | 53 ++++++++++------ framework/swell/api/operations/get-product.ts | 33 ++++++++++ .../swell/api/operations/get-site-info.ts | 37 ++++++++++++ framework/swell/api/operations/login.ts | 46 ++++++++++++++ framework/swell/auth/use-login.tsx | 4 +- framework/swell/auth/use-logout.tsx | 3 +- framework/swell/auth/use-signup.tsx | 10 +--- framework/swell/cart/use-add-item.tsx | 6 +- framework/swell/cart/use-cart.tsx | 4 +- framework/swell/cart/use-remove-item.tsx | 60 ++++++------------- framework/swell/cart/use-update-item.tsx | 33 +++++----- framework/swell/common/get-all-pages.ts | 37 ------------ framework/swell/common/get-site-info.ts | 31 ---------- framework/swell/customer/use-customer.tsx | 27 +-------- .../swell/product/get-all-product-paths.ts | 39 ------------ framework/swell/product/get-all-products.ts | 36 ----------- framework/swell/product/get-product.ts | 32 ---------- framework/swell/product/index.ts | 2 + framework/swell/product/use-search.tsx | 18 +----- framework/swell/provider.ts | 9 ++- framework/swell/types.ts | 23 ++----- framework/swell/types/cart.ts | 1 + framework/swell/types/checkout.ts | 1 + framework/swell/types/common.ts | 1 + framework/swell/types/customer.ts | 1 + framework/swell/types/index.ts | 25 ++++++++ framework/swell/types/login.ts | 11 ++++ framework/swell/types/logout.ts | 1 + framework/swell/types/page.ts | 1 + framework/swell/types/product.ts | 1 + framework/swell/types/signup.ts | 1 + framework/swell/types/site.ts | 1 + framework/swell/types/wishlist.ts | 1 + framework/swell/utils/get-categories.ts | 2 +- framework/swell/utils/normalize.ts | 24 +++++--- framework/vendure/api/index.ts | 2 +- .../swell/swell-js.d.ts => swell-js.d.ts | 0 tsconfig.json | 4 +- 44 files changed, 448 insertions(+), 372 deletions(-) delete mode 100644 framework/swell/api/customers/login.ts rename framework/swell/{product => api/operations}/get-all-collections.ts (86%) create mode 100644 framework/swell/api/operations/get-all-pages.ts create mode 100644 framework/swell/api/operations/get-all-product-paths.ts create mode 100644 framework/swell/api/operations/get-all-products.ts create mode 100644 framework/swell/api/operations/get-product.ts create mode 100644 framework/swell/api/operations/get-site-info.ts create mode 100644 framework/swell/api/operations/login.ts delete mode 100644 framework/swell/common/get-all-pages.ts delete mode 100644 framework/swell/common/get-site-info.ts delete mode 100644 framework/swell/product/get-all-product-paths.ts delete mode 100644 framework/swell/product/get-all-products.ts delete mode 100644 framework/swell/product/get-product.ts create mode 100644 framework/swell/product/index.ts create mode 100644 framework/swell/types/cart.ts create mode 100644 framework/swell/types/checkout.ts create mode 100644 framework/swell/types/common.ts create mode 100644 framework/swell/types/customer.ts create mode 100644 framework/swell/types/index.ts create mode 100644 framework/swell/types/login.ts create mode 100644 framework/swell/types/logout.ts create mode 100644 framework/swell/types/page.ts create mode 100644 framework/swell/types/product.ts create mode 100644 framework/swell/types/signup.ts create mode 100644 framework/swell/types/site.ts create mode 100644 framework/swell/types/wishlist.ts rename framework/swell/swell-js.d.ts => swell-js.d.ts (100%) diff --git a/framework/swell/api/customers/login.ts b/framework/swell/api/customers/login.ts deleted file mode 100644 index ea9b101e1..000000000 --- a/framework/swell/api/customers/login.ts +++ /dev/null @@ -1 +0,0 @@ -export default function () {} diff --git a/framework/swell/api/index.ts b/framework/swell/api/index.ts index 1494af9c7..463c42fae 100644 --- a/framework/swell/api/index.ts +++ b/framework/swell/api/index.ts @@ -1,5 +1,8 @@ -import type { CommerceAPIConfig } from '@commerce/api' - +import { + CommerceAPI, + CommerceAPIConfig, + getCommerceApi as commerceApi, +} from '@commerce/api' import { SWELL_CHECKOUT_ID_COOKIE, SWELL_CUSTOMER_TOKEN_COOKIE, @@ -7,31 +10,19 @@ import { } from '../const' import fetchApi from './utils/fetch-swell-api' +import login from './operations/login' +import getAllPages from './operations/get-all-pages' +import getPage from './operations/get-page' +import getSiteInfo from './operations/get-site-info' +import getAllProductPaths from './operations/get-all-product-paths' +import getAllProducts from './operations/get-all-products' +import getProduct from './operations/get-product' export interface SwellConfig extends CommerceAPIConfig { fetch: any } -export class Config { - private config: SwellConfig - - constructor(config: SwellConfig) { - this.config = config - } - - getConfig(userConfig: Partial = {}) { - return Object.entries(userConfig).reduce( - (cfg, [key, value]) => Object.assign(cfg, { [key]: value }), - { ...this.config } - ) - } - - setConfig(newConfig: Partial) { - Object.assign(this.config, newConfig) - } -} - -const config = new Config({ +const config: SwellConfig = { locale: 'en-US', commerceUrl: '', apiToken: ''!, @@ -39,12 +30,24 @@ const config = new Config({ cartCookieMaxAge: SWELL_COOKIE_EXPIRE, fetch: fetchApi, customerCookie: SWELL_CUSTOMER_TOKEN_COOKIE, -}) - -export function getConfig(userConfig?: Partial) { - return config.getConfig(userConfig) } -export function setConfig(newConfig: Partial) { - return config.setConfig(newConfig) +const operations = { + login, + getAllPages, + getPage, + getSiteInfo, + getAllProductPaths, + getAllProducts, + getProduct, +} + +export const provider = { config, operations } + +export type Provider = typeof provider + +export function getCommerceApi

( + customProvider: P = provider as any +): CommerceAPI

{ + return commerceApi(customProvider) } diff --git a/framework/swell/product/get-all-collections.ts b/framework/swell/api/operations/get-all-collections.ts similarity index 86% rename from framework/swell/product/get-all-collections.ts rename to framework/swell/api/operations/get-all-collections.ts index 6b82ce449..e150ef749 100644 --- a/framework/swell/product/get-all-collections.ts +++ b/framework/swell/api/operations/get-all-collections.ts @@ -1,5 +1,5 @@ -import { CollectionEdge } from '../schema' -import { getConfig, SwellConfig } from '../api' +import { CollectionEdge } from '../../schema' +import { getConfig, SwellConfig } from '..' const getAllCollections = async (options?: { variables?: any diff --git a/framework/swell/api/operations/get-all-pages.ts b/framework/swell/api/operations/get-all-pages.ts new file mode 100644 index 000000000..6abaa155c --- /dev/null +++ b/framework/swell/api/operations/get-all-pages.ts @@ -0,0 +1,45 @@ +import { Provider, SwellConfig } from '..' +import type { OperationContext } from '@commerce/api/operations' +import type { Page } from '../../types/page' + +export type GetAllPagesResult< + T extends { pages: any[] } = { pages: Page[] } +> = T + +export default function getAllPagesOperation({ + commerce, +}: OperationContext) { + async function getAllPages(opts?: { + config?: Partial + preview?: boolean + }): Promise + + async function getAllPages(opts: { + url: string + config?: Partial + preview?: boolean + }): Promise> + + async function getAllPages({ + config: cfg, + preview, + }: { + url?: string + config?: Partial + preview?: boolean + } = {}): Promise { + const config = commerce.getConfig(cfg) + const { locale, fetch } = config + const data = await fetch('content', 'list', ['pages']) + const pages = + data?.results?.map(({ slug, ...rest }: { slug: string }) => ({ + url: `/${locale}/${slug}`, + ...rest, + })) ?? [] + return { + pages, + } + } + + return getAllPages +} diff --git a/framework/swell/api/operations/get-all-product-paths.ts b/framework/swell/api/operations/get-all-product-paths.ts new file mode 100644 index 000000000..4d95253e8 --- /dev/null +++ b/framework/swell/api/operations/get-all-product-paths.ts @@ -0,0 +1,48 @@ +import { SwellProduct } from '../../types' +import { SwellConfig, Provider } from '..' +import { OperationContext, OperationOptions } from '@commerce/api/operations' +import { GetAllProductPathsOperation } from '@commerce/types/product' + +export default function getAllProductPathsOperation({ + commerce, +}: OperationContext) { + async function getAllProductPaths< + T extends GetAllProductPathsOperation + >(opts?: { + variables?: T['variables'] + config?: SwellConfig + }): Promise + + async function getAllProductPaths( + opts: { + variables?: T['variables'] + config?: SwellConfig + } & OperationOptions + ): Promise + + async function getAllProductPaths({ + variables, + config: cfg, + }: { + query?: string + variables?: T['variables'] + config?: SwellConfig + } = {}): Promise { + const config = commerce.getConfig(cfg) + // RecursivePartial forces the method to check for every prop in the data, which is + // required in case there's a custom `query` + const { results } = await config.fetch('products', 'list', [ + { + limit: variables?.first, + }, + ]) + + return { + products: results?.map(({ slug: handle }: SwellProduct) => ({ + path: `/${handle}`, + })), + } + } + + return getAllProductPaths +} diff --git a/framework/swell/api/operations/get-all-products.ts b/framework/swell/api/operations/get-all-products.ts new file mode 100644 index 000000000..9c4c1534a --- /dev/null +++ b/framework/swell/api/operations/get-all-products.ts @@ -0,0 +1,42 @@ +import { normalizeProduct } from '../../utils/normalize' +import { SwellProduct } from '../../types' +import { Product } from '@commerce/types/product' +import { Provider, SwellConfig } from '../' +import { OperationContext } from '@commerce/api/operations' + +export type ProductVariables = { first?: number } + +export default function getAllProductsOperation({ + commerce, +}: OperationContext) { + async function getAllProducts(opts?: { + variables?: ProductVariables + config?: Partial + preview?: boolean + }): Promise<{ products: Product[] }> + + async function getAllProducts({ + config: cfg, + }: { + query?: string + variables?: ProductVariables + config?: Partial + preview?: boolean + } = {}): Promise<{ products: Product[] | any[] }> { + const config = commerce.getConfig(cfg) + const { results } = await config.fetch('products', 'list', [ + { + limit: 250, + }, + ]) + const products = results.map((product: SwellProduct) => + normalizeProduct(product) + ) + + return { + products, + } + } + + return getAllProducts +} diff --git a/framework/swell/api/operations/get-page.ts b/framework/swell/api/operations/get-page.ts index b04002dda..05646b71a 100644 --- a/framework/swell/api/operations/get-page.ts +++ b/framework/swell/api/operations/get-page.ts @@ -1,25 +1,44 @@ import { Page } from '../../schema' -import { SwellConfig, getConfig } from '..' +import { SwellConfig, Provider } from '..' +import { OperationContext } from '@commerce/api/operations' export type GetPageResult = T export type PageVariables = { - id: string + id: number } -async function getPage({ - url, - variables, - config, - preview, -}: { - url?: string - variables: PageVariables - config?: SwellConfig - preview?: boolean -}): Promise { - config = getConfig(config) - return {} -} +export default function getPageOperation({ + commerce, +}: OperationContext) { + async function getPage(opts: { + url?: string + variables: PageVariables + config?: Partial + preview?: boolean + }): Promise -export default getPage + async function getPage(opts: { + url: string + variables: V + config?: Partial + preview?: boolean + }): Promise> + + async function getPage({ + url, + variables, + config: cfg, + preview, + }: { + url?: string + variables: PageVariables + config?: Partial + preview?: boolean + }): Promise { + const config = commerce.getConfig(cfg) + return {} + } + + return getPage +} diff --git a/framework/swell/api/operations/get-product.ts b/framework/swell/api/operations/get-product.ts new file mode 100644 index 000000000..c9a3d6f1d --- /dev/null +++ b/framework/swell/api/operations/get-product.ts @@ -0,0 +1,33 @@ +import { normalizeProduct } from '../../utils' + +import { Product } from '@commerce/types/product' +import { OperationContext } from '@commerce/api/operations' +import { Provider, SwellConfig } from '../' + +export default function getProductOperation({ + commerce, +}: OperationContext) { + async function getProduct({ + variables, + config: cfg, + }: { + query?: string + variables: { slug: string } + config?: Partial + preview?: boolean + }): Promise { + const config = commerce.getConfig(cfg) + + const product = await config.fetch('products', 'get', [variables.slug]) + + if (product && product.variants) { + product.variants = product.variants?.results + } + + return { + product: product ? normalizeProduct(product) : null, + } + } + + return getProduct +} diff --git a/framework/swell/api/operations/get-site-info.ts b/framework/swell/api/operations/get-site-info.ts new file mode 100644 index 000000000..36fcebf01 --- /dev/null +++ b/framework/swell/api/operations/get-site-info.ts @@ -0,0 +1,37 @@ +import getCategories from '../../utils/get-categories' +import getVendors, { Brands } from '../../utils/get-vendors' +import { Provider, SwellConfig } from '../' +import { OperationContext } from '@commerce/api/operations' +import { Category } from '@commerce/types/site' + +export type GetSiteInfoResult< + T extends { categories: any[]; brands: any[] } = { + categories: Category[] + brands: Brands + } +> = T + +export default function getSiteInfoOperation({ + commerce, +}: OperationContext) { + async function getSiteInfo({ + variables, + config: cfg, + }: { + query?: string + variables?: any + config?: Partial + preview?: boolean + } = {}): Promise { + const config = commerce.getConfig(cfg) + const categories = await getCategories(config) + const brands = await getVendors(config) + + return { + categories, + brands, + } + } + + return getSiteInfo +} diff --git a/framework/swell/api/operations/login.ts b/framework/swell/api/operations/login.ts new file mode 100644 index 000000000..33e1e2948 --- /dev/null +++ b/framework/swell/api/operations/login.ts @@ -0,0 +1,46 @@ +import type { ServerResponse } from 'http' +import type { + OperationContext, + OperationOptions, +} from '@commerce/api/operations' +import type { LoginOperation } from '../../types/login' +import { Provider, SwellConfig } from '..' + +export default function loginOperation({ + commerce, +}: OperationContext) { + async function login(opts: { + variables: T['variables'] + config?: Partial + res: ServerResponse + }): Promise + + async function login( + opts: { + variables: T['variables'] + config?: Partial + res: ServerResponse + } & OperationOptions + ): Promise + + async function login({ + variables, + res: response, + config: cfg, + }: { + query?: string + variables: T['variables'] + res: ServerResponse + config?: Partial + }): Promise { + const config = commerce.getConfig(cfg) + + const { data } = await config.fetch('account', 'login', [variables]) + + return { + result: data, + } + } + + return login +} diff --git a/framework/swell/auth/use-login.tsx b/framework/swell/auth/use-login.tsx index 57c3ce921..587163d97 100644 --- a/framework/swell/auth/use-login.tsx +++ b/framework/swell/auth/use-login.tsx @@ -3,12 +3,12 @@ import type { MutationHook } from '@commerce/utils/types' import { CommerceError, ValidationError } from '@commerce/utils/errors' import useCustomer from '../customer/use-customer' import { - CustomerAccessTokenCreateInput, CustomerUserError, Mutation, MutationCheckoutCreateArgs, } from '../schema' import useLogin, { UseLogin } from '@commerce/auth/use-login' +import { LoginHook } from '../types/login' import { setCustomerToken } from '../utils' export default useLogin as UseLogin @@ -22,7 +22,7 @@ const getErrorMessage = ({ code, message }: CustomerUserError) => { return message } -export const handler: MutationHook = { +export const handler: MutationHook = { fetchOptions: { query: 'account', method: 'login', diff --git a/framework/swell/auth/use-logout.tsx b/framework/swell/auth/use-logout.tsx index ae17ba74e..7dc7411ec 100644 --- a/framework/swell/auth/use-logout.tsx +++ b/framework/swell/auth/use-logout.tsx @@ -3,10 +3,11 @@ import type { MutationHook } from '@commerce/utils/types' import useLogout, { UseLogout } from '@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 -export const handler: MutationHook = { +export const handler: MutationHook = { fetchOptions: { query: 'account', method: 'logout', diff --git a/framework/swell/auth/use-signup.tsx b/framework/swell/auth/use-signup.tsx index d417122fc..674b9861f 100644 --- a/framework/swell/auth/use-signup.tsx +++ b/framework/swell/auth/use-signup.tsx @@ -3,18 +3,12 @@ import type { MutationHook } from '@commerce/utils/types' import { CommerceError } from '@commerce/utils/errors' import useSignup, { UseSignup } from '@commerce/auth/use-signup' import useCustomer from '../customer/use-customer' -import { CustomerCreateInput } from '../schema' - +import { SignupHook } from '../types/signup' import handleLogin from '../utils/handle-login' export default useSignup as UseSignup -export const handler: MutationHook< - null, - {}, - CustomerCreateInput, - CustomerCreateInput -> = { +export const handler: MutationHook = { fetchOptions: { query: 'account', method: 'create', diff --git a/framework/swell/cart/use-add-item.tsx b/framework/swell/cart/use-add-item.tsx index 990514d42..e324a44d9 100644 --- a/framework/swell/cart/use-add-item.tsx +++ b/framework/swell/cart/use-add-item.tsx @@ -2,14 +2,14 @@ import type { MutationHook } from '@commerce/utils/types' import { CommerceError } from '@commerce/utils/errors' import useAddItem, { UseAddItem } from '@commerce/cart/use-add-item' import useCart from './use-cart' -import { Cart, CartItemBody } from '../types' import { checkoutToCart } from './utils' import { getCheckoutId } from '../utils' import { useCallback } from 'react' +import { AddItemHook } from '../types/cart' export default useAddItem as UseAddItem -export const handler: MutationHook = { +export const handler: MutationHook = { fetchOptions: { query: 'cart', method: 'addItem', @@ -24,7 +24,7 @@ export const handler: MutationHook = { }) } const variables: { - product_id: string + product_id: string | undefined variant_id?: string checkoutId?: string quantity?: number diff --git a/framework/swell/cart/use-cart.tsx b/framework/swell/cart/use-cart.tsx index 531286ee6..885f889f5 100644 --- a/framework/swell/cart/use-cart.tsx +++ b/framework/swell/cart/use-cart.tsx @@ -1,13 +1,13 @@ import useCart, { UseCart } from '@commerce/cart/use-cart' -import { Cart } from '@commerce/types' import { SWRHook } from '@commerce/utils/types' import { useMemo } from 'react' import { normalizeCart } from '../utils/normalize' import { checkoutCreate, checkoutToCart } from './utils' +import type { GetCartHook } from '@commerce/types/cart' export default useCart as UseCart -export const handler: SWRHook = { +export const handler: SWRHook = { fetchOptions: { query: 'cart', method: 'get', diff --git a/framework/swell/cart/use-remove-item.tsx b/framework/swell/cart/use-remove-item.tsx index 8dc1ea713..7ef3af7cd 100644 --- a/framework/swell/cart/use-remove-item.tsx +++ b/framework/swell/cart/use-remove-item.tsx @@ -1,29 +1,21 @@ import { useCallback } from 'react' - import type { MutationHookContext, HookFetcherContext, } from '@commerce/utils/types' -import { ValidationError } from '@commerce/utils/errors' - -import useRemoveItem, { - RemoveItemInput as RemoveItemInputBase, - UseRemoveItem, -} from '@commerce/cart/use-remove-item' - +import useRemoveItem, { UseRemoveItem } from '@commerce/cart/use-remove-item' +import type { Cart, LineItem, RemoveItemHook } from '@commerce/types/cart' import useCart from './use-cart' import { checkoutToCart } from './utils' -import { Cart, LineItem } from '../types' -import { RemoveCartItemBody } from '@commerce/types' export type RemoveItemFn = T extends LineItem - ? (input?: RemoveItemInput) => Promise - : (input: RemoveItemInput) => Promise + ? (input?: RemoveItemActionInput) => Promise + : (input: RemoveItemActionInput) => Promise -export type RemoveItemInput = T extends LineItem - ? Partial - : RemoveItemInputBase +export type RemoveItemActionInput = T extends LineItem + ? Partial + : RemoveItemHook['actionInput'] export default useRemoveItem as UseRemoveItem @@ -36,36 +28,22 @@ export const handler = { input: { itemId }, options, fetch, - }: HookFetcherContext) { - const response = await fetch({ - ...options, - variables: [itemId], - }) + }: HookFetcherContext) { + const response = await fetch({ ...options, variables: [itemId] }) + return checkoutToCart(response) }, - useHook: ({ - fetch, - }: MutationHookContext) => < - T extends LineItem | undefined = undefined - >( - ctx: { item?: T } = {} - ) => { - const { item } = ctx + useHook: ({ fetch }: MutationHookContext) => () => { const { mutate } = useCart() - const removeItem: RemoveItemFn = async (input) => { - const itemId = input?.id ?? item?.id - if (!itemId) { - throw new ValidationError({ - message: 'Invalid input used for this operation', - }) - } + return useCallback( + async function removeItem(input) { + const data = await fetch({ input: { itemId: input.id } }) + await mutate(data, false) - const data = await fetch({ input: { itemId } }) - await mutate(data, false) - return data - } - - return useCallback(removeItem as RemoveItemFn, [fetch, mutate]) + return data + }, + [fetch, mutate] + ) }, } diff --git a/framework/swell/cart/use-update-item.tsx b/framework/swell/cart/use-update-item.tsx index b1031b2e7..631a394f6 100644 --- a/framework/swell/cart/use-update-item.tsx +++ b/framework/swell/cart/use-update-item.tsx @@ -2,25 +2,30 @@ import { useCallback } from 'react' import debounce from 'lodash.debounce' import type { HookFetcherContext, + MutationHook, MutationHookContext, } from '@commerce/utils/types' import { ValidationError } from '@commerce/utils/errors' -import useUpdateItem, { - UpdateItemInput as UpdateItemInputBase, - UseUpdateItem, -} from '@commerce/cart/use-update-item' - +// import useUpdateItem, { +// UpdateItemInput as UpdateItemInputBase, +// UseUpdateItem, +// } from '@commerce/cart/use-update-item' +import useUpdateItem, { UseUpdateItem } from '@commerce/cart/use-update-item' import useCart from './use-cart' import { handler as removeItemHandler } from './use-remove-item' -import type { Cart, LineItem, UpdateCartItemBody } from '../types' +import { CartItemBody, LineItem } from '@commerce/types/cart' import { checkoutToCart } from './utils' - -export type UpdateItemInput = T extends LineItem - ? Partial> - : UpdateItemInputBase +import { UpdateItemHook } from '../types/cart' +// export type UpdateItemInput = T extends LineItem +// ? Partial> +// : UpdateItemInputBase export default useUpdateItem as UseUpdateItem +export type UpdateItemActionInput = T extends LineItem + ? Partial + : UpdateItemHook['actionInput'] + export const handler = { fetchOptions: { query: 'cart', @@ -30,7 +35,7 @@ export const handler = { input: { itemId, item }, options, fetch, - }: HookFetcherContext) { + }: 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) { @@ -52,9 +57,7 @@ export const handler = { return checkoutToCart(response) }, - useHook: ({ - fetch, - }: MutationHookContext) => < + useHook: ({ fetch }: MutationHookContext) => < T extends LineItem | undefined = undefined >( ctx: { @@ -66,7 +69,7 @@ export const handler = { const { mutate, data: cartData } = useCart() as any return useCallback( - debounce(async (input: UpdateItemInput) => { + debounce(async (input: UpdateItemActionInput) => { const firstLineItem = cartData.lineItems[0] const itemId = item?.id || firstLineItem.id const productId = item?.productId || firstLineItem.productId diff --git a/framework/swell/common/get-all-pages.ts b/framework/swell/common/get-all-pages.ts deleted file mode 100644 index 8d0b9cf36..000000000 --- a/framework/swell/common/get-all-pages.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { getConfig, SwellConfig } from '../api' - -type Variables = { - first?: number -} - -type ReturnType = { - pages: Page[] -} - -export type Page = { - id: string - name: string - url: string - sort_order?: number - body: string -} - -const getAllPages = async (options?: { - variables?: Variables - config: SwellConfig - preview?: boolean -}): Promise => { - let { config, variables = { first: 250 } } = options ?? {} - config = getConfig(config) - const { locale, fetch } = config - const data = await fetch('content', 'list', ['pages']) - const pages = - data?.results?.map(({ slug, ...rest }: { slug: string }) => ({ - url: `/${locale}/${slug}`, - ...rest, - })) ?? [] - - return { pages } -} - -export default getAllPages diff --git a/framework/swell/common/get-site-info.ts b/framework/swell/common/get-site-info.ts deleted file mode 100644 index c7a06c52e..000000000 --- a/framework/swell/common/get-site-info.ts +++ /dev/null @@ -1,31 +0,0 @@ -import getCategories from '../utils/get-categories' -import getVendors, { Brands } from '../utils/get-vendors' -import { Category } from '@commerce/types' -import { getConfig, SwellConfig } from '../api' - -export type GetSiteInfoResult< - T extends { categories: any[]; brands: any[] } = { - categories: Category[] - brands: Brands - } -> = T - -const getSiteInfo = async (options?: { - variables?: any - config: SwellConfig - preview?: boolean -}): Promise => { - let { config } = options ?? {} - - config = getConfig(config) - - const categories = await getCategories(config) - const brands = await getVendors(config) - - return { - categories, - brands, - } -} - -export default getSiteInfo diff --git a/framework/swell/customer/use-customer.tsx b/framework/swell/customer/use-customer.tsx index 632065d5a..50e85d3f6 100644 --- a/framework/swell/customer/use-customer.tsx +++ b/framework/swell/customer/use-customer.tsx @@ -1,11 +1,11 @@ import useCustomer, { UseCustomer } from '@commerce/customer/use-customer' -import { Customer } from '@commerce/types' import { SWRHook } from '@commerce/utils/types' import { normalizeCustomer } from '../utils/normalize' +import type { CustomerHook } from '../types/customer' export default useCustomer as UseCustomer -export const handler: SWRHook = { +export const handler: SWRHook = { fetchOptions: { query: 'account', method: 'get', @@ -25,26 +25,3 @@ export const handler: SWRHook = { }) }, } - -// const handler = (): { data: Customer } => { -// const swell = getContext(); -// const response = swell.account.get(); -// const { firstName, lastName, email, company, customerGroupId, notes, phone, -// entityId, addressCount, attributeCount, storeCredit } = response; -// return { -// data: { -// firstName, -// lastName, -// email, -// company, -// customerGroupId, -// notes, -// phone, -// entityId, -// addressCount, -// attributeCount, -// storeCredit -// } -// } -// } -// export default handler; diff --git a/framework/swell/product/get-all-product-paths.ts b/framework/swell/product/get-all-product-paths.ts deleted file mode 100644 index 933eb73bc..000000000 --- a/framework/swell/product/get-all-product-paths.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { SwellProduct } from '../types' -import { getConfig, SwellConfig } from '../api' - -type ProductPath = { - path: string -} - -export type ProductPathNode = { - node: ProductPath -} - -type ReturnType = { - products: ProductPathNode[] -} - -const getAllProductPaths = async (options?: { - variables?: any - config?: SwellConfig - preview?: boolean -}): Promise => { - let { config, variables = [{ limit: 100 }] } = options ?? {} - config = getConfig(config) - - const { results } = await config.fetch('products', 'list', [ - { - limit: variables.first, - }, - ]) - - return { - products: results?.map(({ slug: handle }: SwellProduct) => ({ - node: { - path: `/${handle}`, - }, - })), - } -} - -export default getAllProductPaths diff --git a/framework/swell/product/get-all-products.ts b/framework/swell/product/get-all-products.ts deleted file mode 100644 index c0746efca..000000000 --- a/framework/swell/product/get-all-products.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { getConfig, SwellConfig } from '../api' -import { normalizeProduct } from '../utils/normalize' -import { Product } from '@commerce/types' -import { SwellProduct } from '../types' - -type Variables = { - first?: number - field?: string -} - -type ReturnType = { - products: Product[] -} - -const getAllProducts = async (options: { - variables?: Variables - config?: SwellConfig - preview?: boolean -}): Promise => { - let { config, variables = { first: 250 } } = options ?? {} - config = getConfig(config) - const { results } = await config.fetch('products', 'list', [ - { - limit: variables.first, - }, - ]) - const products = results.map((product: SwellProduct) => - normalizeProduct(product) - ) - - return { - products, - } -} - -export default getAllProducts diff --git a/framework/swell/product/get-product.ts b/framework/swell/product/get-product.ts deleted file mode 100644 index 0d75a57cd..000000000 --- a/framework/swell/product/get-product.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { GraphQLFetcherResult } from '@commerce/api' -import { getConfig, SwellConfig } from '../api' -import { normalizeProduct } from '../utils' - -type Variables = { - slug: string -} - -type ReturnType = { - product: any -} - -const getProduct = async (options: { - variables: Variables - config: SwellConfig - preview?: boolean -}): Promise => { - let { config, variables } = options ?? {} - config = getConfig(config) - - const product = await config.fetch('products', 'get', [variables.slug]) - - if (product && product.variants) { - product.variants = product.variants?.results - } - - return { - product: product ? normalizeProduct(product) : null, - } -} - -export default getProduct diff --git a/framework/swell/product/index.ts b/framework/swell/product/index.ts new file mode 100644 index 000000000..426a3edcd --- /dev/null +++ b/framework/swell/product/index.ts @@ -0,0 +1,2 @@ +export { default as usePrice } from './use-price' +export { default as useSearch } from './use-search' diff --git a/framework/swell/product/use-search.tsx b/framework/swell/product/use-search.tsx index ce116caa3..bdcca3ff2 100644 --- a/framework/swell/product/use-search.tsx +++ b/framework/swell/product/use-search.tsx @@ -1,11 +1,8 @@ import { SWRHook } from '@commerce/utils/types' import useSearch, { UseSearch } from '@commerce/product/use-search' - import { normalizeProduct } from '../utils' - -import { Product } from '@commerce/types' - import { SwellProduct } from '../types' +import type { SearchProductsHook } from '../types/product' export default useSearch as UseSearch @@ -16,18 +13,9 @@ export type SearchProductsInput = { sort?: string } -export type SearchProductsData = { - products: Product[] - found: boolean -} - -export const handler: SWRHook< - SearchProductsData, - SearchProductsInput, - SearchProductsInput -> = { +export const handler: SWRHook = { fetchOptions: { - query: 'products', // String(Math.random()), + query: 'products', method: 'list', }, async fetcher({ input, options, fetch }) { diff --git a/framework/swell/provider.ts b/framework/swell/provider.ts index 0bcbd7888..aa7be31d4 100644 --- a/framework/swell/provider.ts +++ b/framework/swell/provider.ts @@ -1,3 +1,5 @@ +import { Provider } from '@commerce' + import { SWELL_CHECKOUT_URL_COOKIE, STORE_DOMAIN } from './const' import { handler as useCart } from './cart/use-cart' @@ -14,18 +16,15 @@ import { handler as useSignup } from './auth/use-signup' import fetcher from './fetcher' -export const swellProvider = { +export const swellProvider: Provider = { locale: 'en-us', cartCookie: SWELL_CHECKOUT_URL_COOKIE, - storeDomain: STORE_DOMAIN, + // storeDomain: STORE_DOMAIN, fetcher, cart: { useCart, useAddItem, useUpdateItem, useRemoveItem }, customer: { useCustomer }, products: { useSearch }, auth: { useLogin, useLogout, useSignup }, - features: { - wishlist: false, - }, } export type SwellProvider = typeof swellProvider diff --git a/framework/swell/types.ts b/framework/swell/types.ts index 71848d4a4..efd98cba6 100644 --- a/framework/swell/types.ts +++ b/framework/swell/types.ts @@ -1,4 +1,5 @@ -import * as Core from '@commerce/types' +import * as Core from '@commerce/types/cart' +import { Customer } from '@commerce/types' import { CheckoutLineItem } from './schema' export type SwellImage = { @@ -43,6 +44,7 @@ export type SwellVariant = { name: string price?: number stock_status?: string + __type?: 'MultipleChoiceOption' | undefined } export interface ProductOptionValue { @@ -73,10 +75,7 @@ export interface SwellProduct { variants: any[] } -export interface SwellCustomer extends Core.Customer { - first_name: string - last_name: string -} +export type SwellCustomer = any export type SwellCheckout = { id: string @@ -106,17 +105,3 @@ export type CartItemBody = Core.CartItemBody & { productId: string // The product id is always required for BC optionSelections?: OptionSelections } - -export type GetCartHandlerBody = Core.GetCartHandlerBody - -export type AddCartItemBody = Core.AddCartItemBody - -export type AddCartItemHandlerBody = Core.AddCartItemHandlerBody - -export type UpdateCartItemBody = Core.UpdateCartItemBody - -export type UpdateCartItemHandlerBody = Core.UpdateCartItemHandlerBody - -export type RemoveCartItemBody = Core.RemoveCartItemBody - -export type RemoveCartItemHandlerBody = Core.RemoveCartItemHandlerBody diff --git a/framework/swell/types/cart.ts b/framework/swell/types/cart.ts new file mode 100644 index 000000000..6ed5c6c64 --- /dev/null +++ b/framework/swell/types/cart.ts @@ -0,0 +1 @@ +export * from '@commerce/types/cart' diff --git a/framework/swell/types/checkout.ts b/framework/swell/types/checkout.ts new file mode 100644 index 000000000..4e2412ef6 --- /dev/null +++ b/framework/swell/types/checkout.ts @@ -0,0 +1 @@ +export * from '@commerce/types/checkout' diff --git a/framework/swell/types/common.ts b/framework/swell/types/common.ts new file mode 100644 index 000000000..b52c33a4d --- /dev/null +++ b/framework/swell/types/common.ts @@ -0,0 +1 @@ +export * from '@commerce/types/common' diff --git a/framework/swell/types/customer.ts b/framework/swell/types/customer.ts new file mode 100644 index 000000000..87c9afcc4 --- /dev/null +++ b/framework/swell/types/customer.ts @@ -0,0 +1 @@ +export * from '@commerce/types/customer' diff --git a/framework/swell/types/index.ts b/framework/swell/types/index.ts new file mode 100644 index 000000000..7ab0b7f64 --- /dev/null +++ b/framework/swell/types/index.ts @@ -0,0 +1,25 @@ +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/framework/swell/types/login.ts b/framework/swell/types/login.ts new file mode 100644 index 000000000..ab11a420a --- /dev/null +++ b/framework/swell/types/login.ts @@ -0,0 +1,11 @@ +import * as Core from '@commerce/types/login' +import { LoginBody, LoginTypes } from '@commerce/types/login' + +export * from '@commerce/types/login' + +export type LoginHook = { + data: null + actionInput: LoginBody + fetcherInput: LoginBody + body: T['body'] +} diff --git a/framework/swell/types/logout.ts b/framework/swell/types/logout.ts new file mode 100644 index 000000000..9f0a466af --- /dev/null +++ b/framework/swell/types/logout.ts @@ -0,0 +1 @@ +export * from '@commerce/types/logout' diff --git a/framework/swell/types/page.ts b/framework/swell/types/page.ts new file mode 100644 index 000000000..20ec8ea38 --- /dev/null +++ b/framework/swell/types/page.ts @@ -0,0 +1 @@ +export * from '@commerce/types/page' diff --git a/framework/swell/types/product.ts b/framework/swell/types/product.ts new file mode 100644 index 000000000..c776d58fa --- /dev/null +++ b/framework/swell/types/product.ts @@ -0,0 +1 @@ +export * from '@commerce/types/product' diff --git a/framework/swell/types/signup.ts b/framework/swell/types/signup.ts new file mode 100644 index 000000000..58543c6f6 --- /dev/null +++ b/framework/swell/types/signup.ts @@ -0,0 +1 @@ +export * from '@commerce/types/signup' diff --git a/framework/swell/types/site.ts b/framework/swell/types/site.ts new file mode 100644 index 000000000..bfef69cf9 --- /dev/null +++ b/framework/swell/types/site.ts @@ -0,0 +1 @@ +export * from '@commerce/types/site' diff --git a/framework/swell/types/wishlist.ts b/framework/swell/types/wishlist.ts new file mode 100644 index 000000000..8907fbf82 --- /dev/null +++ b/framework/swell/types/wishlist.ts @@ -0,0 +1 @@ +export * from '@commerce/types/wishlist' diff --git a/framework/swell/utils/get-categories.ts b/framework/swell/utils/get-categories.ts index acf33a5b9..ab38bae96 100644 --- a/framework/swell/utils/get-categories.ts +++ b/framework/swell/utils/get-categories.ts @@ -1,5 +1,5 @@ import { SwellConfig } from '../api' -import { Category } from '@commerce/types' +import { Category } from '../types/site' const getCategories = async (config: SwellConfig): Promise => { const data = await config.fetch('categories', 'get') diff --git a/framework/swell/utils/normalize.ts b/framework/swell/utils/normalize.ts index b0cfb6193..fcc7ef4f3 100644 --- a/framework/swell/utils/normalize.ts +++ b/framework/swell/utils/normalize.ts @@ -1,6 +1,6 @@ -import { Product, Customer } from '@commerce/types' - -import { MoneyV2, ProductOption } from '../schema' +import { Customer } from '../types/customer' +import { Product, ProductOption } from '../types/product' +import { MoneyV2 } from '../schema' import type { Cart, @@ -21,8 +21,13 @@ const money = ({ amount, currencyCode }: MoneyV2) => { } } +type swellProductOption = { + id: string + name: string + values: any[] +} + type normalizedProductOption = { - __typename?: string id: string displayName: string values: ProductOptionValue[] @@ -32,11 +37,11 @@ const normalizeProductOption = ({ id, name: displayName = '', values = [], -}: ProductOption) => { +}: swellProductOption): ProductOption => { let returnValues = values.map((value) => { let output: any = { label: value.name, - id: value?.id || id, + // id: value?.id || id, } if (displayName.match(/colou?r/gi)) { output = { @@ -91,10 +96,10 @@ const normalizeProductVariants = ( return { id, - name, + // name, // sku: sku ?? id, - price: price ?? null, - listPrice: price ?? null, + // price: price ?? null, + // listPrice: price ?? null, // requiresShipping: true, options, } @@ -116,6 +121,7 @@ export function normalizeProduct(swellProduct: SwellProduct): Product { } = swellProduct // ProductView accesses variants for each product const emptyVariants = [{ options: [], id, name }] + const productOptions = options ? options.map((o) => normalizeProductOption(o)) : [] diff --git a/framework/vendure/api/index.ts b/framework/vendure/api/index.ts index 6762ee6aa..ca617f1a6 100644 --- a/framework/vendure/api/index.ts +++ b/framework/vendure/api/index.ts @@ -1,4 +1,4 @@ -import type { APIProvider, CommerceAPIConfig } from '@commerce/api' +import type { CommerceAPIConfig } from '@commerce/api' import { CommerceAPI, getCommerceApi as commerceApi } from '@commerce/api' import fetchGraphqlApi from './utils/fetch-graphql-api' diff --git a/framework/swell/swell-js.d.ts b/swell-js.d.ts similarity index 100% rename from framework/swell/swell-js.d.ts rename to swell-js.d.ts diff --git a/tsconfig.json b/tsconfig.json index 96e4359e5..dec7c44b5 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -22,8 +22,8 @@ "@components/*": ["components/*"], "@commerce": ["framework/commerce"], "@commerce/*": ["framework/commerce/*"], - "@framework": ["framework/shopify"], - "@framework/*": ["framework/shopify/*"] + "@framework": ["framework/swell"], + "@framework/*": ["framework/swell/*"] } }, "include": ["next-env.d.ts", "**/*.d.ts", "**/*.ts", "**/*.tsx", "**/*.js"],