-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
107 lines (91 loc) · 2.39 KB
/
index.js
File metadata and controls
107 lines (91 loc) · 2.39 KB
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
const atob = require('atob');
const btoa = require('btoa');
const isBase64 = require('is-base64');
const decodeId = (node) => {
return {
...node,
id: isBase64(node.id) ? atob(node.id) : node.id,
storefrontId: isBase64(node.id) ? node.id : btoa(node.id),
};
};
const optionsMap = (valueKey) => (map, option) => {
return {
...map,
[option.name]: option[valueKey],
};
};
const addProduct = function addProduct(node) {
return {
...node,
product: {
title: this.title,
productType: this.productType,
id: this.id,
legacyResourceId: this.legacyResourceId,
handle: this.handle,
tags: this.tags,
},
};
};
const normalizeImage = (image) => {
if (!image || !image.id) return null;
return {
...image,
id: isBase64(image.id) ? atob(image.id) : image.id,
ratio: Math.round((image.width / image.height) * 100) / 100,
};
};
const normalizeMedia = function normalizeMedia(media) {
if (media.mediaContentType === 'IMAGE') {
return {
...media,
image: normalizeImage(media.image),
previewImage: normalizeImage(media.preview.image),
};
}
return {
...media,
previewImage: normalizeImage(media.preview.image),
};
};
const normalizeProductVariant = (variant) => {
return {
...variant,
image: normalizeImage(variant.image),
selectedOptionsMap: variant.selectedOptions.reduce(optionsMap('value'), {}),
};
};
const normalizeProduct = function normalizeProduct(product) {
const variants = product.variants
.map(decodeId)
.map(addProduct, product)
.map(normalizeProductVariant);
const media = product.media
.map(decodeId)
.map(addProduct, product)
.map(normalizeMedia, product);
const images = media
.filter(({ mediaContentType }) => mediaContentType === 'IMAGE')
.map(({ image }) => image);
return {
...product,
variants,
media,
images,
featuredImage: images[0] || null,
options: product.options.map(decodeId),
optionsMap: product.options.reduce(optionsMap('values'), {}),
seo: {
title: product.seo.title || product.title,
description: product.seo.description || product.description,
},
};
};
module.exports = (input) => {
const { products, collections } = input;
const result = {
products: products.map(decodeId).map(normalizeProduct),
collections: collections.map(decodeId),
};
return result;
};