Search code examples
flatiron.js

Get query string params using Restful / Resourceful / Flatiron


I have the following node app using Restful / Resourceful / Flatiron:

app.js

var flatiron    = require('flatiron'),
    fixtures    = require('./fixtures'),
    restful     = require('restful'),
    resourceful = require('resourceful');

var app = module.exports = flatiron.app;
app.resources = {};
app.resources.Creature = fixtures.Creature;

app.use(flatiron.plugins.http, {
  headers: {
    'x-powered-by': 'flatiron ' + flatiron.version
  }
});
app.use(restful);
app.start(8000, function(){
  console.log(app.router.routes);
  console.log(' > http server started on port 8000');
  console.log(' > visit: http://localhost:8000/ ');
});

Here is the fixtures module:

fixtures.js

var fixtures = exports;

var resourceful = require('resourceful');

// // Create a new Creature resource using the Resourceful library //
fixtures.Creature = resourceful.define('creature', function () {

   var self = this;

   this.restful = true;

   this.all = function (callback) {
     console.log(this);
     callback(null, "ok");   };

 });

How can I access the request/query string parameters? E.g. if the route is /creatures?foo=bar

I came across this issue from the Github repo, but the comments imply there may be a more long winded method of obtaining this data?

I've been looking at the source code for resourceful and I don't see a clear way. Here is the line in question:

https://github.com/flatiron/resourceful/blob/master/lib/resourceful/resource.js#L379


Solution

  • The default versions listed via NPM Package Manager are out of date which caused some confusion.

    See the Github issue here:

    https://github.com/flatiron/restful/issues/33

    Using package.json in combination with NPM install works with the version combinations:

    "restful": "0.4.4",
    "director": "1.1.x",
    "resourceful": "0.3.x",
    "director-explorer": "*"
    

    With this newer version the url format now works in the style of:

    /create/find?foo=bar

    The method in question is can be found here:

    https://github.com/flatiron/restful/blob/master/lib/restful.js#L506

    At the time of writing the method looks as follows:

      router.get('/' + entity + '/find', function () {
        var res = this.res,
            req = this.req;
        preprocessRequest(req, resource, 'find');
        resource.find(req.restful.data, function(err, result){
          respond(req, res, 200, entity, result);
        });
      });
    

    The key component being that req.restful.data is the parsed query string data.