Skip to content

Instantly share code, notes, and snippets.

@pveen2
Created September 16, 2022 06:18
Show Gist options
  • Save pveen2/0bafeb3bd1686c92bb31cf40988e642f to your computer and use it in GitHub Desktop.
Save pveen2/0bafeb3bd1686c92bb31cf40988e642f to your computer and use it in GitHub Desktop.
const wishlistApi = async ({req, res, shopifyAccessToken, shopifyDomain, allowedOrigins, metafieldNamespace, metafieldKey}) => {
const shopifyAdminConfig = {
Accept: 'application/json',
'Content-Type': 'application/json',
'X-Shopify-Access-Token': shopifyAccessToken,
};
const apiVersion = '2022-07'
const preparePayload = (query, variables) => ({
query,
variables,
});
const CUSTOMER_QUERY = `
query customerQuery($email: String!) {
customers(first: 1, query: $email) {
edges {
node {
id
metafield(namespace: "${metafieldNamespace}", key: "${metafieldKey}") {
id
}
}
}
}
}
`;
const METAFIELD_DELETE_MUTATION = `
mutation metafieldDelete($input: MetafieldDeleteInput!) {
metafieldDelete(input: $input) {
deletedId
userErrors {
field
message
}
}
}
`;
const CUSTOMER_UPDATE_MUTATION = `
mutation customerUpdate($input: CustomerInput!) {
customerUpdate(input: $input) {
customer {
id
}
userErrors {
field
message
}
}
}
`;
// we pass an array of origin strings in allowedOrigins. If it matches, we set the CORS header
if (allowedOrigins.includes(req.headers.origin)) {
res.setHeader('Access-Control-Allow-Origin', req.headers.origin);
}
// (1) call customer to get customer id for customer update mutation
// (2) call metafieldDelete to remove metafield if it already exists (because we cannot overwrite metafield)
// (3) call customer update mutation to update metafielfd
let input;
try {
input = JSON.parse(req.body);
} catch (error) {
// eslint-disable-next-line no-console
console.error('JSON parsing error when trying to set customer wishlist:', error);
return res.status(400).json({ error: 'Bad request body' });
}
if (!input?.wishlist || !input?.email) {
return res.status(400).json({ error: 'Bad request body' });
}
let customerId;
let metafieldId;
const payloadCustomer = preparePayload(CUSTOMER_QUERY, {
email: `email:${input.email}`,
});
try {
const customerRes = await fetch(
`https://${shopifyDomain}.myshopify.com/admin/api/${apiVersion}/graphql`,
{
method: 'POST',
headers: shopifyAdminConfig,
body: JSON.stringify(payloadCustomer),
}
);
if (customerRes.ok) {
const { data: customerData } = await customerRes.json();
customerId = customerData.customers.edges[0]?.node.id;
metafieldId = customerData.customers.edges[0]?.node.metafield?.id || null;
if (!customerId) {
return res.status(500).json({ error: 'Cannot find customer' });
}
}
} catch (error) {
return res.status(500).json({ error: error.message });
}
if (metafieldId) {
const payloadDeleteMetafield = preparePayload(METAFIELD_DELETE_MUTATION, {
input: {
id: metafieldId,
},
});
try {
const metafieldRes = await fetch(
`https://${shopifyDomain}.myshopify.com/admin/api/${apiVersion}/graphql`,
{
method: 'POST',
headers: shopifyAdminConfig,
body: JSON.stringify(payloadDeleteMetafield),
}
);
if (!metafieldRes.ok) {
return res.status(500).json({ error: 'Failed to set customer wishlist' });
}
} catch (error) {
return res.status(500).json({ error: error.message });
}
}
const payloadMutateCustomer = preparePayload(CUSTOMER_UPDATE_MUTATION, {
input: {
id: customerId,
metafields: [
{
namespace: metafieldNamespace,
key: metafieldKey,
value: JSON.stringify(input.wishlist),
type: 'json',
},
],
},
});
try {
const customerRes = await fetch(
`https://${shopifyDomain}.myshopify.com/admin/api/${apiVersion}/graphql`,
{
method: 'POST',
headers: shopifyAdminConfig,
body: JSON.stringify(payloadMutateCustomer),
}
);
if (customerRes.ok) {
const { data: customerData } = await customerRes.json();
return res.status(200).json({ customer: customerData });
}
return res.status(500).json({ error: 'Failed to set customer wishlist' });
} catch (error) {
return res.status(500).json({ error: error.message });
}
}
export default wishlistApi;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment