Skip to content

Commit

Permalink
lint
Browse files Browse the repository at this point in the history
  • Loading branch information
haoxin committed May 16, 2017
1 parent fb947af commit 28c4a0b
Show file tree
Hide file tree
Showing 6 changed files with 235 additions and 233 deletions.
4 changes: 4 additions & 0 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
---
extends: standard
env:
mocha: true
76 changes: 37 additions & 39 deletions example.js
Original file line number Diff line number Diff line change
@@ -1,76 +1,74 @@

const logger = require('./');
const Koa = require('koa');
const compress = require('koa-compress')();
const app = new Koa();
const logger = require('./')
const Koa = require('koa')
const compress = require('koa-compress')()
const app = new Koa()

// wrap subsequent middleware in a logger

app.use(logger());
app.use(logger())

// 204

app.use(function(ctx, next){
if ('/204' == ctx.path) ctx.status = 204;
else return next();
app.use(function (ctx, next) {
if (ctx.path === '/204') ctx.status = 204
else return next()
})

// 404

app.use(function(ctx, next){
if ('/404' == ctx.path) return;
return next();
app.use(function (ctx, next) {
if (ctx.path === '/404') return
return next()
})

// destroy

app.use(function(ctx, next){
if ('/close' == ctx.path) return ctx.req.destroy();
return next();
app.use(function (ctx, next) {
if (ctx.path === '/close') return ctx.req.destroy()
return next()
})

// compress the response 1/2 the time to calculate the stream length

app.use(function(ctx, next){
app.use(function (ctx, next) {
if (Math.random() > 0.5) {
return next();
return next()
} else {
return compress(ctx, next);
return compress(ctx, next)
}
})

// response middleware

app.use(function(ctx, next){
app.use(function (ctx, next) {
// yield control downstream
next().then(function() {
next().then(function () {
// sleep for 0-2s
return sleep(Math.random() * 2000 | 0);
}).then(function() {

return sleep(Math.random() * 2000 | 0)
}).then(function () {
// error
if (Math.random() > .75) {
const err = new Error('boom');
err.status = 500;
throw err;
if (Math.random() > 0.75) {
const err = new Error('boom')
err.status = 500
throw err
}

// random body
const body = Array(Math.random() * 5 * 1024 | 9).join('a');
ctx.status = 200;
ctx.body = body;

});
});
const body = Array(Math.random() * 5 * 1024 | 9).join('a')
ctx.status = 200
ctx.body = body
})
})

const port = process.env.PORT || 3000;
app.listen(port);
console.log('listening on port ' + port);
const port = process.env.PORT || 3000
app.listen(port)
console.log('listening on port ' + port)

// sleep helper

function sleep(ms) {
return new Promise(function(resolve){
setTimeout(resolve, ms);
});
function sleep (ms) {
return new Promise(function (resolve) {
setTimeout(resolve, ms)
})
}
105 changes: 49 additions & 56 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,18 @@
/**
* Module dependencies.
*/
'use strict';
'use strict'

const Counter = require('passthrough-counter');
const humanize = require('humanize-number');
const bytes = require('bytes');
const chalk = require('chalk');

/**
* TTY check for dev format.
*/

const isatty = process.stdout.isTTY;
const Counter = require('passthrough-counter')
const humanize = require('humanize-number')
const bytes = require('bytes')
const chalk = require('chalk')

/**
* Expose logger.
*/

module.exports = dev;
module.exports = dev

/**
* Color map.
Expand All @@ -31,100 +25,99 @@ const colorCodes = {
2: 'green',
1: 'green',
0: 'yellow'
};
}

/**
* Development logger.
*/

function dev(opts) {
return async function logger(ctx, next) {
function dev (opts) {
return async function logger (ctx, next) {
// request
const start = new Date;
console.log(' ' + chalk.gray('<--')
+ ' ' + chalk.bold('%s')
+ ' ' + chalk.gray('%s'),
const start = new Date()
console.log(' ' + chalk.gray('<--') +
' ' + chalk.bold('%s') +
' ' + chalk.gray('%s'),
ctx.method,
ctx.originalUrl);
ctx.originalUrl)

try {
await next()
} catch (err) {
// log uncaught downstream errors
log(ctx, start, null, err);
throw err;
log(ctx, start, null, err)
throw err
}

// calculate the length of a streaming response
// by intercepting the stream with a counter.
// only necessary if a content-length header is currently not set.
const length = ctx.response.length;
const body = ctx.body;
let counter;
if (null == length && body && body.readable) {
const length = ctx.response.length
const body = ctx.body
let counter
if (length == null && body && body.readable) {
ctx.body = body
.pipe(counter = Counter())
.on('error', ctx.onerror);
.on('error', ctx.onerror)
}

// log when the response is finished or closed,
// whichever happens first.
const res = ctx.res;
const res = ctx.res

const onfinish = done.bind(null, 'finish');
const onclose = done.bind(null, 'close');
const onfinish = done.bind(null, 'finish')
const onclose = done.bind(null, 'close')

res.once('finish', onfinish);
res.once('close', onclose);
res.once('finish', onfinish)
res.once('close', onclose)

function done(event){
res.removeListener('finish', onfinish);
res.removeListener('close', onclose);
log(ctx, start, counter ? counter.length : length, null, event);
function done (event) {
res.removeListener('finish', onfinish)

This comment has been minimized.

Copy link
@sergeyampo

sergeyampo May 7, 2020

What is a purpose of removing listeners? After the response has been sent, Context object will be destructed!

This comment has been minimized.

Copy link
@haoxins

haoxins May 7, 2020

Member

this commit just formatted the code style, can u open an issue for this?

res.removeListener('close', onclose)
log(ctx, start, counter ? counter.length : length, null, event)
}

}
}

/**
* Log helper.
*/

function log(ctx, start, len, err, event) {
function log (ctx, start, len, err, event) {
// get the status code of the response
const status = err
? (err.status || 500)
: (ctx.status || 404);
: (ctx.status || 404)

// set the color of the status code;
const s = status / 100 | 0;
const color = colorCodes[s];
const s = status / 100 | 0
const color = colorCodes[s]

// get the human readable response length
let length;
let length
if (~[204, 205, 304].indexOf(status)) {
length = '';
} else if (null == len) {
length = '-';
length = ''
} else if (len == null) {
length = '-'
} else {
length = bytes(len).toLowerCase();
length = bytes(len).toLowerCase()
}

const upstream = err ? chalk.red('xxx')
: event === 'close' ? chalk.yellow('-x-')
: chalk.gray('-->')

console.log(' ' + upstream
+ ' ' + chalk.bold('%s')
+ ' ' + chalk.gray('%s')
+ ' ' + chalk[color]('%s')
+ ' ' + chalk.gray('%s')
+ ' ' + chalk.gray('%s'),
console.log(' ' + upstream +
' ' + chalk.bold('%s') +
' ' + chalk.gray('%s') +
' ' + chalk[color]('%s') +
' ' + chalk.gray('%s') +
' ' + chalk.gray('%s'),
ctx.method,
ctx.originalUrl,
status,
time(start),
length);
length)
}

/**
Expand All @@ -133,9 +126,9 @@ function log(ctx, start, len, err, event) {
* in seconds otherwise.
*/

function time(start) {
const delta = new Date - start;
function time (start) {
const delta = new Date() - start
return humanize(delta < 10000
? delta + 'ms'
: Math.round(delta / 1000) + 's');
: Math.round(delta / 1000) + 's')
}
7 changes: 7 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,17 @@
"index.js"
],
"scripts": {
"lint": "eslint --fix .",
"test": "mocha test.js"
},
"devDependencies": {
"chai": "^3.5.0",
"eslint": "^3.19.0",
"eslint-config-standard": "^10.2.1",
"eslint-plugin-import": "^2.2.0",
"eslint-plugin-node": "^4.2.2",
"eslint-plugin-promise": "^3.5.0",
"eslint-plugin-standard": "^3.0.1",
"koa": "^2.0.0-alpha.7",
"koa-route": "^3.2.0",
"mocha": "^3.2.0",
Expand Down
52 changes: 26 additions & 26 deletions test-server.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,37 +3,37 @@
* test server
*/

const Koa = require('koa');
const _ = require('koa-route');
const logger = require('./index');
const Koa = require('koa')
const _ = require('koa-route')
const logger = require('./index')

const app = new Koa();
app.use(logger());
const app = new Koa()
app.use(logger())

app.use(_.get('/200', function(ctx) {
ctx.body = 'hello world';
}));
app.use(_.get('/200', function (ctx) {
ctx.body = 'hello world'
}))

app.use(_.get('/301', function(ctx) {
ctx.status = 301;
}));
app.use(_.get('/301', function (ctx) {
ctx.status = 301
}))

app.use(_.get('/304', function(ctx) {
ctx.status = 304;
}));
app.use(_.get('/304', function (ctx) {
ctx.status = 304
}))

app.use(_.get('/404', function(ctx) {
ctx.status = 404;
ctx.body = 'not found';
}));
app.use(_.get('/404', function (ctx) {
ctx.status = 404
ctx.body = 'not found'
}))

app.use(_.get('/500', function(ctx) {
ctx.status = 500;
ctx.body = 'server error';
}));
app.use(_.get('/500', function (ctx) {
ctx.status = 500
ctx.body = 'server error'
}))

app.use(_.get('/error', function(ctx) {
throw new Error('oh no');
}));
app.use(_.get('/error', function (ctx) {
throw new Error('oh no')
}))

module.exports = app;
module.exports = app
Loading

0 comments on commit 28c4a0b

Please sign in to comment.