— javascript, es6, chunk, process, nodejs, code snippet, today-i-learned — 1 min read
(Copypasta from the other shell script post!) Was writing a script to pull metadata from an NFT collection.
I had to write a loop that queried the API for the asset ID, which then generated JSON files in batches of 10, now prepopulated with asset IDs. These weren't in proper JSON format yet, so I had to add the array brackets at the start and end of the file. Also had to account for customization (in case we want to try querying for another NFT project).
It was one of those rare times I get to write a utility script with no RESTful API involved, a.k.a., not work.
My implementation:
1// ENV VAR2const args = process.argv.slice(2);34const policyId = args[0];
When running it on Terminal:
1node 02_generate_batch_queries.js <POLICY_ID>
Then some quick and simple code for chunking, ref: SO Answer:
1// generate query strings that will output to specific batch files2const result = fullArray.reduce((resultArray, item, index) => {3 const chunkIndex = Math.floor(index / CHUNK_SIZE);4 if (!resultArray[chunkIndex]) {5 resultArray[chunkIndex] = []; // start a new chunk6 }78 const textQuery = `${queryString}${item.asset} >> ${METADATA_FILE_PREFIX}${chunkIndex}.json`;910 resultArray[chunkIndex].push(textQuery);11 return resultArray;12}, []);