rewrite.js
2.87 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
/**
* 路由重写
* @author: chenfeng<feng.chen@yoho.cn>
* @date: 2017/2/20
*/
'use strict';
const typeLib = require('../../config/type-lib');
const _ = require('lodash');
const utils = require('../../utils');
const helpers = global.yoho.helpers;
/**
* 解析url规则中的参数
*/
const resolve = (req, res, next) => {
let path,
params = {
channel: req.yoho.channel
};
path = _.join(_.map(req.params, v => {
return v;
}), '-');
if (!path) {
return next();
}
let conditions = path.split('-').filter(cond => cond);
_.each(conditions, condition => {
if (typeLib.channels[condition]) {
params.channel = condition;
} else if (condition.indexOf('_') >= 0) {
let item = condition.split('_');
if (item.length === 2) {
params[item[0]] = item[1];
}
} else if (condition >= 0 && !params.id) {
params.id = _.parseInt(condition);
}
});
req.yoho.channel = params.channel;
res.locals.channel = params.channel;
res.locals.pageChannel = { [params.channel]: true };
res.locals.setChannel = true;
Object.assign(req.query, params);
next();
};
/**
* 简介channel参数
*/
const channel = (req, res, next) => {
let channelName;
if (req.query.channel) {
if (req.query.channel >= 0) {
channelName = typeLib.channelNames[req.query.channel];
} else if (typeLib.channels[req.query.channel]) {
channelName = req.query.channel;
}
} else if (req.query.gender) {
let gender = req.query.gender;
switch (gender) {
case typeLib.gender.boys:
gender = 1;
break;
case typeLib.gender.girls:
gender = 2;
break;
case typeLib.gender.kids:
gender = 3;
break;
case typeLib.gender.lifestyle:
gender = 4;
break;
default:
break;
}
channelName = typeLib.channelNames[gender];
}
channelName = channelName || req.yoho.channel;
req.yoho.channel = channelName;
delete req.query.channel;
delete req.query.gender;
next();
};
/**
* 参数排序
*/
const sortParams = (req, res, next) => {
let sorts = utils.mapSort(req.query);
let queryKeys = _.keys(req.query);
let index = 0;
let matched = _.map(sorts, (val, key) => {
return key === queryKeys[index++];
});
if (_.every(matched, match => match)) {
return next();
} else {
let subdomain = 'list';
if (req.hostname.indexOf('search') === 0) {
subdomain = 'search';
}
return res.redirect(helpers.urlFormat('/', sorts, subdomain));
}
};
module.exports = {
resolve,
channel,
sortParams
};