Skip to content

Instantly share code, notes, and snippets.

@enriquebeta6
Created July 25, 2024 21:56
Show Gist options
  • Save enriquebeta6/87256e0f23e13cfa055f89ac9140fcfb to your computer and use it in GitHub Desktop.
Save enriquebeta6/87256e0f23e13cfa055f89ac9140fcfb to your computer and use it in GitHub Desktop.
Script for "add all the products to collection"
{
"name": "scripts",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"@apollo/client": "^3.11.1",
"cross-fetch": "^4.0.0",
"graphql": "^16.9.0"
},
"devDependencies": {
"react": "^18.3.1"
}
}
const ApolloClientModule = require("@apollo/client")
const RetryLink = require("@apollo/client/link/retry").RetryLink
const { ApolloClient, gql, from, HttpLink, InMemoryCache } = ApolloClientModule
const client = getApolloClient()
main()
async function main() {
let lastPage = 0
let currentPage = 1
const collectionId = null
do {
const { items: productIds , paging } = await getProductsIds(currentPage)
if (lastPage === 0) {
lastPage = paging.pages
}
console.log(`page ${currentPage} of ${lastPage}`)
if (productIds.length === 0} break
await insertProductsToCollection(productIds, collectionId)
currentPage += 1
} while(currentPage <= lastPage)
}
async function getProductsIds(page = 1, pageSize = 100) {
const query = gql`
query productsIds($page: Int!, $pageSize: Int!) {
productsIds(term: "", page: $page, pageSize: $pageSize) {
items
paging {
pages
total
}
}
}
`
const { data, errors } = await client.query({
query,
variables: {
page,
pageSize
}
})
if (errors) {
console.log('getProductsIds', errors)
}
return data?.productsIds
}
async function insertProductsToCollection(productIds, collectionId) {
const mutation = gql`
mutation insertProducts($input: CollectionProductsInput) {
insertProductsToCollection(input: $input)
}
`
const { errors } = await client.mutate({
mutation,
variables: {
input: {
productIds,
collectionId,
}
}
})
if (errors) {
console.log('insertProductsToCollection', errors)
}
}
function getApolloClient() {
const account = ''
const uri = `https://${account}.myvtex.com/_v/private/graphql/v1`
const SIXTY_SECONDS = 1000 * 60
const headers = {
"content-type": "application/json",
// cookie with auth credentials
cookie: "",
}
const link = from([
new RetryLink({
delay: {
jitter: true,
initial: 200,
max: SIXTY_SECONDS,
},
attempts: {
max: 5,
}
}),
new HttpLink({
uri,
headers,
credentials: "include",
}),
])
return new ApolloClient({
link,
credentials: 'include',
cache: new InMemoryCache(),
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment