spirit
Version:
extensible web library for building applications & frameworks
90 lines (81 loc) • 2.61 kB
JavaScript
;
var url = require("url");
var urlquery = function urlquery(req, request) {
if (!req.url) return;
var result = url.parse(req.url, true);
request.url = result.pathname;
request.pathname = result.pathname; // alias to url for those who are use to node.js url api
request.query = result.query;
};
var hostport = function hostport(req, request) {
if (req.headers && req.headers.host) {
var host = req.headers.host;
// ipv6
var offset = 0;
if (host[0] === "[") {
offset = host.indexOf("]") + 1;
}
var index = host.indexOf(":", offset);
request.host = host;
if (index !== -1) {
request.host = host.substring(0, index);
request.port = parseInt(host.substring(index + 1, host.length));
}
}
};
var protocol = function protocol(req, request) {
request.protocol = "http";
if (req.connection && req.connection.encrypted) {
request.protocol = "https";
}
};
/**
* create a request map
*
* A request map most likely contains the following:
* - port {number} the port the request was made on
* - host {string} either a hostname or ip of the server
* - ip {string} the requesting client's ip
* - url {string} the request URI (excluding query string)
* - path {string} the request URI (including query string)
* - method {string} the request method
* - protocol {string} transport protocol, either "http" or "https"
* - scheme {string} the protocol version ex: "1.1"
* - headers {object} the request headers (as node delivers it)
* - query {object} query string of request URI parsed as object (defaults to {})
*
* - req {function} returns the node IncomingRequest object
*
*** TODO, add a body if possible
* - body {Stream} raw unparsed request body, this is just `req`, as it is the easiest way to pass the 'raw' body, which would be a node stream
* NOTE: this may change, treat it as a stream only
*
* @param {http.Request} req - a node http IncomingRequest object
* @return {request-map}
*/
var create = function create(_req) {
var request = {
method: _req.method,
headers: _req.headers,
scheme: _req.httpVersion,
path: _req.url,
//body: req
req: function req() {
return _req;
}
};
if (_req.connection) {
request.ip = _req.connection.remoteAddress;
}
if (typeof request.method === "string") request.method = request.method.toUpperCase();
protocol(_req, request);
hostport(_req, request);
urlquery(_req, request);
return request;
};
module.exports = {
hostport: hostport,
protocol: protocol,
urlquery: urlquery,
create: create
};