1 |
|
2 | /**
|
3 | * Pretty JSON response middleware.
|
4 | *
|
5 | * - `pretty` default to pretty response [true]
|
6 | * - `param` optional query-string param for pretty responses [none]
|
7 | *
|
8 | * @param {Object} opts
|
9 | * @return {GeneratorFunction}
|
10 | * @api public
|
11 | */
|
12 |
|
13 | module.exports = function(opts){
|
14 | var opts = opts || {};
|
15 | var param = opts.param;
|
16 | var pretty = null == opts.pretty ? true : opts.pretty;
|
17 |
|
18 | return function *filter(next){
|
19 | yield *next;
|
20 |
|
21 | var body = this.body;
|
22 |
|
23 | // non-json
|
24 | if (!body || 'object' != typeof body) return;
|
25 |
|
26 | // query
|
27 | var hasParam = param && this.query[param];
|
28 |
|
29 | // pretty
|
30 | if (pretty || hasParam) {
|
31 | this.body = JSON.stringify(body, null, 2);
|
32 | }
|
33 | }
|
34 | };
|