This repository has been archived by the owner on Feb 23, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 219
/
products-middleware.tsx
92 lines (80 loc) · 2.23 KB
/
products-middleware.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/**
* External dependencies
*/
import apiFetch from '@wordpress/api-fetch';
import type { ProductResponseItem } from '@woocommerce/types';
/**
* Internal dependencies
*/
import type { ProductItem } from './types';
type WooCommerceBlocksAPIproductResponse = ProductResponseItem;
const passProperties = ( input: ProductItem ) => {
const {
_links,
backordered,
backorders,
backorders_allowed,
button_text,
...passedProperties
} = input;
return { ...passedProperties };
};
const createPricesProperty = ( input: WooCommerceAPIproductResponse ) => {
// @todo: get actual currency data
const currency = {
currency_code: 'PLN',
currency_symbol: 'z\u0142',
currency_minor_unit: 2,
currency_decimal_separator: ',',
currency_thousand_separator: '',
currency_prefix: '',
currency_suffix: ' z\u0142',
};
// @todo: price is already formatted, not in a lowest currency unit as in store API
const { price, regular_price, sale_price } = input;
return {
price,
regular_price,
sale_price,
price_range: null,
...currency,
};
};
const createAddToCartProperty = ( input: WooCommerceAPIproductResponse ) => {
const { id, name } = input;
return {
text: 'Add to cart',
description: `Add “${ name }” to your cart`,
url: `?add-to-cart=${ id }`,
minimum: 1,
maximum: 9999,
multiple_of: 1,
};
};
export const transformProductData = (
input: WooCommerceAPIproductResponse
): WooCommerceBlocksAPIproductResponse => {
const passedProperties = passProperties( input );
return {
...passedProperties,
prices: createPricesProperty( input ),
add_to_cart: createAddToCartProperty( input ),
};
};
const defaultTransform = ( input: WooCommerceAPIproductResponse ) => input;
export const productCollectionApiFetchMiddleware = (
transform = defaultTransform
) => {
apiFetch.use( async ( options, next ) => {
const regex = /^\/wp\/v2\/product.*isProductCollectionBlock=true/;
if ( options.path && regex.test( options?.path ) ) {
const from = '/wp/v2/product';
const to = '/wc/v3/products';
const amendedPath = options.path.replace( from, to );
const response = await next( { ...options, path: amendedPath } );
const output = response.map( transform );
return output;
}
return next( options );
} );
};