-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
48 lines (44 loc) · 1.34 KB
/
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
var cheerio = require('cheerio');
function isRedirect(status) {
if (status != 301 && status != 302) {
return false;
}
return true;
}
function isPjax(request) {
if (request.headers['X-PJAX'.toLowerCase()] == 'true') {
return true;
}
if (request.querystring && request.querystring.indexOf('_pjax=') != -1) {
return true;
}
return false;
}
function getPjaxContainer(request) {
if ( !! request.headers['X-PJAX-Container'.toLowerCase()]) {
return request.headers['X-PJAX-Container'.toLowerCase()];
}
if (request.url.indexOf('_pjax=') != -1) {
var container = request.url.match(new RegExp("[\?\&]" + '_pjax' + "=([^\&]+)","i"));
if (container != null && container.length < 1) {
return container[1];
}
}
return false;
}
module.exports = function(opts) {
return function *(next) {
yield next;
if ( ! isRedirect(this.status) && isPjax(this.req)) {
yield next;
var $ = cheerio.load(this.body);
var title = $.html('title');
var pjaxContainer = getPjaxContainer(this.req);
if (pjaxContainer) {
var container = $.html(pjaxContainer);
this.set('X-PJAX-URL', this.href);
this.body = title + container;
}
}
}
}