GithubHelp home page GithubHelp logo

fullcube / loopback-ds-computed-mixin Goto Github PK

View Code? Open in Web Editor NEW
32.0 11.0 12.0 136 KB

A mixin to enable computed (dynamic) properties for loopback Models

License: MIT License

JavaScript 100.00%
loopback lb2 loopback-mixin fullcube mit

loopback-ds-computed-mixin's Introduction

COMPUTED

Greenkeeper badge

CircleCI Coverage Status Dependencies semantic-release

This is a mixin for the LoopBack framework that adds computed properties to a model.

A computed property is a property of which the value is set dynamically after reading model data from the data source.

  • The mixin uses the loaded observer.
  • It only runs when a single instance gets loaded, e.g. it checks ctx.instance.
  • It only runs when it is a new instance, e.g. it checks ctx.isNewInstance.
  • It overrides the configured property if one exists in the data source.

INSTALL

npm install --save loopback-ds-computed-mixin

SERVER CONFIG

Add the mixins property to your server/model-config.json:

{
  "_meta": {
    "sources": [
      "loopback/common/models",
      "loopback/server/models",
      "../common/models",
      "./models"
    ],
    "mixins": [
      "loopback/common/mixins",
      "../node_modules/loopback-ds-computed-mixin/lib",
      "../common/mixins"
    ]
  }
}

CONFIG

To use with your Models add the mixins attribute to the definition object of your model config.

The property you want to compute has to be defined in the model. The callback can be a promise too.

{
    "name": "Item",
    "properties": {
        "name": "String",
        "description": "String",
        "status": "String",
        "readonly": "boolean"
    },
    "mixins": {
        "Computed": {
            "properties": {
                "readonly": "computeReadonly"
            }
        }
    }
}

On your model you have to define the callback method.

// Set an item to readonly if status is archived
Item.computeReadonly = function computeReadonly(item) {
  return item.status === 'archived';
};

TESTING

Run the tests in test.js

  npm test

Run with debugging output on:

  DEBUG='loopback:mixin:computed' npm test

loopback-ds-computed-mixin's People

Contributors

beeman avatar greenkeeper[bot] avatar lewie6 avatar probil avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

loopback-ds-computed-mixin's Issues

Async Computed Properties affect ordering of query results, breaking query order/scopes

I have a default scope on my model 'Volume',

"scope": {
    "order": "volumeNumber ASC"
  }

which worked fine. however when I added in a computed property to the model:

"mixins": {
    "Computed": {
      "properties": {
        "attachments": "getAttachments"
      }
    }
  }

the results of finds are no longer in volumeNumber ASC order. My "getAttachments" function is async, returning a promise.

Volume.getAttachments = function (volume) {
    var Attachment = Volume.app.models.Attachment;
    var filter = {
      where: {
        modelType: 'Volume',
        foreignKey: volume.id.toString()
      }
    };
    return Attachment.find(filter).then(function(atts) { return atts; }).catch( function (err) {return err;});
}

(note the reason I don't do this using model relations is because Attachments are polymorphic and contain the info about which model they belong to within the filename itself, therefore I need to "roll my own" relation a bit).

MySQL connecter error

I tried to use this mixin and can't get it to work with the following setup:

server/server.js

var loopback = require('loopback');
var boot = require('loopback-boot');

// Otherwise Promise.map doesn't work.
global.Promise = require('bluebird');

var app = module.exports = loopback();

require('loopback-ds-computed-mixin')(app);

app.start = function() {
  // start the web server
  return app.listen(function() {
    app.emit('started');
    console.log('Web server listening at: %s', app.get('url'));
  });
};

// Bootstrap the application, configure models, datasources and middleware.
// Sub-apps like REST API are mounted via boot scripts.
boot(app, __dirname, function(err) {
  if (err) throw err;

  // start the server if `$ node server.js`
  if (require.main === module)
    app.start();
});

common/models/myModel.json

{
  "name": "MyModel",
  "options": {
    "idInjection": false,
    "mysql": {
      "schema": "someSchema",
      "table": "myModel"
    }
  },
  "properties": {
    "description": "String"
  },
  "mixins": {
    "Computed": {
      "properties": {
        "description": "computedDescription"
      }
    }
  }
}

common/models/myModel.js

module.exports = function(MyModel) {
  MyModel.computedDescription = function(myModel) {
    return "some description";
  };
};

When I try to GET /api/MyModels I get an error from the mysql connector saying it can't find the description field.

An in-range update of loopback is breaking the build 🚨

Version 3.17.1 of loopback was just published.

Branch Build failing 🚨
Dependency loopback
Current Version 3.17.0
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

loopback is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ ci/circleci Your tests failed on CircleCI Details

Commits

The new version differs by 9 commits.

  • 243af4b 3.17.1
  • b045e4a Merge pull request #3681 from zipitwireless/master
  • 317e00d Update nestRemoting to pass optionsFromContext
  • fdb4539 Merge pull request #3725 from STRML/fix/exclusive-test
  • 3af6a1b fix(test): rem exclusive test
  • 3bf84ba Merge pull request #3720 from STRML/fix/falsy-id-3.x
  • 2bfd67c fix(test): working test with 0 userId
  • b362776 fix(AccessContext): Tighten userid/appid checks
  • 0bac0a9 fix(id): replace with != null

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Where conditions?

Maybe this isn't possible, but is there a way to possibly accomplish filtering by where conditions on computed properties? Or does that defeat the purpose? I'd imagine if that is a requirement then you need to actually use the database?

Test not passing because lint

> [email protected] pretest /home/josx/Desarrollo/crear/testing/loopback-ds-computed-mixin
> npm run lint


> [email protected] lint /home/josx/Desarrollo/crear/testing/loopback-ds-computed-mixin
> jscs index.js && jshint index.js

No code style errors found.
index.js: line 17, col 85, Line is too long.
index.js: line 27, col 81, Line is too long.

2 errors

Not working with MongoDb connector

Not certain it's an issue with the MongoDb connector, but it works locally with memory datasource. Once I switch over to mongo, no luck. Adding some extra logging, the computed value gets computed correctly, and ctx.instance[property] = res gets executed with the correct value. But somehow this value never makes it to the output.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.