You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让ES6模块支持动态数据依赖?API动态更新方案问询

Dynamic Data Dependency Handling for API with MongoDB & ES6 Modules

I'm working on an API that relies on two data objects pulled from MongoDB collections:

  • mycompanyProducts
  • mycompanySettings

The mycompanyProducts structure looks like this:

{
  "MYTHING01": {
    "sku": "MYTHING01",
    "name": "15-Pack",
    "price": 30,
    "shopifyData": {
      "id": "7987037995068",
      "product_id": "664292996940",
      "price": "30.00",
      "taxable": true,
      "inventory_quantity": 10,
      "weight": 2,
      "weight_unit": "kg",
      "lastFetched": { "$date": "2018-05-09T14:16:57.209Z" }
    }
  },
  "MYTHING02": {
    "sku": "MYTHING02",
    "name": "5-Pack",
    "price": 15,
    "shopifyData": {
      "id": "7836960168028",
      "product_id": "645959671756",
      "price": "15.00",
      "taxable": true,
      "inventory_quantity": 10,
      "weight": 2,
      "weight_unit": "kg",
      "lastFetched": { "$date": "2018-05-09T14:16:57.228Z" }
    }
  }
}

The mycompanySettings collection holds app configurations like maximum image upload size (in MB) and other environment-specific values.

Here's the core requirement: after updating either MongoDB collection, the API should pick up the new data without needing a full rebuild — I want to avoid the hassle of triggering rebuilds via Shopify webhooks. Additionally, if a product's shopifyData.lastFetched timestamp is older than 10 minutes, we need to refresh that product's data from Shopify first. Here's the refresh logic I have so far:

// Loop through each Shopify product and update the product in the db
await Promise.all(res.data.products.map(async (shopifyProduct) => {
  const variant = shopifyProduct.variants.find(v => mySKUs.includes(v.sku))
  product.shopifyData = {
    ...variant,
    lastFetched: new Date(),
  }
  await product.save()
}))

The problem I'm stuck on is that ES6 modules use static exports, which means the data only loads once at module initialization — so I have to rebuild the API to get fresh data. I tried exporting async functions that return the latest dependencies, but this has limitations:

  • I can't use await at the top level in React components (which consume this API data)
  • Even if I call the async function, it only runs once when the module loads, so it doesn't fetch updated data later

I'm looking for a general solution that works across both backend API logic and frontend React components, allowing real-time access to the latest MongoDB data without requiring rebuilds. Any advice or patterns would be greatly appreciated!

内容的提问来源于stack exchange,提问作者j_d

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:40:32