Skip to content

Commit

Permalink
oops
Browse files Browse the repository at this point in the history
  • Loading branch information
mikermcneil committed May 12, 2014
1 parent 84e0b26 commit 952c380
Show file tree
Hide file tree
Showing 6 changed files with 272 additions and 194 deletions.
1 change: 1 addition & 0 deletions lib/app/request.js
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ module.exports = function request( /* address, body, cb */ ) {
// Don't include body if it is empty
if (!clientRes.body) delete clientRes.body;

console.log(clientRes.statusCode, clientRes);
// If status code is indicative of an error, send the
// response body or status code as the first error argument.
if (clientRes.statusCode < 200 || clientRes.statusCode >= 400) {
Expand Down
155 changes: 5 additions & 150 deletions lib/router/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ _.defaults = require('merge-defaults');
var express = require('express');
var Writable = require('stream').Writable;

var buildRequest = require('./req');
var buildResponse = require('./res');

var defaultHandlers = require('./bindDefaultHandlers');


Expand Down Expand Up @@ -152,8 +155,8 @@ Router.prototype.route = function(req, res, next) {

// Make sure request and response objects have reasonable defaults
// (will use the supplied definitions if possible)
req = reasonableDefaultRequest(req);
res = reasonableDefaultResponse(req, res);
req = buildRequest(req,res);
res = buildResponse(req,res);

// Use our private router to route the request
this._privateRouter.router(req, res, function handleUnmatchedNext(err) {
Expand Down Expand Up @@ -287,151 +290,3 @@ Router.prototype.flush = function(routes) {
sails.emit('router:after');
};





//
// TODO:
// replace w/ req.js and res.js:
//

/**
* Ensure that request object has a minimum set of reasonable defaults.
* Used primarily as a test fixture.
*
* @api private
*/

function FakeSession() {}

function reasonableDefaultRequest(req) {
// if (req.params && req.method) {
// return req;
// }
// else {
return _.defaults(req || {}, {
params: {},
session: new FakeSession(),
query: {},
body: {},
param: function(paramName) {

var key, params = {};
for (key in (req.params || {}) ) {
params[key] = params[key] || req.params[key];
}
for (key in (req.query || {}) ) {
params[key] = params[key] || req.query[key];
}
for (key in (req.body || {}) ) {
params[key] = params[key] || req.body[key];
}

// Grab the value of the parameter from the appropriate place
// and return it
return params[paramName];
},
wantsJSON: true,
method: 'GET'
});
// }
}


/**
* Ensure that response object has a minimum set of reasonable defaults
* Used primarily as a test fixture.
*
* @api private
*/

function reasonableDefaultResponse(req, res) {
if (typeof res !== 'object') {
res = new Writable();
}

res.status = res.status || function status_shim (statusCode) {
res.statusCode = statusCode;
};

res.send = res.send || function send_shim () {
var args = normalizeResArgs(arguments);

if (!res.end || !res.write) {
return res._cb();
}
else {
res.statusCode = args.statusCode || res.statusCode || 200;

if (args.other) {
res.write(args.other);
}
res.end();
}
};

res.json = res.json || function json_shim () {
var args = normalizeResArgs(arguments);

try {
var json = JSON.stringify(args.other);
return res.send(json, args.statusCode || res.statusCode || 200);
}
catch(e) {
var failedStringify = new Error(
'Failed to stringify specified JSON response body :: ' + util.inspect(args.other) +
'\nError:\n' + util.inspect(e)
);
return res.send(failedStringify.stack, 500);
}
};

res.render = res.render || function render_shim (relativeViewPath, locals, cb) {
if (_.isFunction(arguments[1])) {
cb = arguments[1];
locals = {};
}
// console.log('\n\n\nRENDER\n\n', locals);//_.defaults(locals || {}, res.locals));
if (!req._sails.renderView) return res.send('Cannot call res.render() - `views` hook is not enabled', 500);
return res.send('Not implemented in core yet');
// return sails.renderView(relativeViewPath, _.defaults(locals || {}, res.locals), cb);
};


return res;


/**
* As long as one of them is a number (i.e. a status code),
* allows a 2-nary method to be called with flip-flopped arguments:
* method( [statusCode|other], [statusCode|other] )
*
* This avoids confusing errors & provides Express 2.x backwards compat.
*
* E.g. usage in res.send():
* var args = normalizeResArgs.apply(this, arguments),
* body = args.other,
* statusCode = args.statusCode;
*
* @api private
*/
function normalizeResArgs( args ) {

// Traditional usage:
// `method( other [,statusCode] )`
var isNumeric = function (x) {
return (+x === x);
};
if (isNumeric(args[0])) {
return {
statusCode: args[0],
other: args[1]
};
}
else return {
statusCode: args[1],
other: args[0]
};
}
}
188 changes: 145 additions & 43 deletions lib/router/req.js
Original file line number Diff line number Diff line change
@@ -1,69 +1,115 @@
/**
* Module dependencies
*/
var Request = require('express/lib/request')
, express = require('express');
var _ = require('lodash');
var MockReq = require('mock-req');

// var ExpressRequest = require('express/lib/request')
// , express = require('express');


/**
* Build generic Sails request object (i.e. `req`).
* Factory which builds generic Sails request object (i.e. `req`).
*
* This generic implementation of `req` forms the basis for
* Sails' transport-agnostic support of Connect/Express
* middleware. Used by hooks (i.e. sockets) but also for
* tests-- both at the app-level and in Sails core.
*
* @type {Request} simulated HTTP request object
* @return {Request} simulated HTTP request object
*/

module.exports = (function mock_req (){

var req = Request;

// Examine something like [shot](https://github.com/spumko/shot/)
// for the streaming methods.

//
// Express methods/properties
//


// Create a stub express 'app' object.
//
// We need to pass it in as `req.app` for Express'
// default `req` implementation to work.
//
// Just like in Express (at least as of 3.4.x), `req.app.settings`
// changed during a request will persist only for the remainder of that request.
req.app = express();


// Reasonable defaults
req.params = req.params || [],
req.query = req.query || {},
req.body = req.body || {},
req.method = 'GET',
req.headers = {
host: 'pretend.com'
};
module.exports = function buildRequest (_req) {

var req;
if (typeof _req === 'object' && _req.method && _req.url && _req.headers) {
req = _req;
}
else {
req = new MockReq({
method: _req.method,
headers: _req.headers,
url: _req.url
});
}

function FakeSession() {}

return _.defaults(req || {}, {
params: {},
session: new FakeSession(),
query: {},
body: {},
param: function(paramName) {

var key, params = {};
for (key in (req.params || {}) ) {
params[key] = params[key] || req.params[key];
}
for (key in (req.query || {}) ) {
params[key] = params[key] || req.query[key];
}
for (key in (req.body || {}) ) {
params[key] = params[key] || req.body[key];
}

// Grab the value of the parameter from the appropriate place
// and return it
return params[paramName];
},
wantsJSON: true,
method: 'GET'
});
};

// module.exports = (function mock_req (){

// var req = Request;

// // Examine something like [shot](https://github.com/spumko/shot/)
// // for the streaming methods.

// //
// // Express methods/properties
// //


// // Create a stub express 'app' object.
// //
// // We need to pass it in as `req.app` for Express'
// // default `req` implementation to work.
// //
// // Just like in Express (at least as of 3.4.x), `req.app.settings`
// // changed during a request will persist only for the remainder of that request.
// req.app = express();


// // Reasonable defaults
// req.params = req.params || [],
// req.query = req.query || {},
// req.body = req.body || {},
// req.method = 'GET',
// req.headers = {
// host: 'pretend.com'
// };




//
// Sails extensions
//
// //
// // Sails extensions
// //

req.transport = 'mock';
// req.transport = 'mock';

// TODO: get the request (from the `request` hook)
// // TODO: get the request (from the `request` hook)


// require-cache will automatically cache this mocked request object
// to avoid running this block of code more than once.
return req;
// // require-cache will automatically cache this mocked request object
// // to avoid running this block of code more than once.
// return req;

})();
// })();



Expand Down Expand Up @@ -168,3 +214,59 @@ module.exports = (function mock_req (){
// other: args[1]
// };
// }










// //
// // TODO:
// // replace w/ req.js and res.js:
// //

/**
* Ensure that request object has a minimum set of reasonable defaults.
* Used primarily as a test fixture.
*
* @api private
*/

// function FakeSession() {}

// function reasonableDefaultRequest(req) {
// // if (req.params && req.method) {
// // return req;
// // }
// // else {
// return _.defaults(req || {}, {
// params: {},
// session: new FakeSession(),
// query: {},
// body: {},
// param: function(paramName) {

// var key, params = {};
// for (key in (req.params || {}) ) {
// params[key] = params[key] || req.params[key];
// }
// for (key in (req.query || {}) ) {
// params[key] = params[key] || req.query[key];
// }
// for (key in (req.body || {}) ) {
// params[key] = params[key] || req.body[key];
// }

// // Grab the value of the parameter from the appropriate place
// // and return it
// return params[paramName];
// },
// wantsJSON: true,
// method: 'GET'
// });
// // }
// }
Loading

0 comments on commit 952c380

Please sign in to comment.