Socket
Socket
Sign inDemoInstall

protein

Package Overview
Dependencies
0
Maintainers
1
Versions
13
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 0.4.1 to 0.5.0

example.js

118

index.js

@@ -41,99 +41,35 @@ var clone = function(from, to) {

};
var onerror = function(err, req, res) {
if (err) {
console.error(err.stack);
res.writeHead(500, {'Content-Type': 'text/plain'});
res.end(err.stack+'\n');
return;
}
res.writeHead(404);
res.end();
};
var protein = function() {
var stack = [];
module.exports = function() {
var onresponse = injector();
var onrequest = injector();
var onresponse = injector();
var shorthand = function(define) {
return function(name, fn) {
define(reduce[name.split('.')[0]], name.split('.').pop(), fn);
return reduce;
};
var mixin = function(request, response, next) {
request.response = response;
onrequest(request);
response.request = request;
onresponse(response);
if (!next) return;
response.next = request.next = next;
next();
};
var reduce = function(req, res, callback) {
var i = 0;
var url = req.url;
var loop = function(err) {
var next = stack[i++];
var route = next && next.route;
req.url = url;
if (!next) return (callback || onerror)(err, req, res);
if (route) {
if (url.substr(0, route.length) !== route) return loop(err);
req.url = url.substr(route.length) || '/';
if (req.url[0] === '?') req.url = '/'+req.url;
if (req.url[0] !== '/') return loop(err);
}
try {
if (err && next.length < 4) return loop(err);
if (next.length >= 4) return next(err, req, res, loop);
next(req, res, loop);
} catch (err) {
loop(err);
}
};
mixin.request = onrequest.proto;
mixin.response = onresponse.proto;
mixin.use = function(key, options, fn) {
if (typeof options === 'function') return mixin.use(key, {}, options);
// set the callback
req.next = res.next = loop;
key = key.replace('res.', 'response.').replace('req.', 'request.').split('.');
var owner = key[0] === 'response' ? onresponse : onrequest;
var method = key[1];
// set request prototype
req.response = res;
onrequest(req);
// set response prototype
res.request = req;
onresponse(res);
// bootstrap the loop
loop();
};
reduce.request = onrequest.proto;
reduce.response = onresponse.proto;
reduce.getter = shorthand(function(proto, name, fn) {
proto.__defineGetter__(name, fn);
});
reduce.setter = shorthand(function(proto, name, fn) {
proto.__defineSetter__(name, fn);
});
reduce.fn = shorthand(function(proto, name, fn) {
proto[name] = fn;
});
reduce.using = function(fn) {
return stack.indexOf(fn) > -1;
};
reduce.use = function(route, fn) {
if (!fn) {
fn = route;
route = null;
if (options.getter) {
owner.proto.__defineGetter__(method, fn);
} else if (options.setter) {
owner.proto.__defineSetter__(method, fn);
} else {
owner.proto[method] = fn;
}
if (!fn) return reduce;
if (Array.isArray(fn)) {
fn.forEach(reduce.use.bind(reduce, route));
return reduce;
}
if (typeof fn === 'function') {
fn.route = route && route.replace(/\/$/, ''); // FIXME: bug here if fn is reused :(
stack.push(fn);
}
clone(fn.request, reduce.request);
clone(fn.response, reduce.response);
return reduce;
return mixin;
};
return reduce;
};
module.exports = protein;
return mixin;
};
{
"name":"protein",
"version":"0.4.1",
"version":"0.5.0",
"repository": "git://github.com/mafintosh/protein",
"description":"Protein is connect compatible middleware with support for prototype methods, getters, and setters",
"keywords": ["web", "middleware", "connect", "prototype", "prototypical", "getters", "setters"],
"description":"Protein is http prototype mixins for Node.js",
"keywords": ["web", "middleware", "mixin", "connect", "prototype", "prototypical", "getters", "setters"],
"author": "Mathias Buus Madsen <mathiasbuus@gmail.com>"
}
# Protein
Protein is http middleware for Node with support for prototype methods, getters and setters. It's compatible with [Connect](https://github.com/senchalabs/connect).
Protein is http prototype mixins for Node.js

@@ -15,16 +15,16 @@ It's available through npm:

var fn = protein()
// Adds a query property to the request. Use request.query to access the parsed query
.getter('request.query', function() {
return this._query || (this._query = url.parse(request.url, true).query);
var mixin = protein()
.use('request.query', {getter:true}, function() {
return this._query || (this.query = url.parse(this.url, true).query);
})
// Adds an echo method to the response. Use response.echo() to return the query
.fn('response.echo', function() {
this.end(JSON.stringify(this.request.query));
})
.use(function(request, response) {
response.echo();
.use('response.echo', function(data) {
return this.end(JSON.stringify(data));
});
require('http').createServer(fn).listen(8080);
var listener = function(request, response) {
mixin(request, response);
response.echo(request.query);
};
require('http').createServer(listener).listen(8080);
```

@@ -59,10 +59,10 @@

But if we look closer at the above example we are actually parsing the query on every request even though we never use it.
But if we look closer at the above example we are actually parsing the query on every request even though we never use it.
Wouldn't it be nicer to just parse when we access it?
Using Protein we can just define a getter on the middleware prototype:
Using Protein we can just define a getter on the mixin prototype:
``` js
var fn = protein()
.getter('request.query', function() {
var mixin = protein()
.use('request.query', {getter:true}, function() {
return this._query || (this._query = url.parse(request.url, true).query);

@@ -73,19 +73,18 @@ })

Now when we access request.query the first time the query will be parsed and in all other cases no parsing happens.
Notice Protein is actually defining the getter on the middleware prototype for us so the is actually only defined once - *NOT* every request.
Now when we access request.query the first time the query will be parsed and in all other cases no parsing happens.
Notice Protein is actually defining the getter on the mixin prototype so it's actually only defined once - *NOT* every request.
Similary we could just define `echo` on the middleware prototype instead of defining it on every request:
Similary we could just define `echo` on the mixin prototype instead of defining it on every request:
``` js
var fn = protein()
.getter('request.query', function() {
var mixin = protein()
.use('request.query', {getter:true}, function() {
return this._query || (this._query = url.parse(request.url, true).query);
})
.fn('response.echo', function() {
.use('response.echo', function() {
this.end(JSON.stringify(request.query));
})
.use( ... )
```
Note that we are only expanding the middleware prototype and not the prototype from the `http` module so their should be zero side effects.
Note that we are only expanding the mixin prototype and not the prototype from the `http` module so there should be zero side effects.
The final program just looks like this:

@@ -97,64 +96,28 @@

var fn = protein()
.getter('request.query', function() {
return this._query || (this._query = url.parse(request.url, true).query);
var mixin = protein()
.use('request.query', {getter:true}, function() {
return this._query || (this.query = url.parse(this.url, true).query);
})
.fn('response.echo', function() {
this.end(JSON.stringify(request.query));
})
.use(function(request, response) {
// this method is the only one which is run on every request
response.end('hello world');
.use('response.echo', function(data) {
return this.end(JSON.stringify(data));
});
require('http').createServer(fn).listen(8080);
```
# Reusing middleware
If you want to create middleware that can be reused in other places and which expands the middleware prototype you can use the following format:
``` js
var random = function(request, response, next) {
request.random = Math.random();
next();
var listener = function(request, response) {
mixin(request, response);
response.echo('hello world');
};
random.response = {}; // the collection of middleware response prototype methods
random.response.random = function() {
this.end(''+this.request.random); // we can access the request from the response using this.request
};
protein().use(random).use(function(request, response) {
response.random(); // should return a random number
});
require('http').createServer(listener).listen(8080);
```
If we dont want to run a function on every request but instead want to just expand the prototypes we can just declare a map:
``` js
var random = {request: {}, response: {}};
random.request.__defineGetter__('random', function() {
return Math.random();
});
random.response.random = function() {
this.end(''+this.request.random);
};
protein().use(random).use(function(request, response) {
response.random(); // should return a random number
});
```
For more examples on how to create your own reusable middleware see the [examples](https://github.com/mafintosh/Protein/tree/master/examples).
# Connect compatibility
All Connect modules should be compatible with Protein. To make a Protein module compatible with Connect you need to wrap it:
Protein mixins are directly compatible with connect making then easy to use with your express application:
``` js
var connectable = protein().use(myProteinMiddleware);
var app = express();
connect.use(connectable);
var mixin = protein().use('response.echo', ...);
app.use(mixin);
```

@@ -167,7 +130,7 @@

> Copyright (c) 2012 Mathias Buus Madsen <mathiasbuus@gmail.com>
>
>
> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
>
>
> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
>
>
> THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

@@ -0,8 +1,13 @@

#!/usr/bin/env node
var fs = require('fs');
var path = require('path');
var exec = require('child_process').exec;
var TIMEOUT = 20000;
var tests = fs.readdirSync(__dirname).filter(function(file) {
return !fs.statSync(__dirname+'/'+file).isDirectory();
return !fs.statSync(path.join(__dirname,file)).isDirectory();
}).filter(function(file) {
return file !== 'index.js';
return /^test(-|_|\.).*\.js$/i.test(file);
});

@@ -16,8 +21,5 @@

if (!next) {
console.log('\033[32m[ok]\033[39m all ok');
return;
}
if (!next) return console.log('\033[32m[ok]\033[39m all ok');
exec('node '+__dirname+'/'+next, function(err) {
exec('node '+path.join(__dirname,next), {timeout:TIMEOUT}, function(err) {
cnt++;

@@ -28,8 +30,6 @@

console.error('\n '+(''+err.stack).split('\n').join('\n ')+'\n');
process.exit(1);
return;
} else {
console.log('\033[32m[ok]\033[39m '+cnt+'/'+all+' - '+next);
return process.exit(1);
}
console.log('\033[32m[ok]\033[39m '+cnt+'/'+all+' - '+next);
setTimeout(loop, 100);

@@ -36,0 +36,0 @@ });

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc