UNPKG

opinion

Version:

this is my opinion on koa and stuff

1,180 lines (816 loc) 23.5 kB
# koa-compose [![Build Status](https://travis-ci.org/koajs/compose.png)](https://travis-ci.org/koajs/compose) Compose middleware. ## API ### compose([a, b, c, ...]) Compose the given middleware and return middleware. ## License MIT # Koa Compress [![Build Status](https://travis-ci.org/koajs/compress.png)](https://travis-ci.org/koajs/compress) Compress middleware for Koa ## Example ```js var compress = require('koa-compress') var koa = require('koa') var app = koa() app.use(compress({ filter: function (content_type) { return /text/i.test(content_type) }, threshold: 2048, flush: require('zlib').Z_SYNC_FLUSH })) ``` ## Options The options are passed to `zlib`: http://nodejs.org/api/zlib.html#zlib_options ### filter An optional function that checks the response content type to decide whether to compress. By default, it uses [compressible](https://github.com/expressjs/compressible). ### threshold Minimum response size in bytes to compress. Default `1024` bytes or `1kb`. ## Manually turning compression on and off You can always enable compression by setting `this.compress = true`. You can always disable compression by setting `this.compress = false`. This bypasses the filter check. ```js app.use(function (next) { return function *() { this.compress = true this.body = fs.createReadStream(file) } }) ``` ## License The MIT License (MIT) Copyright (c) 2013 Jonathan Ong me@jongleberry.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. # koa-conditional-get [![Build Status](https://travis-ci.org/koajs/conditional-get.png)](https://travis-ci.org/koajs/conditional-get) Conditional GET support for koa. ## Installation ```js $ npm install koa-conditional-get ``` ## Example ```js var conditional = require('koa-conditional-get'); var etag = require('koa-etag'); var koa = require('koa'); var app = koa(); // use it upstream from etag so // that they are present app.use(conditional()); // add etags app.use(etag()); // respond app.use(function *(next){ yield next; this.body = { name: 'tobi', species: 'ferret', age: 2 }; }) app.listen(3000); console.log('listening on port 3000'); ``` ## License MIT # Koa CSRF [![Build Status](https://travis-ci.org/koajs/csrf.svg)](https://travis-ci.org/koajs/csrf) CSRF tokens for koa. ## Install ``` npm install koa-csrf ``` ## API To install, do: ```js require('koa-csrf')(app, options) ``` ### Options All options are passed to [csrf-tokens](https://github.com/expressjs/csrf-tokens). ### this.csrf Lazily creates a CSRF token. CSRF tokens change on every request. ```js app.use(function* () { this.render({ csrf: this.csrf }) }) ``` ### this.assertCSRF([body]) Check the CSRF token of a request with an optional body. Will throw if the CSRF token does not exist or is not valid. ```js app.use(function* () { var body = yield parse(this) // co-body or something try { this.assertCSRF(body) } catch (err) { this.status = 403 this.body = { message: 'This CSRF token is invalid!' } return } }) ``` ### Middleware koa-csrf also provide a koa middleware, it is similar to `connect-csrf`. in most situation, you only need: ```js var koa = require('koa') var csrf = require('koa-csrf') var session = require('koa-session') var app = koa() app.keys = ['session secret'] app.use(session()) csrf(app) app.use(csrf.middleware) app.use(function* () { if (this.method === 'GET') { this.body = this.csrf } else if (this.method === 'POST') { this.status = 204 } }) ``` # koa-etag ETag support for Koa responses. ## Installation ```js $ npm install koa-etag ``` ## Example ```js var etag = require('koa-etag'); var koa = require('koa'); var app = koa(); app.use(etag()); app.use(function(next){ return function *(){ yield next; this.body = 'Hello World'; } }) app.listen(3000); console.log('listening on port 3000'); ``` ## Options ### calculate By default, `etag` uses `crc32` to calculate bodies. If you want to use a custom function, set `options.calculate`. Custom etag calculation functions should accept both strings and buffers. For example, to use hex-encoded `sha256` sums: ```js var crypto = require('crypto'); app.use(etag({ calculate: function (body) { return crypto.createHash('sha256') .update(body) .digest('hex'); } })); ``` ## License MIT # koa-favicon [![Build Status](https://travis-ci.org/koajs/favicon.svg)](https://travis-ci.org/koajs/favicon) Koa middleware for serving a favicon. Based on [serve-favicon](https://github.com/expressjs/serve-favicon). ## Installation ```js $ npm install koa-favicon ``` ## Example ```js var koa = require('koa'); var favicon = require('koa-favicon'); var app = koa(); app.use(favicon(__dirname + '/public/favicon.ico')); ``` ## API ### favicon(path, [options]) Returns a middleware serving the favicon found on the given `path`. #### options - `maxAge` cache-control max-age directive in ms, defaulting to 1 day. ## License MIT # Koa Is JSON Check if a body is JSON # koa-logger Development style logger middleware for koa. ``` <-- GET / --> GET / 200 835ms 746b <-- GET / --> GET / 200 960ms 1.9kb <-- GET /users --> GET /users 200 357ms 922b <-- GET /users?page=2 --> GET /users?page=2 200 466ms 4.66kb ``` ## Installation ```js $ npm install koa-logger ``` ## Example ```js var logger = require('koa-logger') var koa = require('koa') var app = koa() app.use(logger()) ``` ## Notes Recommended that you `.use()` this middleware near the top to "wrap" all subsequent middleware. ## License MIT # koa-mount Mount other Koa applications as middleware. The `path` passed to `mount()` is stripped from the URL temporarily until the stack unwinds. This is useful for creating entire apps or middleware that will function correctly regardless of which path segment(s) they should operate on. ## Installation ```js $ npm install koa-mount ``` ## Examples View the [./examples](examples) directory for working examples. ### Mounting Applications Entire applications mounted at specific paths. For example you could mount a blog application at "/blog", with a router that matches paths such as "GET /", "GET /posts", and will behave properly for "GET /blog/posts" etc when mounted. ```js var mount = require('koa-mount'); var koa = require('koa'); // hello var a = koa(); a.use(function *(next){ yield next; this.body = 'Hello'; }); // world var b = koa(); b.use(function *(next){ yield next; this.body = 'World'; }); // app var app = koa(); app.use(mount('/hello', a)); app.use(mount('/world', b)); app.listen(3000); console.log('listening on port 3000'); ``` Try the following requests: ``` $ GET / Not Found $ GET /hello Hello $ GET /world World ``` ### Mounting Middleware Mount middleware at specific paths, allowing them to operate independently of the prefix, as they're not aware of it. ```js var mount = require('koa-mount'); var koa = require('koa'); function *hello(next){ yield next; this.body = 'Hello'; } function *world(next){ yield next; this.body = 'World'; } var app = koa(); app.use(mount('/hello', hello)); app.use(mount('/world', world)); app.listen(3000); console.log('listening on port 3000'); ``` ### Optional Paths The path argument is optional, defaulting to "/": ```js app.use(mount(a)); app.use(mount(b)); ``` ## Debugging Use the __DEBUG__ environement variable to whitelist koa-mount debug output: ``` $ DEBUG=koa-mount node myapp.js & $ GET /foo/bar/baz koa-mount enter /foo/bar/baz -> /bar/baz +2s koa-mount enter /bar/baz -> /baz +0ms koa-mount enter /baz -> / +0ms koa-mount leave /baz -> / +1ms koa-mount leave /bar/baz -> /baz +0ms koa-mount leave /foo/bar/baz -> /bar/baz +0ms ``` ## License MIT # koa-ratelimit Rate limiter middleware for koa. ## Installation ```js $ npm install koa-ratelimit ``` ## Example ```js var ratelimit = require('koa-ratelimit'); var redis = require('redis'); var koa = require('koa'); var app = koa(); // apply rate limit app.use(ratelimit({ db: redis.createClient(), duration: 60000, max: 100 })); // response middleware app.use(function *(){ this.body = 'Stuff!'; }); app.listen(3000); console.log('listening on port 3000'); ``` ## Options - `db` redis connection instance - `max` max requests within `duration` [2500] - `duration` of limit in milliseconds [3600000] ## Responses Example 200 with header fields: ``` HTTP/1.1 200 OK X-Powered-By: koa X-RateLimit-Limit: 100 X-RateLimit-Remaining: 99 X-RateLimit-Reset: 1384377793 Content-Type: text/plain; charset=utf-8 Content-Length: 6 Date: Wed, 13 Nov 2013 21:22:13 GMT Connection: keep-alive Stuff! ``` Example 429 response: ``` HTTP/1.1 429 Too Many Requests X-Powered-By: koa X-RateLimit-Limit: 100 X-RateLimit-Remaining: 0 X-RateLimit-Reset: 1384377716 Content-Type: text/plain; charset=utf-8 Content-Length: 39 Retry-After: 7 Date: Wed, 13 Nov 2013 21:21:48 GMT Connection: keep-alive Rate limit exceeded, retry in 8 seconds ``` ## License MIT # koa-response-time X-Response-Time middleware for koa. ## Installation ```js $ npm install koa-response-time ``` ## Note Best to `.use()` at the _top_ before any other middleware, to wrap all subsequent middleware. ## License MIT # koa-rewrite URL rewrite middleware for koa. ## Installation ```js $ npm install koa-rewrite ``` ## Examples Rewrite using a regular expression, rewriting `/i123` to `/items/123`. ```js app.use(rewrite(/^\/i(\w+)/, '/items/$1')); ``` Rewrite using route parameters, references may be named or numeric. For example rewrite `/foo..bar` to `/commits/foo/to/bar`: ```js app.use(rewrite('/:src..:dst', '/commits/$1/to/$2')); app.use(rewrite('/:src..:dst', '/commits/:src/to/:dst')); ``` You may also use the wildcard `*` to soak up several segments, for example `/js/vendor/jquery.js` would become `/public/assets/js/vendor/jquery.js`: ```js app.use(rewrite('/js/*', '/public/assets/js/$1')); ``` ## Debugging Use the __DEBUG__ environment variable with "koa-rewrite": ``` koa-rewrite rewrite /i123 -> /items/123 +762ms koa-rewrite rewrite /i321 -> /items/321 +9s koa-rewrite rewrite /i123 -> /items/123 +5s ``` ## License MIT # Router middleware for [koa](https://github.com/koajs/koa) [![Build Status](https://secure.travis-ci.org/alexmingoia/koa-router.png)](http://travis-ci.org/alexmingoia/koa-router) [![Dependency Status](https://david-dm.org/alexmingoia/koa-router.png)](http://david-dm.org/alexmingoia/koa-router) [![NPM version](https://badge.fury.io/js/koa-router.png)](http://badge.fury.io/js/koa-router) * Express-style routing using `app.get`, `app.put`, `app.post`, etc. * Named URL parameters and regexp captures. * String or regular expression route matching. * Named routes with URL generation. * Responds to `OPTIONS` requests with allowed methods. * Support for `405 Method Not Allowed` and `501 Not Implemented`. * Multiple route middleware. * Multiple routers. ## Install koa-router is available using [npm](https://npmjs.org): ``` npm install koa-router ``` ## Usage Require the router and mount the middleware: ```javascript var koa = require('koa') , router = require('koa-router') , app = koa(); app.use(router(app)); ``` After the router has been initialized you can register routes: ```javascript app.get('/users/:id', function *(next) { var user = yield User.findOne(this.params.id); this.body = user; }); ``` ### Multiple routers You can use multiple routers and sets of routes by omitting the `app` argument. For example, separate routers for two versions of an API: ```javascript var koa = require('koa'); , mount = require('koa-mount') , Router = require('koa-router'); var app = koa(); var APIv1 = new Router(); var APIv2 = new Router(); APIv1.get('/sign-in', function *() { // ... }); APIv2.get('/sign-in', function *() { // ... }); app .use(mount('/v1', APIv1.middleware())) .use(mount('/v2', APIv2.middleware())); ``` ### Chaining The http methods (get, post, etc) return their `Router` instance, so routes can be chained as you're used to with express: ```js var api = new Router(); api .get('/foo', showFoo) .get('/bar', showBar) .post('/foo', createFoo); ``` ## API ### Migrating from 2.x to 3.x Resource routing was separated into the [koa-resource-router](https://github.com/alexmingoia/koa-resource-router) module. ### Router#verb([name, ]path, middleware[, middleware...]) Match URL patterns to callback functions or controller actions using `router.verb()`, where **verb** is one of the HTTP verbs such as `router.get()` or `router.post()`. ```javascript app.get('/', function *(next) { this.body = 'Hello World!'; }); app.post('/users', function *(next) { // ... }); app.put('/users/:id', function *(next) { // ... }); app.del('/users/:id', function *(next) { // ... }); ``` Route paths will be translated to regular expressions used to match requests. Query strings will not be considered when matching requests. #### Named routes Routes can optionally have names. This allows generation of URLs and easy renaming of URLs during development. ```javascript app.get('user', '/users/:id', function *(next) { // ... }); app.url('user', 3); // => "/users/3" ``` #### Multiple middleware Multiple middleware may be given and are composed using [koa-compose](https://github.com/koajs/koa-compose): ```javascript app.get( '/users/:id', function *(next) { this.user = yield User.findOne(this.params.id); yield next; }, function *(next) { console.log(this.user); // => { id: 17, name: "Alex" } } ); ``` #### URL parameters Named route parameters are captured and added to `ctx.params`. Capture groups from regular expression routes are also added to `ctx.params`, which is an array. ##### Named parameters ```javascript app.get('/:category/:title', function *(next) { console.log(this.params); // => [ category: 'programming', title: 'how-to-node' ] }); ``` ##### Regular expression captures ```javascript app.get(/^\/([^\/]+)\/([^\/]+)\/?$/, function *(next) { console.log(this.params); // => [ 'programming', 'how-to-node' ] }); ``` #### Regular expressions Control route matching exactly by specifying a regular expression instead of a path string when creating the route. For example, it might be useful to match date formats for a blog, such as `/blog/2013-09-04`: ```javascript app.get(/^\/blog\/\d{4}-\d{2}-\d{2}\/?$/i, function *(next) { // ... }); ``` #### Multiple methods Create routes with multiple HTTP methods using `router.register()`: ```javascript app.register('/', ['get', 'post'], function *(next) { // ... }); ``` Create route for all methods using `router.all()`: ```javascript app.all('/', function *(next) { // ... }); ``` ### Router#redirect(source, destination, [code]) Redirect `source` to `destination` URL with optional 30x status `code`. Both `source` and `destination` can be route names. ```javascript app.redirect('/login', 'sign-in'); ``` This is equivalent to: ```javascript app.all('/login', function *() { this.redirect('/sign-in'); this.status = 301; }); ``` ### Router#route(name) Lookup route with given `name`. Returns the route or `false`. ### Router#url(name, params) Generate URL for route. Takes either map of named `params` or series of arguments (for regular expression routes). Returns `Error` if no route is found with given `name`. ```javascript app.get('user', '/users/:id', function *(next) { // ... }); app.url('user', 3); // => "/users/3" app.url('user', { id: 3 }); // => "/users/3" ``` ## Tests Tests use [mocha](https://github.com/visionmedia/mocha) and can be run with [npm](https://npmjs.org): ``` npm test ``` ## MIT Licensed # koa-send [![Build Status](https://travis-ci.org/koajs/send.png)](https://travis-ci.org/koajs/send) Static file serving middleware. ## Installation ```js $ npm install koa-send ``` ## Options - `maxage` Browser cache max-age in milliseconds. defaults to 0 - `hidden` Allow transfer of hidden files. defaults to false - `root` Root directory to restrict file access ## Root path Note that when `root` is _not_ used you __MUST__ provide an _absolute_ path, and this path must not contain "..", protecting developers from concatenating user input. If you plan on serving files based on user input supply a `root` directory from which to serve from. For example to serve files from `./public`: ```js app.use(function *(){ yield send(this, this.path, { root: __dirname + '/public' }); }) ``` To serve developer specified files: ```js app.use(function *(){ yield send(this, 'path/to/my.js'); }) ``` ## Example ```js var send = require('koa-send'); var koa = require('koa'); var app = koa(); // $ GET /package.json // $ GET / app.use(function *(){ if ('/' == this.path) return this.body = 'Try GET /package.json'; yield send(this, __dirname + '/package.json'); }) app.listen(3000); console.log('listening on port 3000'); ``` ## License MIT # koa-session Simple cookie-based session middleware for Koa. ## Installation ```js $ npm install koa-session ``` ## Example View counter example: ```js var session = require('koa-session'); var koa = require('koa'); var app = koa(); app.keys = ['some secret hurr']; app.use(session()); app.use(function *(){ var n = this.session.views || 0; this.session.views = ++n; this.body = n + ' views'; }) app.listen(3000); console.log('listening on port 3000'); ``` ## Semantics This module provides "guest" sessions, meaning any visitor will have a session, authenticated or not. If a session is _new_ a Set-Cookie will be produced regardless of populating the session. ## API ### Options The cookie name is controlled by the `key` option, which defaults to "koa:sess". All other options are passed to `ctx.cookie.get()` and `ctx.cookie.set()` allowing you to control security, domain, path, and signing among other settings. ### Session#isNew Returns __true__ if the session is new. ### Destroying a session To destroy a session simply set it to `null`: ```js this.session = null; ``` ## License MIT # Koa SPDY Push SPDY Push helper for Koa. Automatically handles `close` events and errors to avoid leaks. ## API ### push(this, options) ```js var push = require('koa-spdy-push')({ threshold: 1kb }) app.use(function* () { is (!this.res.isSpdy) return push(this, { path: '/image.png', filename: 'image.png', headers: { 'content-type': 'image/png' } }) }) ``` Pushes a file in a separate coroutine. Options: - `path` <required> - The url of the stream - `headers` <required> - Headers of the stream - `priority: 7` - SPDY Push stream priority, defaults to lowest - `body` - a body of the stream, either a `String`, `Buffer`, or `Stream.Readable` - `filename` - a filename of a body. Use this to push bodies without creating a stream first (otherwise you'll create file descriptor leaks) Either `body` or `filename` is required. Don't set the following headers. These headers will be automatically set: - `content-encoding` - `content-length` # koa-static [![Build Status](https://travis-ci.org/koajs/static.png)](https://travis-ci.org/koajs/static) Static file serving middleware. ## Installation ```bash $ npm install koa-static ``` ## Options - `maxage` Browser cache max-age in milliseconds. defaults to 0 - `hidden` Allow transfer of hidden files. defaults to false - `index` Default file name, defaults to 'index.html' - `defer` If true, serves after `yield next`, allowing any downstream middleware to respond first. ## Example ```js var serve = require('koa-static'); var koa = require('koa'); var app = koa(); // $ GET /package.json app.use(serve('.')); // $ GET /hello.txt app.use(serve('test/fixtures')); // or use absolute paths app.use(serve(__dirname + '/test/fixtures')); app.listen(3000); console.log('listening on port 3000'); ``` ## License MIT <img src="https://dl.dropboxusercontent.com/u/6396913/koa/logo.png" alt="koa middleware framework for nodejs" width="255px" /> [![Build Status](https://travis-ci.org/koajs/koa.svg)](https://travis-ci.org/koajs/koa) Expressive middleware for node.js using generators via [co](https://github.com/visionmedia/co) to make web applications and APIs more enjoyable to write. Koa's middleware flow in a stack-like manner allowing you to perform actions downstream, then filter and manipulate the response upstream. Koa's use of generators also greatly increases the readability and robustness of your application. Only methods that are common to nearly all HTTP servers are integrated directly into Koa's small ~550 SLOC codebase. This includes things like content-negotiation, normalization of node inconsistencies, redirection, and a few others. No middleware are bundled with koa. If you prefer to only define a single dependency for common middleware, much like Connect, you may use [koa-common](https://github.com/koajs/common). ## Installation ``` $ npm install koa ``` To use Koa you must be running __node 0.11.9__ or higher for generator support, and must run node(1) with the `--harmony` flag. If you don't like typing this, add an alias to your shell profile: ``` alias node='node --harmony' ``` ## Community - [API](docs/api/index.md) documentation - [Examples](https://github.com/koajs/examples) - [Middleware](https://github.com/koajs/koa/wiki) list - [Wiki](https://github.com/koajs/koa/wiki) - [G+ Community](https://plus.google.com/communities/101845768320796750641) - [Reddit Community](http://reddit.com/r/koajs) - [Mailing list](https://groups.google.com/forum/#!forum/koajs) - [Guide](docs/guide.md) - [FAQ](docs/faq.md) - __#koajs__ on freenode ## Example ```js var koa = require('koa'); var app = koa(); // logger app.use(function *(next){ var start = new Date; yield next; var ms = new Date - start; console.log('%s %s - %s', this.method, this.url, ms); }); // response app.use(function *(){ this.body = 'Hello World'; }); app.listen(3000); ``` ## Running tests ``` $ make test ``` ## Authors - [TJ Holowaychuk](https://github.com/visionmedia) - [Jonathan Ong](https://github.com/jonathanong) - [Julian Gruber](https://github.com/juliangruber) # License MIT