-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstorefrontClient.js
More file actions
115 lines (101 loc) · 2.64 KB
/
storefrontClient.js
File metadata and controls
115 lines (101 loc) · 2.64 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
108
109
110
111
112
113
114
115
// [START integrate.config]
const STOREFRONT_ACCESS_TOKEN = 'your-storefront-access-token';
const SHOP_DOMAIN = '{shop}.myshopify.com';
const API_VERSION = '2026-01';
// [END integrate.config]
// [START complete-tutorial.fetch-products]
async function fetchProducts() {
const query = `
query Products {
products(first: 10) {
edges {
node {
id
title
description
featuredImage { url }
variants(first: 1) {
edges {
node {
id
title
price { amount currencyCode }
}
}
}
}
}
}
}
`;
const response = await fetch(
`https://${SHOP_DOMAIN}/api/${API_VERSION}/graphql.json`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Shopify-Storefront-Access-Token': STOREFRONT_ACCESS_TOKEN,
},
body: JSON.stringify({ query }),
}
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const { data, errors } = await response.json();
if (errors) {
throw new Error(errors[0].message);
}
return data.products.edges.map(edge => edge.node);
}
// [END complete-tutorial.fetch-products]
// [START complete-tutorial.create-cart]
async function createCart(variantId, quantity = 1) {
const mutation = `
mutation CartCreate($input: CartInput!) {
cartCreate(input: $input) {
cart {
id
checkoutUrl
}
userErrors {
field
message
}
}
}
`;
const response = await fetch(
`https://${SHOP_DOMAIN}/api/${API_VERSION}/graphql.json`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Shopify-Storefront-Access-Token': STOREFRONT_ACCESS_TOKEN,
},
body: JSON.stringify({
query: mutation,
variables: {
input: {
lines: [{ merchandiseId: variantId, quantity }],
},
},
}),
}
);
const { data, errors } = await response.json();
if (errors) {
throw new Error(errors[0].message);
}
if (data.cartCreate.userErrors.length > 0) {
throw new Error(data.cartCreate.userErrors[0].message);
}
return data.cartCreate.cart;
}
// [END complete-tutorial.create-cart]
// [START integrate.cart-permalink]
function buildCartPermalink(variantId, quantity = 1) {
return `https://${SHOP_DOMAIN}/cart/${variantId}:${quantity}`;
}
// [END integrate.cart-permalink]
export { fetchProducts, createCart, buildCartPermalink, SHOP_DOMAIN };