-
Notifications
You must be signed in to change notification settings - Fork 6
/
index.js
49 lines (42 loc) · 974 Bytes
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/*!
* koa-html-minifier
*
* Copyright (c) 2020 Koa.js contributors
* MIT Licensed
*/
'use strict';
/**
* Module dependencies.
*/
const { minify } = require('html-minifier-terser');
/**
* Expose `koaHtmlMinifier()`.
*/
module.exports = koaHtmlMinifier;
/**
* Middleware that minifies your HTML responses.
*
* @api public
*/
function koaHtmlMinifier(options) {
return async (ctx, next) => {
await next();
if (
!options ||
!ctx.response.is('html') ||
!ctx.response.body ||
typeof ctx.response.body.pipe === 'function'
)
return;
if (Buffer.isBuffer(ctx.response.body))
ctx.response.body = ctx.response.body.toString('utf8');
if (typeof ctx.response.body === 'object') return;
try {
ctx.response.body = await minify(ctx.response.body, options);
} catch (err) {
const originalError = err.toString();
ctx.status = 500;
ctx.response.body = { originalError };
}
};
}