derbyjs / racer

Realtime model synchronization engine for Node.js
1.18k stars 116 forks source link

Add ability to fetch only if the data is not loaded #273

Closed hdavidzhu closed 2 months ago

hdavidzhu commented 4 years ago

Currently, there are 2 ways to load data: fetch and subscribe. With a subscription, calling additional fetches or subscriptions will not issue another request. With fetch, we issue a new request anytime fetch is called.

Sometimes it's useful to only fetch if the data is not already loaded. For instance, a function might require some loaded data:

function doSomething() {
  const $account = model.at('accounts.account-id')

  const queries = []

  if (!$account.get()) queries.push($account)

  model.fetch(queries, (err) => {
    // ...
    $account.set(...)
  })
}

However, the caller may have already fetched $account:

$account.fetch((err) => {
  doSomething()
})

The intent of doSomething may just be that it needs the data, but not to refresh. In that case, we need to write additional boilerplate to fetch only if the data isn't already loaded with queries = [].

It would be nice to have something like model.fetchIfMissing(...) that does not issue additional requests if the data exists.

IAkumaI commented 4 years ago

Second fetch will not load full data. It just checks document version. You can just do

if (!model.get('some.id')) model.fetch('some.id')