dragoman 0.7.16

Server for scholarly metadata in commonmeta format stored in a SQLite database.
/**
 * The ROR of a funder, where the store knows one.
 *
 * A work names its funders by a Crossref Funder ID far more often than by a
 * ROR — `https://doi.org/10.13039/100000001` is the National Science
 * Foundation — and a Funder ID leads nowhere on this site. The server reads
 * the ROR back out of its own index of them (`/api/funders`), so a card can
 * link the funders that have a ROR record and leave the rest as text.
 *
 * Asked for lazily and in one request per batch, the way the maths renderer is
 * fetched: a card calls `funderRor` while it renders, which returns what is
 * known and asks for what is not. The answer lands in state the card read
 * during its render, so the name becomes a link a moment later. Every id is
 * asked once, whether or not it resolved.
 */
let rors = $state({})
const asked = new Set()
let pending = new Set()
let scheduled = false

/** How many a request resolves; the server takes no more. */
const BATCH = 100

async function resolve() {
  scheduled = false
  const ids = [...pending].slice(0, BATCH)
  pending = new Set([...pending].slice(BATCH))
  if (ids.length === 0) return
  const params = ids.map(id => `id=${encodeURIComponent(id)}`).join('&')
  try {
    const response = await fetch(`/api/funders?${params}`)
    if (response.ok) {
      const found = await response.json()
      // Every id asked for is recorded, the ones with no ROR as `''`, so a
      // funder the store cannot resolve is not asked for again on every card.
      rors = { ...rors, ...Object.fromEntries(ids.map(id => [id, found[id] ?? ''])) }
    }
  } catch { /* a funder that cannot be resolved stays text, as it was */ }
  if (pending.size > 0) schedule()
}

function schedule() {
  if (scheduled) return
  scheduled = true
  // After the render that asked: a page of twenty works asks once, not once
  // per card.
  queueMicrotask(resolve)
}

/**
 * The bare ROR of `funderId`, or `''` where there is none — yet, or at all.
 *
 * A ROR the record already carries is its own answer: nothing to resolve.
 */
export function funderRor(funderId = '') {
  const id = String(funderId ?? '').trim()
  if (!id || !id.includes('10.13039/')) return ''
  if (id in rors) return rors[id]
  if (!asked.has(id)) {
    asked.add(id)
    pending.add(id)
    schedule()
  }
  return ''
}