Skip to content

Auto-invalidate or auto-update cached relations #256

@bajtos

Description

@bajtos

Consider the following code snippet from loopback-workspace:

// Project hasMany Models

project.models(function(err, list) { // (1)
  // print all models
  var modelName = // let the user choose one model
  addPermission(modelName, saveToFiles);
}

function addPermission(modelName, cb) { 
  // extract from project.addPermission()
  project.models( // (2)
    {where: { name: modelName }, limit: 1 },
    function(err, list) {
      list[0].options.acls.push({/* ACL config */});
      list[0].save(cb); // (3)
  });
}

function saveToFiles(cb) {
  // extract from project.saveToFiles
  project.models(function(err, list) { // (4)
    // build models.json from list
    // etc.
    cb();
  });
}

The line (1) fills "project.models" cache with the list of all related models. The line (2) queries the related models and returns a new copy of the model, which is saved back to the datasource in (3). Finally line (4) lists all models again, but receives stale data.

Since the modification was made through project.models, it should be possible to improve the caching mechanism, so that either:

  1. The query on related models returns existing objects from the cache, so that any updates are automatically propagated to the cache too.
  2. The save function of models returned by the query updates the cached record.
  3. The save function of models returned by the query invalidates the whole relation cache and forces the next "find-all" query to fetch fresh data from the datasource.

Workaround

Always pass 'true' as the first parameter of "find-all" queries. In other words, changing the line (4) to project.models(true, function(err, list) { fixes the problem.

Although the workaround is trivial, tracking the problem down to the related-models-cache is not straightforward.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions