I have this function to grab data from the shopify API:
async function getProductsMetaData () {
const productsQuery = client.graphQLClient.query((root) => {
root.addConnection('products', { args: { first: 250 } }, (product) => {
product.add('title');
product.add('tags');
});
});
let result = await client.graphQLClient.send(productsQuery);
let metaData = {};
result.data.products.edges.forEach(p => {
let product = p.node;
metaData[product.id] = {
tags: product.tags,
};
});
return metaData;
}
this works just fine if i try to grab it after my server has started, like this:
shopify.getProductsMetaData().then((metaData) => console.log('metadata:',metaData)).catch(e=>console.error('error:',e));
but i dont want this function to be run with every single page load, I want it only to run the first time, and subsequent times it should just grab the data it fetched initially.
I thought this would be a perfect case for a promise:
let productsMetaData = new Promise(async (resolve, reject) => {
try {
resolve(await getProductsMetaData());
} catch (e) {
reject(e);
}
});
I could then just do await productsMetaData and it would return the data immediately (or run the function if it’s the first time).
But that promise is giving me a weird hard to understand error:
ReferenceError: fetch is not defined
at Client.fetcher (project/node_modules/shopify-buy/index.unoptimized.umd.js:1874:5)
at Client.send (project/node_modules/shopify-buy/index.unoptimized.umd.js:2076:19)
at getProductsMetaData (project/modules/node/shopify/shopify.js:42:42)
at project/modules/node/shopify/shopify.js:57:17
at new Promise (<anonymous>)
at Object.<anonymous> (project/modules/node/shopify/shopify.js:55:24)
at Module._compile (node:internal/modules/cjs/loader:1126:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1180:10)
at Module.load (node:internal/modules/cjs/loader:1004:32)
at Function.Module._load (node:internal/modules/cjs/loader:839:12)
at Module.require (node:internal/modules/cjs/loader:1028:19)
at require (node:internal/modules/cjs/helpers:102:18)
at Object.<anonymous> (project/projects/pixel-school/routes/pixel-school.js:3:17)
at Module._compile (node:internal/modules/cjs/loader:1126:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1180:10)
at Module.load (node:internal/modules/cjs/loader:1004:32)
The 3rd line in the trace is the file this is declared in, pointing the line let result = await client.graphQLClient.send(productsQuery);, which is weird, because that line works just fine when it’s run later.
What could possibly be causing this?