Skip to content

Instantly share code, notes, and snippets.

@bajtos
Created September 9, 2014 16:27
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bajtos/213d5dae87e19f47db5d to your computer and use it in GitHub Desktop.
Save bajtos/213d5dae87e19f47db5d to your computer and use it in GitHub Desktop.
Add a custom remote method to a full-stack LoopBack AngularJS applications

This is an extra exercise for the workshop Building a full-stack application with LoopBack and AngularJS.

Add a custom model method

Let's write a method Whiskey.prototype.ratingStats that will provide a breakdown of rating data for a given whiskey. This method should be defined in common/models/whiskey.js. Below is a template, it's up to the reader to implement the statistical computation.

module.exports = function(Whiskey) {
  Whiskey.prototype.ratingStats = function(cb) {
    // TODO: compute rating statistics
    // the whiskey id is available as `this.id`
    cb(null, {
      5: 10, // percent
      4: 30, 
      3: 40,
      2: 10,
      1: 10
    });
  };

  Whiskey.setup = function() {
    Whiskey.base.setup.apply(this, arguments);

    this.remoteMethod('ratingStats', {
      isStatic: false,
      returns: [{ arg: 'stats', type: 'object' }]
    });
  };

  Whiskey.setup();
};

Use the LoopBack Explorer to test this new function via the REST API. Re-run lb-ng to update the Angular client services and have the method available in the client app too.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment