-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinterceptor.js
48 lines (40 loc) · 1.15 KB
/
interceptor.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
var interceptor = require('express-interceptor')
var cheerio = require('cheerio')
var styleInterceptor = interceptor(function(req, res){
return {
// Only HTML responses will be intercepted
isInterceptable: function(){
if (!/2\d\d/.test(res.statusCode)) {
return false
}
return /text\/html/.test(res.get('Content-Type'))
},
// Appends a paragraph at the end of the response body
intercept: function(body, send) {
var $ = cheerio;
var $document = $.load(body)
var $nodes = $document('[data-node="node-stylus"]')
var uniqStyles = {}
var $styles = $nodes.each(function(idx, elm) {
var css = $(elm).text()
var style = [
'<style id=',
elm.attribs.id + '-style',
' ',
'data-node="node-style"',
'>',
css,
'</style>'
].join('')
uniqStyles[elm.attribs.id] = style
})
for (var i in uniqStyles) {
if (uniqStyles.hasOwnProperty(i)) {
$document('head').append(uniqStyles[i])
}
}
send($document.html())
}
}
})
module.exports = styleInterceptor