Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
marcomontalbano committed Jun 27, 2024
1 parent 5c0e64d commit 140cb32
Show file tree
Hide file tree
Showing 25 changed files with 1,621 additions and 2,027 deletions.
2 changes: 1 addition & 1 deletion .npmrc
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
engine-strict=true
use-node-version=18.18.0
use-node-version=20.12.2
strict-peer-dependencies=false
2 changes: 1 addition & 1 deletion packages/drop-in/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@
},
"dependencies": {
"@commercelayer/js-auth": "^6.2.2",
"@commercelayer/sdk": "^5.45.0",
"@commercelayer/core-sdk": "v0.0.0-alpha.6",
"@types/lodash": "^4.17.5",
"iframe-resizer": "4.4.2",
"js-cookie": "^3.0.5",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ function mockSkuListItem(
updated_at: time,
id: `123`,
quantity: skuListItem.quantity,
// @ts-expect-error asd
sku: {
code: '123',
created_at: time,
Expand Down
15 changes: 12 additions & 3 deletions packages/drop-in/src/apis/commercelayer/bundles/bundles.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { fireEvent } from '#apis/event'
import type { Bundle, GetBundle, Inventory } from '#apis/types'
import { readItem } from '@commercelayer/core-sdk'
import { memoize } from '../../../utils/utils'
import { createClient } from '../client'
import { getConfig } from '../config'
Expand Down Expand Up @@ -41,9 +42,17 @@ const getMemoizedBundle = memoize<GetBundle>(async (code) => {

const client = await createClient(getConfig())

const bundle = (await client.bundles.retrieve(id, {
include: ['sku_list.sku_list_items.sku']
})) as Bundle
const bundle = (await client.request(
readItem('bundles', id, {
include: {
sku_list: {
sku_list_items: {
sku: {}
}
}
}
})
)) as Bundle

return {
...bundle,
Expand Down
41 changes: 22 additions & 19 deletions packages/drop-in/src/apis/commercelayer/bundles/list.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { Bundle } from '#apis/types'
import { pDebounce } from '#utils/debounce'
import { logGroup } from '#utils/logger'
import { readItems } from '@commercelayer/core-sdk'
import { chunk, memoize, uniq } from '../../../utils/utils'
import { createClient } from '../client'
import { getConfig } from '../config'
Expand All @@ -26,25 +27,27 @@ const _getBundlesViaList = async (codes: string[]): Promise<BundleViaList> => {
const response = (
await Promise.all(
chunkedCodes.map(async (codes) => {
return await client.bundles.list({
pageSize,
filters: { code_in: codes.join(',') },
fields: {
bundles: [
'id',
'code',
'compare_at_amount_cents',
'compare_at_amount_float',
'created_at',
'currency_code',
'formatted_compare_at_amount',
'formatted_price_amount',
'price_amount_cents',
'price_amount_float',
'updated_at'
]
}
})
return await client.request(
readItems('bundles', {
pageSize,
filters: [{ or: ['code'], matcher: { in: codes.join(',') } }],
fields: {
bundles: [
'id',
'code',
'compare_at_amount_cents',
'compare_at_amount_float',
'created_at',
'currency_code',
'formatted_compare_at_amount',
'formatted_price_amount',
'price_amount_cents',
'price_amount_float',
'updated_at'
]
}
})
)
})
)
).flat()
Expand Down
6 changes: 4 additions & 2 deletions packages/drop-in/src/apis/commercelayer/bundles/prices.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { fireEvent } from '#apis/event'
import type { GetBundlePrice } from '#apis/types'
import type { Price } from '@commercelayer/sdk'
import type { Price, PriceList, Sku } from '@commercelayer/core-sdk'
import { memoize } from '../../../utils/utils'
import { _getBundleViaList } from './list'

Expand All @@ -21,7 +21,9 @@ const getMemoizedPrice = memoize<GetBundlePrice>(async (code) => {
id: bundle.id,
type: 'prices',
updated_at: bundle.updated_at,
currency_code: bundle.currency_code
currency_code: bundle.currency_code,
price_list: {} as unknown as PriceList,
sku: {} as unknown as Sku
}

return price
Expand Down
100 changes: 65 additions & 35 deletions packages/drop-in/src/apis/commercelayer/cart.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,14 @@ import type {
TriggerHostedCartUpdate
} from '#apis/types'
import { pDebounce } from '#utils/debounce'
import type { Order, QueryParamsRetrieve } from '@commercelayer/sdk'
import {
createItem,
readItem,
readRelationships,
updateItem,
type Order,
type ReadItemQuery
} from '@commercelayer/core-sdk'
import Cookies from 'js-cookie'
import memoize from 'lodash/memoize'

Expand All @@ -22,9 +29,11 @@ async function createEmptyCart(): Promise<Order> {
const client = await createClient(config)
const token = await getAccessToken(config)

const order = await client.orders.create({
return_url: config.orderReturnUrl
})
const order = await client.request(
createItem('orders', {
return_url: config.orderReturnUrl
})
)

if (token.type === 'guest') {
setCartId(order.id)
Expand Down Expand Up @@ -110,8 +119,15 @@ export async function _getCart(): Promise<Order | null> {
const client = await createClient(config)
const token = await getAccessToken(config)

const orderParams: QueryParamsRetrieve = {
include: ['line_items.item', 'line_items.line_item_options.sku_option']
const orderParams: ReadItemQuery<'orders'> = {
include: {
line_items: {
item: {},
line_item_options: {
sku_option: {}
}
}
}
}

if (token.type === 'guest') {
Expand All @@ -121,9 +137,7 @@ export async function _getCart(): Promise<Order | null> {
return null
}

const order = await client.orders
.retrieve(orderId, orderParams)
.catch(() => null)
const order = await client.request(readItem('orders', orderId, orderParams))

if (order?.editable === false) {
removeCartId()
Expand All @@ -133,18 +147,30 @@ export async function _getCart(): Promise<Order | null> {
return order
}

const [order = null] = await client.customers.orders(token.customerId, {
...orderParams,
filters: {
guest_false: true,
editable_true: true,
status_eq: 'pending'
},
sort: {
updated_at: 'desc'
},
pageSize: 1
})
const [order = null] = await client.request(
readRelationships('customers', token.customerId, 'orders', {
...orderParams,
filters: [
{
or: ['guest'],
matcher: { false: 'true' }
},
{
/** @ts-expect-error // TODO: why editable is not filterable? */
or: ['editable'],
matcher: { true: 'true' }
},
{
or: ['status'],
matcher: { eq: 'pending' }
}
],
sort: {
updated_at: 'desc'
},
pageSize: 1
})
)

return order
}
Expand Down Expand Up @@ -183,16 +209,19 @@ export const addItem: AddItem = async (kind, code, quantity, options = {}) => {
const client = await createClient(getConfig())
const orderId = (await getCart())?.id ?? (await createEmptyCart()).id

const lineItem = await client.line_items.create({
...options,
order: {
id: orderId,
type: 'orders'
},
quantity,
...(kind === 'sku' ? { sku_code: code } : { bundle_code: code }),
_update_quantity: true
})
const lineItem = await client.request(
createItem('line_items', {
relationships: {
order: {
type: 'orders',
id: orderId
}
},
quantity,
...(kind === 'sku' ? { sku_code: code } : { bundle_code: code }),
_update_quantity: true
})
)

fireEvent('cl-cart-additem', [kind, code, quantity, options], lineItem)

Expand All @@ -215,9 +244,10 @@ export async function updateCartUrl(cartUrl: string): Promise<void> {

if (cart !== null && cart.cart_url !== cartUrl) {
const client = await createClient(getConfig())
await client.orders.update({
id: cart.id,
cart_url: cartUrl
})
await client.request(
updateItem('orders', cart.id, {
cart_url: cartUrl
})
)
}
}
12 changes: 5 additions & 7 deletions packages/drop-in/src/apis/commercelayer/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {
type AuthenticateOptions,
type AuthenticateReturn
} from '@commercelayer/js-auth'
import CommerceLayer, { type CommerceLayerClient } from '@commercelayer/sdk'
import { createCommerceLayer, rest } from '@commercelayer/core-sdk'
import Cookies from 'js-cookie'
import memoize from 'lodash/memoize'
import { getConfig, type Config } from './config'
Expand Down Expand Up @@ -174,16 +174,14 @@ export const getAccessToken = memoize(
(clientCredentials) => JSON.stringify(clientCredentials)
)

export async function createClient(
config: Config
): Promise<CommerceLayerClient> {
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
export async function createClient(config: Config) {
const token = await getAccessToken(config)

return CommerceLayer({
return createCommerceLayer({
accessToken: token.accessToken,
organization: config.slug,
domain: config.domain
})
}).with(rest())
}

export async function logout(): Promise<void> {
Expand Down
17 changes: 10 additions & 7 deletions packages/drop-in/src/apis/commercelayer/skus/list.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type { Sku } from '#apis/types'
import { pDebounce } from '#utils/debounce'
import { logGroup } from '#utils/logger'
import { chunk, memoize, uniq } from '#utils/utils'
import { readItems } from '@commercelayer/core-sdk'
import { createClient } from '../client'
import { getConfig } from '../config'

Expand All @@ -26,13 +27,15 @@ const _getSkusViaList = async (codes: string[]): Promise<SkuViaList> => {
const response = (
await Promise.all(
chunkedCodes.map(async (codes) => {
return await client.skus.list({
pageSize,
filters: { code_in: codes.join(',') },
fields: {
skus: ['id', 'code']
}
})
return await client.request(
readItems('skus', {
pageSize,
filters: [{ or: ['code'], matcher: { in: codes.join(',') } }],
fields: {
skus: ['id', 'code']
}
})
)
})
)
).flat()
Expand Down
17 changes: 12 additions & 5 deletions packages/drop-in/src/apis/commercelayer/skus/prices.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { fireEvent } from '#apis/event'
import type { GetSkuPrice } from '#apis/types'
import { pDebounce } from '#utils/debounce'
import { logGroup } from '#utils/logger'
import type { Price } from '@commercelayer/sdk'
import { type Price, readItems } from '@commercelayer/core-sdk'
import { chunk, memoize, uniq } from '../../../utils/utils'
import { createClient } from '../client'
import { getConfig } from '../config'
Expand Down Expand Up @@ -30,10 +30,17 @@ const _getPrices = async (skus: string[]): Promise<PriceList> => {
const pricesResponse = (
await Promise.all(
chunkedSkus.map(async (skus) => {
return await client.prices.list({
pageSize,
filters: { sku_code_in: skus.join(',') }
})
return await client.request(
readItems('prices', {
pageSize,
filters: [
{
or: [{ sku: 'code' }],
matcher: { in: skus.join(',') }
}
]
})
)
})
)
).flat()
Expand Down
3 changes: 2 additions & 1 deletion packages/drop-in/src/apis/commercelayer/skus/skus.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { fireEvent } from '#apis/event'
import type { GetSku, Sku } from '#apis/types'
import { memoize } from '#utils/utils'
import { readItem } from '@commercelayer/core-sdk'
import { createClient } from '../client'
import { getConfig } from '../config'
import { _getSkuViaList } from './list'
Expand All @@ -14,7 +15,7 @@ const getMemoizedSku = memoize<GetSku>(async (code) => {

const client = await createClient(getConfig())

const sku = (await client.skus.retrieve(id)) as Sku
const sku = (await client.request(readItem('skus', id))) as Sku

return sku
})
Expand Down
2 changes: 1 addition & 1 deletion packages/drop-in/src/apis/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import type {
Sku as SdkSku,
SkuList,
SkuListItem
} from '@commercelayer/sdk'
} from '@commercelayer/core-sdk'
import { type Token } from './commercelayer/client'

interface DeliveryLeadTime {
Expand Down
Loading

0 comments on commit 140cb32

Please sign in to comment.