visionmedia / express-resource

Resourceful routing for Express
1.41k stars 140 forks source link

Adding custom actions to controller #24

Closed pacovell closed 13 years ago

pacovell commented 13 years ago

To add custom actions, today I do this (similar, this is adapted so there may be some simple errors):

    var controller = require('users_controller');
    var resource = app.resource('users', controller);

    var custom_user_actions = [
      {
        name: 'login',
        method: 'get', // or post, put, delete
        scope: 'element', // or 'collection'
        action: resource.login
      }
    ];

    // Constructs /users/:user/login for element-type actions, or /users/recent (for example) for collection-type actions
    custom_user_actions.forEach(function(action) {
      var path = '';
      if('element' == action.scope) {
        path = '/' + resource.param;
      } 
      path = path + '/' + action.name;

      // Calls resource.get, etc
      resource[action.method](path, action.action);  // Add with the proper method  
    });
  }

First, is there already a better way to do this? If it makes sense, the forEach could be integrated as a method on the Resource object pretty easily. Other approaches?

pacovell commented 13 years ago

This is already facilitated. Added test case and example: 766b220ed04d77cad4aa6223546ba60f5a022ead