Skip to content

Instantly share code, notes, and snippets.

@johnnygreen
Last active January 30, 2019 03:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnnygreen/4a12c4c6a3b1a0cadcf4a61ef7c1592b to your computer and use it in GitHub Desktop.
Save johnnygreen/4a12c4c6a3b1a0cadcf4a61ef7c1592b to your computer and use it in GitHub Desktop.
(function() {
function shuffle(a) {
var j, x, i;
for (i = a.length; i; i -= 1) {
j = Math.floor(Math.random() * i);
x = a[i - 1];
a[i - 1] = a[j];
a[j] = x;
}
return a;
}
const collectionId = window.location.pathname.replace('/admin/collections/', '')
fetch(`/admin/products.json?collection_id=${collectionId}&limit=250&fields=id`)
.then(response => response.json())
.then(data => {
let ids = shuffle(data.products.map(product => product.id))
let csrf = eval(document.querySelector('[data-serialized-id="csrf"]').innerText)
let operationName = 'ReorderProducts'
let query = `
mutation ReorderProducts($id: ID!, $moves: [MoveInput!]!) {
collectionReorderProducts(id: $id, moves: $moves) {
job {
id
__typename
}
userErrors {
field
message
__typename
}
__typename
}
}
`
let variables = {
id: `gid://shopify/Collection/${collectionId}`,
moves: ids.map((id, key) => {
return {id: `gid://shopify/Product/${id}`, newPosition: `${key}`}
})
}
fetch(`/admin/api/graphql`, {
method: 'post',
mode: 'same-origin',
credentials: 'include',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-CSRF-Token': csrf,
'X-Shopify-Web-Force-Proxy': 1
},
body: JSON.stringify({
operationName: operationName,
query: query,
variables: variables
})
})
.then(() => {
window.location.reload()
})
})
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment