detailRefresh.js 1.5 KB

12345678910111213141516171819202122232425
  1. /** Keep only identity-matched values when this refresh explicitly fails; EMPTY is authoritative. */
  2. export function retainEquipmentRefresh(previous, next, deviceCode) {
  3. if (!previous?.data || previous.data.deviceCode !== deviceCode) return next
  4. const failed = (value) => ['failed', 'unavailable'].includes(value?.state)
  5. if (!next?.data) return failed(next)
  6. ? { ...next, state: 'stale', data: previous.data, retained: true } : next
  7. if (next.data.deviceCode !== deviceCode) return next
  8. let retained = false
  9. const retainSection = (old, current) => {
  10. if (!failed(current) || old?.data == null || !['success', 'stale', 'empty'].includes(old.state)) return current
  11. retained = true
  12. return { ...current, state: 'stale', data: old.data, retained: true }
  13. }
  14. const oldSections = previous.data.sections || {}
  15. const sections = { ...next.data.sections }
  16. for (const [name, current] of Object.entries(sections)) {
  17. sections[name] = retainSection(oldSections[name], current)
  18. }
  19. // The record feed is independent of legacy metrics; a healthy feed must still replace an old one.
  20. if (sections.metrics && next.data.sections?.metrics?.collectionRecords) {
  21. const collectionRecords = retainSection(oldSections.metrics?.collectionRecords, next.data.sections.metrics.collectionRecords)
  22. sections.metrics = { ...sections.metrics, collectionRecords }
  23. }
  24. return retained ? { ...next, retained: true, data: { ...next.data, sections } } : next
  25. }