mirror of
https://github.com/vercel/commerce.git
synced 2025-07-25 19:21:23 +00:00
Fetch product images, standardize API fetch using Spree SDK
This commit is contained in:
20
framework/spree/utils/createGetAbsoluteImageUrl.ts
Normal file
20
framework/spree/utils/createGetAbsoluteImageUrl.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
import { SpreeProductImage } from '../types'
|
||||
import getImageUrl from './getImageUrl'
|
||||
|
||||
const createGetAbsoluteImageUrl =
|
||||
(host: string) =>
|
||||
(
|
||||
image: SpreeProductImage,
|
||||
minWidth: number,
|
||||
minHeight: number
|
||||
): string | null => {
|
||||
const url = getImageUrl(image, minWidth, minHeight)
|
||||
|
||||
if (url === null) {
|
||||
return null
|
||||
}
|
||||
|
||||
return `${host}${url}`
|
||||
}
|
||||
|
||||
export default createGetAbsoluteImageUrl
|
89
framework/spree/utils/expandOptions.ts
Normal file
89
framework/spree/utils/expandOptions.ts
Normal file
@@ -0,0 +1,89 @@
|
||||
import type {
|
||||
ProductOption,
|
||||
ProductOptionValues,
|
||||
} from '@commerce/types/product'
|
||||
import type { JsonApiDocument } from '@spree/storefront-api-v2-sdk/types/interfaces/JsonApi'
|
||||
import type { IProducts } from '@spree/storefront-api-v2-sdk/types/interfaces/Product'
|
||||
import type { RelationType } from '@spree/storefront-api-v2-sdk/types/interfaces/Relationships'
|
||||
import SpreeResponseContentError from '../errors/SpreeResponseContentError'
|
||||
import { findIncluded } from './jsonApi'
|
||||
|
||||
const isColorProductOption = (productOption: ProductOption) =>
|
||||
productOption.displayName === 'Color'
|
||||
|
||||
const expandOptions = (
|
||||
spreeSuccessResponse: IProducts,
|
||||
spreeOptionValue: JsonApiDocument,
|
||||
accumulatedOptions: ProductOption[]
|
||||
): ProductOption[] => {
|
||||
const spreeOptionTypeIdentifier = spreeOptionValue.relationships.option_type
|
||||
.data as RelationType
|
||||
|
||||
const existingOptionIndex = accumulatedOptions.findIndex(
|
||||
(option) => option.id == spreeOptionTypeIdentifier.id
|
||||
)
|
||||
|
||||
let option: ProductOption
|
||||
|
||||
if (existingOptionIndex === -1) {
|
||||
const spreeOptionType = findIncluded(
|
||||
spreeSuccessResponse,
|
||||
spreeOptionTypeIdentifier.type,
|
||||
spreeOptionTypeIdentifier.id
|
||||
)
|
||||
|
||||
if (!spreeOptionType) {
|
||||
throw new SpreeResponseContentError(
|
||||
`Option type with id ${spreeOptionTypeIdentifier.id} not found.`
|
||||
)
|
||||
}
|
||||
|
||||
option = {
|
||||
id: spreeOptionType.id,
|
||||
displayName: spreeOptionType.attributes.presentation,
|
||||
values: [],
|
||||
}
|
||||
} else {
|
||||
const existingOption = accumulatedOptions[existingOptionIndex]
|
||||
|
||||
option = existingOption
|
||||
}
|
||||
|
||||
let optionValue: ProductOptionValues
|
||||
|
||||
const label = isColorProductOption(option)
|
||||
? spreeOptionValue.attributes.name
|
||||
: spreeOptionValue.attributes.presentation
|
||||
|
||||
const productOptionValueExists = option.values.some(
|
||||
(optionValue: ProductOptionValues) => optionValue.label === label
|
||||
)
|
||||
|
||||
if (!productOptionValueExists) {
|
||||
if (isColorProductOption(option)) {
|
||||
optionValue = {
|
||||
label,
|
||||
hexColors: [spreeOptionValue.attributes.presentation],
|
||||
}
|
||||
} else {
|
||||
optionValue = {
|
||||
label,
|
||||
}
|
||||
}
|
||||
|
||||
const expandedOptionValues = [...option.values, optionValue]
|
||||
|
||||
const expandedOptions = [...accumulatedOptions]
|
||||
|
||||
expandedOptions[existingOptionIndex] = {
|
||||
...option,
|
||||
values: expandedOptionValues,
|
||||
}
|
||||
|
||||
return expandedOptions
|
||||
}
|
||||
|
||||
return accumulatedOptions
|
||||
}
|
||||
|
||||
export default expandOptions
|
@@ -4,7 +4,7 @@ import isServer from './isServer'
|
||||
|
||||
const generateMisconfigurationErrorMessage = (
|
||||
keys: Array<string | number | symbol>
|
||||
) => `${keys.join(', ')} must have values before running the Framework.`
|
||||
) => `${keys.join(', ')} must have a value before running the Framework.`
|
||||
|
||||
const forceIsomorphicConfigValues = <
|
||||
X extends keyof T,
|
||||
|
44
framework/spree/utils/getImageUrl.ts
Normal file
44
framework/spree/utils/getImageUrl.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
// Based on https://github.com/spark-solutions/spree2vuestorefront/blob/d88d85ae1bcd2ec99b13b81cd2e3c25600a0216e/src/utils/index.ts
|
||||
|
||||
import type { ImageStyle, SpreeProductImage } from '../types'
|
||||
|
||||
const getImageUrl = (
|
||||
image: SpreeProductImage,
|
||||
minWidth: number,
|
||||
_: number
|
||||
): string | null => {
|
||||
// every image is still resized in vue-storefront-api, no matter what getImageUrl returns
|
||||
if (image) {
|
||||
const {
|
||||
attributes: { styles },
|
||||
} = image
|
||||
const bestStyleIndex = styles.reduce(
|
||||
(bSIndex: number | null, style: ImageStyle, styleIndex: number) => {
|
||||
// assuming all images are the same dimensions, just scaled
|
||||
if (bSIndex === null) {
|
||||
return 0
|
||||
}
|
||||
const bestStyle = styles[bSIndex]
|
||||
const widthDiff = +bestStyle.width - minWidth
|
||||
const minWidthDiff = +style.width - minWidth
|
||||
if (widthDiff < 0 && minWidthDiff > 0) {
|
||||
return styleIndex
|
||||
}
|
||||
if (widthDiff > 0 && minWidthDiff < 0) {
|
||||
return bSIndex
|
||||
}
|
||||
return Math.abs(widthDiff) < Math.abs(minWidthDiff)
|
||||
? bSIndex
|
||||
: styleIndex
|
||||
},
|
||||
null
|
||||
)
|
||||
|
||||
if (bestStyleIndex !== null) {
|
||||
return styles[bestStyleIndex].url
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
export default getImageUrl
|
30
framework/spree/utils/getMediaGallery.ts
Normal file
30
framework/spree/utils/getMediaGallery.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
// Based on https://github.com/spark-solutions/spree2vuestorefront/blob/d88d85ae1bcd2ec99b13b81cd2e3c25600a0216e/src/utils/index.ts
|
||||
|
||||
import type { ProductImage } from '@commerce/types/product'
|
||||
import type { SpreeProductImage } from '../types'
|
||||
|
||||
const getMediaGallery = (
|
||||
images: SpreeProductImage[],
|
||||
getImageUrl: (
|
||||
image: SpreeProductImage,
|
||||
minWidth: number,
|
||||
minHeight: number
|
||||
) => string | null
|
||||
) => {
|
||||
return images.reduce<ProductImage[]>((productImages, _, imageIndex) => {
|
||||
const imageUrl = getImageUrl(images[imageIndex], 9001, 9001)
|
||||
|
||||
if (imageUrl) {
|
||||
return [
|
||||
...productImages,
|
||||
{
|
||||
url: imageUrl,
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
return productImages
|
||||
}, [])
|
||||
}
|
||||
|
||||
export default getMediaGallery
|
56
framework/spree/utils/getSpreeSdkMethodFromEndpointPath.ts
Normal file
56
framework/spree/utils/getSpreeSdkMethodFromEndpointPath.ts
Normal file
@@ -0,0 +1,56 @@
|
||||
import type { Client } from '@spree/storefront-api-v2-sdk'
|
||||
import SpreeSdkMethodFromEndpointPathError from '../errors/SpreeSdkMethodFromEndpointPathError'
|
||||
import { SpreeSdkMethod } from '../types'
|
||||
|
||||
const getSpreeSdkMethodFromEndpointPath = <
|
||||
ExactSpreeSdkClientType extends Client
|
||||
>(
|
||||
client: ExactSpreeSdkClientType,
|
||||
path: string
|
||||
) => {
|
||||
const pathParts = path.split('.')
|
||||
const reachedPath: string[] = []
|
||||
let node = <Record<string, unknown>>client
|
||||
|
||||
console.log(`Looking for ${path} in Spree Sdk.`)
|
||||
|
||||
while (reachedPath.length < pathParts.length - 1) {
|
||||
const checkedPathPart = pathParts[reachedPath.length]
|
||||
const checkedNode = node[checkedPathPart]
|
||||
|
||||
console.log(`Checking part ${checkedPathPart}.`)
|
||||
|
||||
if (typeof checkedNode !== 'object') {
|
||||
throw new SpreeSdkMethodFromEndpointPathError(
|
||||
`Couldn't reach ${path}. Farthest path reached was: ${reachedPath.join(
|
||||
'.'
|
||||
)}.`
|
||||
)
|
||||
}
|
||||
|
||||
if (checkedNode === null) {
|
||||
throw new SpreeSdkMethodFromEndpointPathError(
|
||||
`Path ${path} doesn't exist.`
|
||||
)
|
||||
}
|
||||
|
||||
node = <Record<string, unknown>>checkedNode
|
||||
reachedPath.push(checkedPathPart)
|
||||
}
|
||||
|
||||
if (
|
||||
reachedPath.length !== pathParts.length - 1 ||
|
||||
typeof node[pathParts[reachedPath.length]] !== 'function'
|
||||
) {
|
||||
throw new SpreeSdkMethodFromEndpointPathError(
|
||||
`Couldn't reach ${path}. Farthest path reached was: ${reachedPath.join(
|
||||
'.'
|
||||
)}.`
|
||||
)
|
||||
}
|
||||
|
||||
return (...args: any[]) =>
|
||||
(node[pathParts[reachedPath.length]] as SpreeSdkMethod)(...args)
|
||||
}
|
||||
|
||||
export default getSpreeSdkMethodFromEndpointPath
|
46
framework/spree/utils/jsonApi.ts
Normal file
46
framework/spree/utils/jsonApi.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
// Based on https://github.com/spark-solutions/spree2vuestorefront
|
||||
|
||||
import type {
|
||||
JsonApiResponse,
|
||||
JsonApiDocument,
|
||||
} from '@spree/storefront-api-v2-sdk/types/interfaces/JsonApi'
|
||||
|
||||
export const findIncluded = <T extends JsonApiDocument>(
|
||||
response: JsonApiResponse,
|
||||
objectType: string,
|
||||
objectId: string
|
||||
): T | null => {
|
||||
if (!response.included) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
(response.included.find(
|
||||
(includedObject) =>
|
||||
includedObject.type === objectType && includedObject.id === objectId
|
||||
) as T) || null
|
||||
)
|
||||
}
|
||||
|
||||
export const findIncludedOfType = <T extends JsonApiDocument>(
|
||||
response: JsonApiResponse,
|
||||
singlePrimaryRecord: JsonApiDocument,
|
||||
objectRelationshipType: string
|
||||
): T[] => {
|
||||
if (!response.included) {
|
||||
return []
|
||||
}
|
||||
|
||||
const typeRelationships =
|
||||
singlePrimaryRecord.relationships[objectRelationshipType]
|
||||
|
||||
if (!typeRelationships) {
|
||||
return []
|
||||
}
|
||||
|
||||
return typeRelationships.data
|
||||
.map((typeObject: JsonApiDocument) =>
|
||||
findIncluded(response, typeObject.type, typeObject.id)
|
||||
)
|
||||
.filter((typeRecord: JsonApiDocument | null) => !!typeRecord)
|
||||
}
|
Reference in New Issue
Block a user