Lint JavaScript in Markdown

This commit is contained in:
Robin Pokorný 2016-03-15 16:35:52 +01:00
parent 39f058e11c
commit 340dd4f1a3
7 changed files with 56 additions and 62 deletions

View file

@ -50,32 +50,29 @@ Koa is an middleware framework, it can take 3 different kind function as middlew
Here we write an logger middleware with different function. Here we write an logger middleware with different function.
### Common function ### Common function
```js
```js
// Middleware normally take two parameters (ctx, next), ctx is the context for one request, // Middleware normally take two parameters (ctx, next), ctx is the context for one request,
// next is an function that is invoked to execute the downstream middleware. It returns a Promise with a then function for running code after completion. // next is an function that is invoked to execute the downstream middleware. It returns a Promise with a then function for running code after completion.
app.use((ctx, next) => { app.use((ctx, next) => {
const start = new Date; const start = new Date();
return next().then(() => { return next().then(() => {
const ms = new Date - start; const ms = new Date() - start;
console.log(`${ctx.method} ${ctx.url} - ${ms}ms`); console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
}); });
}); });
``` ```
### ___async___ functions (Babel required) ### ___async___ functions (Babel required)
```js ```js
app.use(async (ctx, next) => { app.use(async (ctx, next) => {
const start = new Date; const start = new Date();
await next(); await next();
const ms = new Date - start; const ms = new Date() - start;
console.log(`${ctx.method} ${ctx.url} - ${ms}ms`); console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
}); });
``` ```
### GeneratorFunction ### GeneratorFunction
@ -83,14 +80,12 @@ app.use(async (ctx, next) => {
To use generator functions, you must use a wrapper such as [co](https://github.com/tj/co) that is no longer supplied with Koa. To use generator functions, you must use a wrapper such as [co](https://github.com/tj/co) that is no longer supplied with Koa.
```js ```js
app.use(co.wrap(function *(ctx, next) {
app.use(co.wrap(function *(ctx, next){ const start = new Date();
const start = new Date;
yield next(); yield next();
const ms = new Date - start; const ms = new Date() - start;
console.log(`${ctx.method} ${ctx.url} - ${ms}ms`); console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
})); }));
``` ```
### Old signature middleware (v1.x) ### Old signature middleware (v1.x)
@ -98,15 +93,14 @@ app.use(co.wrap(function *(ctx, next){
If you want to use old signature or be compatible with old middleware, you must use [koa-convert](https://github.com/gyson/koa-convert) to convert legacy generator middleware to promise middleware. If you want to use old signature or be compatible with old middleware, you must use [koa-convert](https://github.com/gyson/koa-convert) to convert legacy generator middleware to promise middleware.
```js ```js
const convert = require('koa-convert') const convert = require('koa-convert');
app.use(convert(function *(next){ app.use(convert(function *(next) {
const start = new Date; const start = new Date();
yield next; yield next;
const ms = new Date - start; const ms = new Date() - start;
console.log(`${this.method} ${this.url} - ${ms}ms`); console.log(`${this.method} ${this.url} - ${ms}ms`);
})); }));
``` ```
@ -122,7 +116,7 @@ $ npm install babel-preset-stage-3 --save
```js ```js
// set babel in entry file // set babel in entry file
require("babel-core/register")({ require('babel-core/register')({
presets: ['es2015-node5', 'stage-3'] presets: ['es2015-node5', 'stage-3']
}); });
``` ```

View file

@ -12,7 +12,7 @@
snippet: snippet:
```js ```js
app.use(function *(){ app.use(function * () {
this; // is the Context this; // is the Context
this.request; // is a koa Request this.request; // is a koa Request
this.response; // is a koa Response this.response; // is a koa Response

View file

@ -80,25 +80,25 @@ const app = new Koa();
// x-response-time // x-response-time
app.use(async function (ctx, next){ app.use(async function (ctx, next) {
const start = new Date; const start = new Date();
await next(); await next();
const ms = new Date - start; const ms = new Date() - start;
ctx.set('X-Response-Time', `${ms}ms`); ctx.set('X-Response-Time', `${ms}ms`);
}); });
// logger // logger
app.use(async function (ctx, next){ app.use(async function (ctx, next) {
const start = new Date; const start = new Date();
await next(); await next();
const ms = new Date - start; const ms = new Date() - start;
console.log(`${ctx.method} ${ctx.url} - ${ms}`); console.log(`${ctx.method} ${ctx.url} - ${ms}`);
}); });
// response // response
app.use((ctx) => { app.use(ctx => {
ctx.body = 'Hello World'; ctx.body = 'Hello World';
}); });
@ -198,17 +198,17 @@ app.context.db = db();
To perform custom error-handling logic such as centralized logging you can add an "error" event listener: To perform custom error-handling logic such as centralized logging you can add an "error" event listener:
```js ```js
app.on('error', function(err){ app.on('error', err =>
log.error('server error', err); log.error('server error', err)
}); );
``` ```
If an error is in the req/res cycle and it is _not_ possible to respond to the client, the `Context` instance is also passed: If an error is in the req/res cycle and it is _not_ possible to respond to the client, the `Context` instance is also passed:
```js ```js
app.on('error', function(err, ctx){ app.on('error', (err, ctx) =>
log.error('server error', err, ctx); log.error('server error', err, ctx)
}); );
``` ```
When an error occurs _and_ it is still possible to respond to the client, aka no data has been written to the socket, Koa will respond When an error occurs _and_ it is still possible to respond to the client, aka no data has been written to the socket, Koa will respond

View file

@ -96,7 +96,7 @@ this.request.href
Get request `Content-Type` void of parameters such as "charset". Get request `Content-Type` void of parameters such as "charset".
```js ```js
const ct = this.request.type; const ct = this.request.type
// => "image/png" // => "image/png"
``` ```
@ -130,7 +130,7 @@ this.request.charset
setter does _not_ support nested objects. setter does _not_ support nested objects.
```js ```js
this.query = { next: '/login' }; this.query = { next: '/login' }
``` ```
### request.fresh ### request.fresh

View file

@ -146,11 +146,11 @@ If `response.status` has not been set, Koa will automatically set the status to
Here's an example of stream error handling without automatically destroying the stream: Here's an example of stream error handling without automatically destroying the stream:
```js ```js
const PassThrough = require('stream').PassThrough const PassThrough = require('stream').PassThrough;
app.use(function * (next) { app.use(function * (next) {
this.body = someHTTPStream.on('error', this.onerror).pipe(PassThrough()) this.body = someHTTPStream.on('error', this.onerror).pipe(PassThrough());
}) });
``` ```
#### Object #### Object
@ -233,12 +233,12 @@ this.type = 'png';
```js ```js
const minify = require('html-minifier'); const minify = require('html-minifier');
app.use(function *minifyHTML(next){ app.use(function * minifyHTML(next) {
yield next; yield next;
if (!this.response.is('html')) return; if (!this.response.is('html')) return;
const body = this.body; let body = this.body;
if (!body || body.pipe) return; if (!body || body.pipe) return;
if (Buffer.isBuffer(body)) body = body.toString(); if (Buffer.isBuffer(body)) body = body.toString();

View file

@ -13,9 +13,9 @@
```js ```js
async function responseTime(ctx, next) { async function responseTime(ctx, next) {
const start = new Date; const start = new Date();
await next(); await next();
const ms = new Date - start; const ms = new Date() - start;
ctx.set('X-Response-Time', `${ms}ms`); ctx.set('X-Response-Time', `${ms}ms`);
} }
@ -52,7 +52,7 @@ to this behaviour.
For example this would be fine: For example this would be fine:
```js ```js
app.use(async function response(ctx, next){ app.use(async function response(ctx, next) {
if ('/' != this.url) return; if ('/' != this.url) return;
ctx.body = 'Hello World'; ctx.body = 'Hello World';
}); });
@ -79,7 +79,7 @@ app.use(async function response(ctx, next){
function logger(format) { function logger(format) {
format = format || ':method ":url"'; format = format || ':method ":url"';
return async function (ctx, next){ return async function (ctx, next) {
const str = format const str = format
.replace(':method', ctx.method) .replace(':method', ctx.method)
.replace(':url', ctx.url); .replace(':url', ctx.url);
@ -87,7 +87,7 @@ function logger(format) {
console.log(str); console.log(str);
await next(); await next();
} };
} }
app.use(logger()); app.use(logger());
@ -100,9 +100,9 @@ app.use(logger(':method :url'));
```js ```js
function logger(format) { function logger(format) {
return async function logger(ctx, next){ return async function logger(ctx, next) {
} };
} }
``` ```
@ -115,7 +115,7 @@ const compose = require('koa-compose');
async function random(ctx, next) { async function random(ctx, next) {
if ('/random' == this.path) { if ('/random' == this.path) {
ctx.body = Math.floor(Math.random()*10); ctx.body = Math.floor(Math.random() * 10);
} else { } else {
await next(); await next();
} }
@ -137,7 +137,7 @@ async function pi(ctx, next) {
} }
} }
const all = compose([random, backwards, pi]) const all = compose([random, backwards, pi]);
app.use(all); app.use(all);
``` ```
@ -152,20 +152,20 @@ app.use(all);
downstream "three" middleware a chance to manipulate the response. downstream "three" middleware a chance to manipulate the response.
```js ```js
app.use(async function (ctx, next){ app.use(async function (ctx, next) {
console.log('>> one'); console.log('>> one');
await next(); await next();
console.log('<< one'); console.log('<< one');
}); });
app.use(async function (ctx, next){ app.use(async function (ctx, next) {
console.log('>> two'); console.log('>> two');
ctx.body = 'two'; ctx.body = 'two';
await next(); await next();
console.log('<< two'); console.log('<< two');
}); });
app.use(async function (ctx, next){ app.use(async function (ctx, next) {
console.log('>> three'); console.log('>> three');
await next(); await next();
console.log('<< three'); console.log('<< three');
@ -176,19 +176,19 @@ app.use(async function (ctx, next){
with "two", however the third (and any other downstream middleware) will be ignored: with "two", however the third (and any other downstream middleware) will be ignored:
```js ```js
app.use(async function (ctx, next){ app.use(async function (ctx, next) {
console.log('>> one'); console.log('>> one');
await next(); await next();
console.log('<< one'); console.log('<< one');
}); });
app.use(async function (ctx, next){ app.use(async function (ctx, next) {
console.log('>> two'); console.log('>> two');
ctx.body = 'two'; ctx.body = 'two';
console.log('<< two'); console.log('<< two');
}); });
app.use(async function (ctx, next){ app.use(async function (ctx, next) {
console.log('>> three'); console.log('>> three');
await next(); await next();
console.log('<< three'); console.log('<< three');
@ -208,7 +208,7 @@ app.use(async function (ctx, next){
```js ```js
const fs = require('fs-promise'); const fs = require('fs-promise');
app.use(async function (ctx, next){ app.use(async function (ctx, next) {
const paths = await fs.readdir('docs'); const paths = await fs.readdir('docs');
const files = await Promise.all(paths.map(path => fs.readFile(`docs/${path}`, 'utf8'))); const files = await Promise.all(paths.map(path => fs.readFile(`docs/${path}`, 'utf8')));
@ -241,15 +241,15 @@ $ DEBUG=koa* node --harmony examples/simple
```js ```js
const path = require('path'); const path = require('path');
const static = require('koa-static'); const serve = require('koa-static');
const publicFiles = static(path.join(__dirname, 'public')); const publicFiles = serve(path.join(__dirname, 'public'));
publicFiles._name = 'static /public'; publicFiles._name = 'static /public';
app.use(publicFiles); app.use(publicFiles);
``` ```
Now, instead of just seeing "static" when debugging, you will see: Now, instead of just seeing "serve" when debugging, you will see:
``` ```
koa:application use static /public +0ms koa:application use static /public +0ms