feat: Add get content data from static file and get prices from CL

This commit is contained in:
Alessandro Casazza 2022-05-10 18:39:57 +02:00
parent b9f8d0928a
commit 6565266242
No known key found for this signature in database
GPG Key ID: 3AF41B06C6495D3D
5 changed files with 101 additions and 14 deletions

View File

@ -8,6 +8,7 @@ const fetchGraphqlApi: (
) => GraphQLFetcher = ) => GraphQLFetcher =
(getConfig) => (getConfig) =>
async (query: string, { variables, preview } = {}, fetchOptions) => { async (query: string, { variables, preview } = {}, fetchOptions) => {
debugger
const config = getConfig() const config = getConfig()
const res = await fetch(config.commerceUrl, { const res = await fetch(config.commerceUrl, {
...fetchOptions, ...fetchOptions,

View File

@ -0,0 +1,9 @@
import { Product } from '@vercel/commerce/types/Product'
export type Products = (Product & { categoryId: string; brandId: string })[]
export default async function getContentData(id?: string): Promise<Products> {
const url = process.env.NEXT_PUBLIC_COMMERCELAYER_CONTENT_DATA_URL as string
const products = (await (await fetch(url)).json()).products as Products
return !id ? products : products.filter((p) => p.id === id)
}

View File

@ -5,3 +5,23 @@ export default function getCredentials() {
const accessToken = getCookie('CL_TOKEN') as string const accessToken = getCookie('CL_TOKEN') as string
return { accessToken, endpoint } return { accessToken, endpoint }
} }
type ReturnObj = {
organization: string
domain: string
}
export function getOrganizationSlug<E extends string>(endpoint: E): ReturnObj {
const org = {
organization: '',
domain: 'commercelayer.io',
}
if (endpoint) {
if (endpoint.search('commercelayer.io') === -1)
org.domain = 'commercelayer.co'
org.organization = endpoint
.replace('https://', '')
.replace(`.${org.domain}`, '')
}
return org
}

View File

@ -0,0 +1,55 @@
import { Price, CommerceLayerClient } from '@commercelayer/sdk'
import { Product } from '@vercel/commerce/types/product'
import { DeepPartialArray } from './contentfulApi'
type GetPricesArgs = {
products?: DeepPartialArray<Product>
sdk: CommerceLayerClient
}
export default async function getPrices({ products = [], sdk }: GetPricesArgs) {
let allPrices: Price[] = []
const skus: string[] = []
if (products) {
products.forEach(async ({ variants }) => {
if (variants && variants[0]?.options) {
variants[0]?.options[0]?.id && skus.push(variants[0]?.options[0]?.id)
}
})
const prices = await sdk.prices.list({
filters: { sku_code_in: skus.join(',') },
})
allPrices = [...prices]
for (
let pageNumber = prices.meta.currentPage;
pageNumber < prices.meta.pageCount;
pageNumber++
) {
const pricesPage = await sdk.prices.list({
filters: { sku_code_in: skus.join(',') },
pageNumber,
})
allPrices = [...allPrices, ...pricesPage]
}
products.forEach((product, i) => {
for (const price of allPrices) {
const skuCode = price.sku_code
if (skuCode && product?.id && skuCode.startsWith(product.id)) {
product.price = {
value: price.amount_float as number,
currencyCode: price.currency_code,
}
break
}
product.price = {
value: 0,
currencyCode: 'USD',
}
}
if (products && products[i]) {
products[i] = product
}
})
}
return products as Product[]
}

View File

@ -1,30 +1,32 @@
import { LineItem } from '@commercelayer/sdk'
import data from '../../data.json' import data from '../../data.json'
export default function normalizeLineItems(lineItems: any[]) { export default function normalizeLineItems(lineItems: LineItem[]) {
return lineItems return lineItems
.filter((l) => { .filter((l) => {
return !['shipment', 'paymentMethod'].includes(l.itemType) return (
l.item_type && !['shipment', 'payment_method'].includes(l.item_type)
)
}) })
.map((lineItem) => { .map((lineItem) => {
const id = lineItem.id const id = lineItem.id
const attributes = lineItem.attributes
const products = data.products const products = data.products
return { return {
id, id,
name: attributes.name, name: lineItem.name,
path: products.find((p) => p.id === attributes.reference)?.slug, path: products.find((p) => p.id === lineItem.reference)?.slug,
productId: attributes.reference, productId: lineItem.reference,
variantId: attributes.reference, variantId: lineItem.reference,
quantity: attributes.quantity, quantity: lineItem.quantity,
price: attributes.unit_amount_float, price: lineItem.unit_amount_float,
variant: { variant: {
id, id,
name: attributes.name, name: lineItem.name,
sku: attributes.sku_code, sku: lineItem.sku_code,
price: attributes.unit_amount_float, price: lineItem.unit_amount_float,
image: { image: {
url: `https://data.commercelayer.app/vercel-provider/${attributes.reference}_FLAT.png`, url: `https://data.commercelayer.app/vercel-provider/${lineItem.reference}_FLAT.png`,
altText: attributes.name, altText: lineItem.name,
width: 1000, width: 1000,
height: 1000, height: 1000,
}, },