File tree Expand file tree Collapse file tree 4 files changed +44
-0
lines changed Expand file tree Collapse file tree 4 files changed +44
-0
lines changed Original file line number Diff line number Diff line change 32
32
"koa" : " ^2.5.2" ,
33
33
"koa-compress" : " ^3.0.0" ,
34
34
"koa-helmet" : " ^4.0.0" ,
35
+ "koa-is-json" : " ^1.0.0" ,
35
36
"koa-logger" : " ^3.2.0" ,
36
37
"koa-pino-logger" : " ^2.1.3" ,
37
38
"koa-redis-cache" : " ^3.0.1" ,
Original file line number Diff line number Diff line change @@ -6,6 +6,7 @@ const helmet = require('koa-helmet');
6
6
const Koa = require ( 'koa' ) ;
7
7
const logger = require ( 'koa-pino-logger' ) ;
8
8
const MongoClient = require ( 'mongodb' ) ;
9
+ const json = require ( './middleware/json' ) ;
9
10
const options = require ( './middleware/redis' ) ;
10
11
11
12
const capsules = require ( './routes/v2-capsules' ) ;
@@ -66,6 +67,10 @@ if (process.env.NODE_ENV === 'production') {
66
67
app . use ( cache ( options ) ) ;
67
68
}
68
69
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
+
69
74
// Koa routes
70
75
app . use ( capsules . routes ( ) ) ;
71
76
app . use ( errors . routes ( ) ) ;
Original file line number Diff line number Diff line change
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
+ } ;
Original file line number Diff line number Diff line change @@ -44,6 +44,7 @@ if (process.env.REDISCLOUD_URL) {
44
44
path : '/v2/capsules/(.*)' ,
45
45
expire : 86400 ,
46
46
} ] ,
47
+ passParam : 'pretty' ,
47
48
redis : {
48
49
host : redisURL . hostname ,
49
50
port : redisURL . port ,
@@ -88,6 +89,7 @@ if (process.env.REDISCLOUD_URL) {
88
89
path : '/v2/capsules/(.*)' ,
89
90
expire : 86400 ,
90
91
} ] ,
92
+ passParam : 'pretty' ,
91
93
} ;
92
94
}
93
95
You can’t perform that action at this time.
0 commit comments