This repository has been archived by the owner on Jan 9, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 14
/
shopify.js
185 lines (165 loc) · 5.44 KB
/
shopify.js
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
const sanityClient = require('@sanity/client');
const {
REACT_APP_SANITY_API_TOKEN,
REACT_APP_SANITY_PROJECT_ID,
REACT_APP_SANITY_DATASET,
} = process.env;
const client = sanityClient({
projectId: REACT_APP_SANITY_PROJECT_ID,
dataset: REACT_APP_SANITY_DATASET,
token: REACT_APP_SANITY_API_TOKEN,
useCdn: true
});
exports.handler = async (event, context) => {
if (event.httpMethod !== 'POST' || !event.body) {
return {
statusCode: 400,
body: ''
};
}
let data;
let hasVariantsToSync = false;
try {
data = JSON.parse(event.body);
} catch (error) {
console.error('JSON parsing error:', error);
return {
statusCode: 400,
body: JSON.stringify({
error: 'Bad request body'
})
};
}
// Shopify sends both Product Updates/Creations AND deletions as POST requests
// Product Updates & Creations contain the entire product body, including titles, tags, images, handle, etc.
// Product Deletions only contain a singular 'id'
if (data.hasOwnProperty('title') && data.hasOwnProperty('handle')) {
// Build our initial product
const product = {
_type: 'product',
_id: data.id.toString(),
productId: data.id,
title: data.title,
defaultPrice: data.variants[0].price,
slug: {
_type: 'slug',
current: data.handle
}
};
return client
.transaction()
.createIfNotExists(product)
.patch(data.id.toString(), patch => patch.set(product))
.commit()
.then(res => {
console.log(`Successfully updated/patched Product ${data.id} in Sanity`);
if (data.variants.length > 1) {
hasVariantsToSync = true;
return Promise.all(data.variants.map(variant => {
const variantData = {
_type: 'productVariant',
_id: variant.id.toString(),
productId: data.id,
variantId: variant.id,
title: data.title,
variantTitle: variant.title,
sku: variant.sku,
price: variant.price
};
return client
.transaction()
.createIfNotExists(variantData)
.patch(variant.id.toString(), patch => patch.set(variantData))
.commit()
.then(response => {
console.log(`Successfully updated/patched Variant ${variant.id} in Sanity`);
return response;
})
.catch(error => {
console.error('Sanity error:', error);
return error;
});
})).then(result => {
if (hasVariantsToSync) {
return client
.transaction()
.createIfNotExists(product)
.patch(data.id.toString(), patch => patch.set({
variants: data.variants.map(variant => ({
_type: 'reference',
_ref: variant.id.toString(),
_key: variant.id.toString(),
}))
}))
.commit()
.then(response => {
console.log(`Successfully added variant references to ${data.id} in Sanity`);
return {
statusCode: 200,
body: JSON.stringify(response)
};
})
.catch(error => {
console.error('Sanity error:', error);
return error;
});
} else {
return {
statusCode: 200,
body: JSON.stringify(res)
};
}
}).catch(error => {
console.error('Sanity error:', error);
return {
statusCode: 500,
body: JSON.stringify({
error: 'An internal server error has occurred',
})
};
});
} else {
return {
statusCode: 200,
body: JSON.stringify(res)
};
}
})
.catch(error => {
console.error('Sanity error:', error);
return {
statusCode: 500,
body: JSON.stringify({
error: 'An internal server error has occurred',
})
};
});
} else if (data.hasOwnProperty('id') && (!data.hasOwnProperty('title') && !data.hasOwnProperty('handle'))) {
// this is triggered if Shopify sends a Product Deletion webhook that does NOT contain anything besides an ID
// sets the "deleted" boolean to true
// you could likely use this value in Gatsby to decide whether to render the item or not
// tread carefully:
return client
.patch(data.id.toString())
.set({ deleted: true })
.commit()
.then(deletedObject => {
console.log(`successfully marked ${data.id} as 'deleted'`)
})
.catch(error => {
console.error(`Sanity error:`, error)
})
// *~* OR *~*
// DELETE FROM SANITY
// tread carefully here: you might not want to do this if you have products associated anywhere else such as "related products" or any other schemas.
// this will likely cause in your schemas breaking
// return client
// .delete(data.id.toString())
// .then(res => {
// console.log(`Successfully deleted product ${data.id}`)
// })
// .catch(err => {
// console.error('Delete failed: ', err.message)
// })
}
};