More provider fixes

This commit is contained in:
Catalin Pinte 2022-09-13 10:24:26 +03:00
parent 8eedf41879
commit 261442d49d
13 changed files with 33 additions and 30 deletions

View File

@ -12,7 +12,7 @@ function normalizeProductOption(productOption: any) {
} = productOption } = productOption
return { return {
id: entityId, id: String(entityId),
values: edges?.map(({ node }: any) => node), values: edges?.map(({ node }: any) => node),
...rest, ...rest,
} }
@ -41,7 +41,7 @@ export function normalizeProduct(productNode: any): Product {
variants: { variants: {
$apply: ({ edges }: any) => $apply: ({ edges }: any) =>
edges?.map(({ node: { entityId, productOptions, ...rest } }: any) => ({ edges?.map(({ node: { entityId, productOptions, ...rest } }: any) => ({
id: entityId, id: String(entityId),
options: productOptions?.edges options: productOptions?.edges
? productOptions.edges.map(normalizeProductOption) ? productOptions.edges.map(normalizeProductOption)
: [], : [],

View File

@ -32,7 +32,7 @@ export const getErrorMessage = (error: unknown) => {
export const getOperationError = (operation: string, error: unknown) => { export const getOperationError = (operation: string, error: unknown) => {
if (error instanceof ZodError) { if (error instanceof ZodError) {
error = new CommerceError({ return new CommerceError({
code: 'SCHEMA_VALIDATION_ERROR', code: 'SCHEMA_VALIDATION_ERROR',
message: message:
`The ${operation} operation returned invalid data and has ${ `The ${operation} operation returned invalid data and has ${
@ -49,12 +49,5 @@ export const getOperationError = (operation: string, error: unknown) => {
}) })
} }
if (error instanceof Error) {
return new CommerceError({
code: 'OPERATION_ERROR',
message: `An unexpected error ocurred with the ${operation} operation: ${error.message}`,
})
}
return error return error
} }

View File

@ -1,6 +1,7 @@
import type { AllowedOperations, OperationsData } from '../operations' import type { AllowedOperations, OperationsData } from '../operations'
import { z } from 'zod' import { z } from 'zod'
import { getOperationError } from './errors' import { getOperationError } from './errors'
import { pageSchema } from '../../schemas/page' import { pageSchema } from '../../schemas/page'
import { siteInfoSchema } from '../../schemas/site' import { siteInfoSchema } from '../../schemas/site'
@ -12,13 +13,15 @@ export const withSchemaParser =
fn: (...args: any[]) => Promise<OperationsData> fn: (...args: any[]) => Promise<OperationsData>
) => ) =>
async (...args: any[]) => { async (...args: any[]) => {
const result = await fn(...args)
try { try {
const result = await fn(...args)
parse(operation, result) parse(operation, result)
return result
} catch (error) { } catch (error) {
return Promise.reject(getOperationError(operation, error)) throw getOperationError(operation, error)
} }
return result
} }
const parse = (operation: AllowedOperations, data: OperationsData) => { const parse = (operation: AllowedOperations, data: OperationsData) => {

View File

@ -2,7 +2,7 @@ import { Product } from '@vercel/commerce/types/product'
import { GetAllProductsOperation } from '@vercel/commerce/types/product' import { GetAllProductsOperation } from '@vercel/commerce/types/product'
import type { OperationContext } from '@vercel/commerce/api/operations' import type { OperationContext } from '@vercel/commerce/api/operations'
import type { KiboCommerceConfig } from '../index' 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' import { normalizeProduct } from '../../lib/normalize'
export default function getAllProductsOperation({ export default function getAllProductsOperation({
@ -18,11 +18,12 @@ export default function getAllProductsOperation({
config?: Partial<KiboCommerceConfig> config?: Partial<KiboCommerceConfig>
preview?: boolean preview?: boolean
} = {}): Promise<{ products: Product[] | any[] }> { } = {}): Promise<{ products: Product[] | any[] }> {
const cfg = commerce.getConfig(config) 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 { return {
products: normalizedProducts, products: normalizedProducts,

View File

@ -1,7 +1,7 @@
import { OperationContext } from '@vercel/commerce/api/operations' import { OperationContext } from '@vercel/commerce/api/operations'
import { Category } from '@vercel/commerce/types/site' import { Category } from '@vercel/commerce/types/site'
import { KiboCommerceConfig } from '../index' 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' import { normalizeCategory } from '../../lib/normalize'
export type GetSiteInfoResult< export type GetSiteInfoResult<
@ -11,9 +11,11 @@ export type GetSiteInfoResult<
} }
> = T > = T
export default function getSiteInfoOperation({commerce}: OperationContext<any>) { export default function getSiteInfoOperation({
commerce,
}: OperationContext<any>) {
async function getSiteInfo({ async function getSiteInfo({
query= categoryTreeQuery, query = categoryTreeQuery,
variables, variables,
config, config,
}: { }: {
@ -23,12 +25,13 @@ export default function getSiteInfoOperation({commerce}: OperationContext<any>)
preview?: boolean preview?: boolean
} = {}): Promise<GetSiteInfoResult> { } = {}): Promise<GetSiteInfoResult> {
const cfg = commerce.getConfig(config) const cfg = commerce.getConfig(config)
const { data } = await cfg.fetch(query); const { data } = await cfg.fetch(query)
const categories= data.categories.items.map(normalizeCategory); const categories = data.categories.items.map(normalizeCategory)
return Promise.resolve({
return {
categories: categories ?? [], categories: categories ?? [],
brands: [], brands: [],
}) }
} }
return getSiteInfo return getSiteInfo

View File

@ -43,7 +43,6 @@ export function normalizeProduct(productNode: any, config: any): any {
displayName: o.attributeDetail.name, displayName: o.attributeDetail.name,
values: o.values.map((v: any) => ({ values: o.values.map((v: any) => ({
label: v.value.toString(), label: v.value.toString(),
hexColors: '',
})), })),
})) || [], })) || [],
} }

View File

@ -48,6 +48,7 @@ export default function getPageOperation({
? { ? {
...page, ...page,
url: `/${locale}/${page.slug}`, url: `/${locale}/${page.slug}`,
body: page.body ?? '',
} }
: null, : null,
} }

View File

@ -9,6 +9,7 @@ const fetchGraphqlApi: GraphQLFetcher = async (
fetchOptions fetchOptions
) => { ) => {
const config = getCommerceApi().getConfig() const config = getCommerceApi().getConfig()
const res = await fetch(config.commerceUrl, { const res = await fetch(config.commerceUrl, {
...fetchOptions, ...fetchOptions,
method: 'POST', method: 'POST',
@ -23,6 +24,7 @@ const fetchGraphqlApi: GraphQLFetcher = async (
}) })
const json = await res.json() const json = await res.json()
if (json.errors) { if (json.errors) {
throw new FetcherError({ throw new FetcherError({
errors: json.errors ?? [{ message: 'Failed to fetch Vendure API' }], errors: json.errors ?? [{ message: 'Failed to fetch Vendure API' }],

View File

@ -44,7 +44,7 @@ export const fetcher: Fetcher = async ({
if (res.ok) { if (res.ok) {
const { data, errors } = await res.json() const { data, errors } = await res.json()
if (errors) { if (errors) {
throw await new FetcherError({ status: res.status, errors }) throw new FetcherError({ status: res.status, errors })
} }
return data return data
} }

View File

@ -8,7 +8,7 @@ export function normalizeSearchResult(item: SearchResultFragment): Product {
name: item.productName, name: item.productName,
description: item.description, description: item.description,
slug: item.slug, slug: item.slug,
path: `${item.slug}`, path: `/${item.slug}`,
images: [ images: [
{ {
url: item.productAsset?.preview url: item.productAsset?.preview

View File

@ -44,7 +44,7 @@ export const getCategoryPath = (path: string, brand?: string) => {
} }
export const getDesignerPath = (path: string, category?: string) => { export const getDesignerPath = (path: string, category?: string) => {
return `/search${path ? `/designers/${path}` : ''}${ return `/search${path ? `/designers${path}` : ''}${
category ? `/${category}` : '' category ? `/${category}` : ''
}` }`
} }

View File

@ -28,6 +28,7 @@ export async function getStaticProps({
config, config,
preview, preview,
}) })
const { pages } = await pagesPromise const { pages } = await pagesPromise
const { categories } = await siteInfoPromise const { categories } = await siteInfoPromise
const { product } = await productPromise const { product } = await productPromise

View File

@ -23,8 +23,8 @@
"@components/*": ["components/*"], "@components/*": ["components/*"],
"@commerce": ["../packages/commerce/src"], "@commerce": ["../packages/commerce/src"],
"@commerce/*": ["../packages/commerce/src/*"], "@commerce/*": ["../packages/commerce/src/*"],
"@framework": ["../packages/vendure/src"], "@framework": ["../packages/shopify/src"],
"@framework/*": ["../packages/vendure/src/*"] "@framework/*": ["../packages/shopify/src/*"]
} }
}, },
"include": ["next-env.d.ts", "**/*.d.ts", "**/*.ts", "**/*.tsx", "**/*.js"], "include": ["next-env.d.ts", "**/*.d.ts", "**/*.ts", "**/*.tsx", "**/*.js"],