forked from seeden/mongoose-locale
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
129 lines (102 loc) · 2.49 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
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
122
123
124
125
126
127
128
129
'use strict';
module.exports = function localePlugin (schema, options) {
//prepare arguments
options = options || {};
schema.eachPath(function(path, config) {
if(config.schema) {
config.schema.plugin(localePlugin, options);
return;
}
if (!config.options.locale) {
return;
}
//clean actual path
delete config.options.locale;
if(Array.isArray(config.options.type)) {
config.options = config.options.type.length
? config.options.type[0]
: schema.constructor.Types.Mixed;
}
var nested = [{
_id : false,
lg : { type: String },
value : config.options
}];
//replace path
schema.path(path, nested);
//add i18n
var pathParts = path.split('.'),
property = pathParts.pop();
pathParts.push('i18n', property);
var i18nPath = pathParts.join('.');
schema.virtual(i18nPath).get(function() {
var _this = this;
return {
get: function(locale, defaultValue, defaultFirst) {
return _this.getPropertyLocalised(path, locale, defaultValue, defaultFirst);
},
set: function(value, locale) {
return _this.setPropertyLocalised(path, value, locale);
}
};
});
});
schema.methods.getPropertyLocalised = function(property, locale, defaultValue, defaultFirst) {
defaultValue = defaultValue || null;
var prop = this.get(property);
if(!prop || !prop.length) {
return defaultValue;
}
for(var i=0; i<prop.length; i++) {
if(prop[i].lg === locale) {
return prop[i].value;
}
}
return defaultFirst && prop.length ? prop[0].value : defaultValue;
};
schema.methods.setPropertyLocalised = function(property, value, locale) {
var prop = this.get(property);
if(!prop || !prop.length) {
prop = [{
lg: locale,
value: value
}];
} else {
var exists = false;
for(var i=0; i<prop.length; i++) {
var item = prop[i];
if(item.lg !== locale) {
continue;
}
item.value = value;
exists = true;
break;
}
if(!exists) {
prop.push({
lg: locale,
value: value
});
}
}
this.markModified(property);
};
schema.methods.hasPropertyLocale = function(property, locale) {
var locales = this.getPropertyLocales(property);
if(locales.indexOf(locale)!==-1) {
return true;
}
return false;
};
schema.methods.getPropertyLocales = function(property) {
var prop = this.get(property),
locales = [];
if(!prop || !prop.length) {
return locales;
}
for(var i=0; i<prop.length; i++) {
locales.push(prop[i].lg);
}
return locales;
};
};