Skip to content

Commit

Permalink
ensure the nested objects are working
Browse files Browse the repository at this point in the history
  • Loading branch information
chamspan committed May 26, 2014
1 parent 8018432 commit baec82f
Showing 1 changed file with 51 additions and 9 deletions.
60 changes: 51 additions & 9 deletions index.js
Original file line number Diff line number Diff line change
@@ -3,29 +3,47 @@
var mongoose = require('mongoose');

var locales=['en','ru'];
var locale='en';

(function(){
var ma = mongoose.Schema.prototype.add;
var addI18n=function(obj){
var addI18n=function(schema,obj){
//console.log('====');

//console.log(obj);
//console.trace();
var keys = Object.keys(obj);

if (keys.length==1 && keys=='_id') return obj;

var ret={};

for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
var val = obj[key];

if (key==='type'){
ret[key]=val;
continue;
}

if (typeof val != "object") {
ret[key]=val;
continue;
};

if (val instanceof Array) {
ret[key]=val;
continue;
};

var kkeys=Object.keys(val);
var localize=false;
for (var ii=0; ii<kkeys.length;++ii){
var kkey=kkeys[ii];
var vval=val[kkey];
if (typeof vval=="object"){
val[kkey]=addI18n(vval)
if (typeof vval==="object"){
val[kkey]=addI18n(schema,vval)
}else{
if (vval && kkey=="localize"){
localize=true;
@@ -36,25 +54,49 @@ var locales=['en','ru'];
delete(val.localize);
var nval={};
for (var j=0;j<locales.length;j++){
nval[locales[j]]=val;// TODO: let's try to live without copy JSON.parse(JSON.stringify(va));
nval[locales[j]]=val;// Note: must live without copy JSON.parse(JSON.stringify(va)) because of [Function];
//nval[locales[j]]=JSON.parse(JSON.stringify(val));
}
//ret['_localized_'+key]=nval;
ret[key]=nval;
schema.virtual('localized.'+key)
.get(function(value,virtual){
var n=virtual.path.substring(10);
return this[n][locale];
})/*
.set(function(value,virtual){
var n=virtual.path.substring(10);
this[n]=value;
});*/
}else{
ret[key]=val;
}
};
return ret;
}
mongoose.Schema.prototype.add = function add (obj, prefix) {
ma.call(this,addI18n(obj),prefix);
//console.log({in:obj})
//console.trace();
var oobj=addI18n(this,obj);
//console.log({out:oobj})
ma.call(this,oobj,prefix);
};
})();

var localize=module.exports = function(opt){
return {

}
if (opt.locales) locales=opt.locales;
if (opt.locale) locale=opt.locale;
return {}
}
localize.locale=function(){
return locale;
}
localize.setLocale=function(sLocale){
locale=sLocale;
}
localize.locales=function(){
return locales;
}
}
localize.setLocales=function(sLocales){
locales=sLocales;
}

0 comments on commit baec82f

Please sign in to comment.