-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
94 lines (80 loc) · 2.01 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
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
/*!
* locale
* Copyright(c) 2015 Fangdun Cai
* MIT Licensed
*/
'use strict';
/**
* Module dependences.
*/
var delegate = require('delegates');
/**
* Expose
*
* @param {Object} app
* @param {String} key - locale key name.
*
* @returns {Object} app
*/
module.exports = function(app, key) {
key = key || 'locale';
var request = app.request;
// From query, `locale=en`
Object.defineProperty(request, 'getLocaleFromQuery', {
value: function() {
return this.query[key];
}
});
// From query, `locale=en`
Object.defineProperty(request, 'getLocaleFromSubdomain', {
value: function() {
return this.subdomains.pop();
}
});
// From accept-language, `Accept-Language: zh-CN`
Object.defineProperty(request, 'getLocaleFromHeader', {
value: function(multi) {
var accept = this.acceptsLanguages() || '',
reg = /(^|,\s*)([a-z-]+)/gi,
locales = [],
match;
while ((match = reg.exec(accept))) {
locales.push(match[2])
if (!multi && locales.length) {
break;
}
}
return multi ? locales : locales[0];
}
});
// From cookie, `locale=zh-CN`
Object.defineProperty(request, 'getLocaleFromCookie', {
value: function() {
return this.ctx.cookies.get(key);
}
});
// From URL, `http://koajs.com/en`
Object.defineProperty(request, 'getLocaleFromUrl', {
value: function(options) {
var segments = this.path.substring(1).split('/');
return segments[options && options.offset || 0];
}
});
// From The Latest Domain, `http://koajs.com`, `http://kojs.cn`
Object.defineProperty(request, 'getLocaleFromTLD', {
value: function() {
return this.hostname.split('.').pop();
}
});
/**
* Delegate to this.ctx.
*/
delegate(app.context, 'request')
.method('getLocaleFromQuery')
.method('getLocaleFromSubdomain')
.method('getLocaleFromHeader')
.method('getLocaleFromCookie')
.method('getLocaleFromUrl')
.method('getLocaleFromTLD');
return app;
};