Skip to content

Commit d8c51e6

Browse files
committed
Add pretty querstring to allow pretty print json debugging
1 parent 35ef834 commit d8c51e6

File tree

4 files changed

+44
-0
lines changed

4 files changed

+44
-0
lines changed

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232
"koa": "^2.5.2",
3333
"koa-compress": "^3.0.0",
3434
"koa-helmet": "^4.0.0",
35+
"koa-is-json": "^1.0.0",
3536
"koa-logger": "^3.2.0",
3637
"koa-pino-logger": "^2.1.3",
3738
"koa-redis-cache": "^3.0.1",

src/app.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ const helmet = require('koa-helmet');
66
const Koa = require('koa');
77
const logger = require('koa-pino-logger');
88
const MongoClient = require('mongodb');
9+
const json = require('./middleware/json');
910
const options = require('./middleware/redis');
1011

1112
const capsules = require('./routes/v2-capsules');
@@ -66,6 +67,10 @@ if (process.env.NODE_ENV === 'production') {
6667
app.use(cache(options));
6768
}
6869

70+
// Allow pretty print via pretty=true querystring
71+
// Pretty printed json will NOT be cached
72+
app.use(json({ pretty: false, param: { pretty: true } }));
73+
6974
// Koa routes
7075
app.use(capsules.routes());
7176
app.use(errors.routes());

src/middleware/json.js

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
2+
const isJSON = require('koa-is-json');
3+
4+
/**
5+
* Pretty JSON response middleware.
6+
*
7+
* - `pretty` default to pretty response [true]
8+
* - `param` optional query-string param for pretty responses [none]
9+
*
10+
* @param {Object} opts
11+
* @return {GeneratorFunction}
12+
* @api public
13+
*/
14+
15+
module.exports = (opts = {}) => {
16+
const param = opts.param;
17+
const pretty = opts.pretty === false ? true : opts.pretty;
18+
const spaces = opts.spaces || 2;
19+
20+
return (ctx, next) => {
21+
return next().then(() => {
22+
const body = ctx.body;
23+
const json = isJSON(body);
24+
if (!json) return;
25+
26+
// query
27+
const hasParam = param.pretty === true && ctx.query.pretty === 'true';
28+
const prettify = pretty && hasParam;
29+
30+
// prettify JSON responses
31+
if (json && prettify) {
32+
ctx.body = JSON.stringify(body, null, spaces);
33+
}
34+
});
35+
};
36+
};

src/middleware/redis.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ if (process.env.REDISCLOUD_URL) {
4444
path: '/v2/capsules/(.*)',
4545
expire: 86400,
4646
}],
47+
passParam: 'pretty',
4748
redis: {
4849
host: redisURL.hostname,
4950
port: redisURL.port,
@@ -88,6 +89,7 @@ if (process.env.REDISCLOUD_URL) {
8889
path: '/v2/capsules/(.*)',
8990
expire: 86400,
9091
}],
92+
passParam: 'pretty',
9193
};
9294
}
9395

0 commit comments

Comments
 (0)