Mapping WooCommerce product structure to Webflow
As independent services, WooCommerce and Webflow have different data structures for representing products. To be able to provide products to Webflow API, we need to perform mapping of WooCommerce product structure to Webflow. To do so, we write mapping method as follows:
toCreateWebflowProductDto(wooCommerceProduct, wooCommerceStoreCurrencyCode) {
return {
product: {
fields: {
_draft: true,
_archived: false,
name: wooCommerceProduct.name,
slug: wooCommerceProduct.slug,
description: wooCommerceProduct.description,
}
},
sku: {
fields: {
_archived: false,
_draft: true,
name: wooCommerceProduct.name,
slug: wooCommerceProduct.sku,
'main-image': {
url: wooCommerceProduct.images[0].url
},
price: {
unit: wooCommerceStoreCurrencyCode,
value: wooCommerceProduct.price,
}
},
}
};
}
The resulting data structure is applicable for Webflow API to create products.
Some changes/adaptations are needed though.
When we analyze further, we can recognize the two important notes why this mapper will not work properly:
- The description in WooCommerce is HTML5 since it includes styling of the Product description.
- The price in WooCommerce is retrieved as a string. Also, it includes the decimal point. Webflow API accepts product price as the integer. So, if we want the price to be $42.00 we need to send 4200. Or, as another example, if we want the price to be $243.55, we need to send 24355 as the price value.
Considering these two notes, the final ProductMapper implementation looks like:
export class ProductMapper {
toCreateWebflowProductDto(wooCommerceProduct, wooCommerceStoreCurrencyCode) {
return {
product: {
fields: {
_draft: true,
_archived: false,
name: wooCommerceProduct.name,
slug: wooCommerceProduct.slug,
description: this.parseDescriptionStripTags(wooCommerceProduct.description),
}
},
sku: {
fields: {
_archived: false,
_draft: true,
name: wooCommerceProduct.name,
slug: wooCommerceProduct.sku,
'main-image': {
url: wooCommerceProduct.images[0].url
},
price: {
unit: wooCommerceStoreCurrencyCode,
value: this.parsePriceToInt(wooCommerceProduct.price),
}
},
}
};
}
parseDescriptionStripTags(description) {
return description.replace(/<\/?[^>]+(>|$)/g, "");
}
parsePriceToInt(price) {
if (price.indexOf('.') === -1) {
return parseInt(price) * 100;
} else {
const parts = price.split('.');
if (parts[1].length > 2) {
parts[1] = parts[1].substring(0, 2);
} else if (parts[1].length === 1) {
parts[1] += '0';
}
price = parts.join('');
return parseInt(price);
}
}
}
By finalizing this step, we are able to retrieve the product from WooCommerce and map it to the appropriate structure for WebFlow API.