Last active
September 22, 2015 22:46
-
-
Save klauskpm/ab82dcf94263927321b7 to your computer and use it in GitHub Desktop.
Transforming object datas from an Entity
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Rest = function () | |
{ | |
var entitySufix = "Entity"; | |
var dataTransformer = new DataTransformer(); | |
this.get = function (entityName, data) { | |
var entity = new window[entityName + entitySufix](data); | |
dataTransformer.setFields(entity.fields); | |
dataTransformer.setHide(entity.hide); | |
return dataTransformer.getData(entity.get()); | |
}; | |
}; | |
PersonEntity = function (data) | |
{ | |
var entityData = data; | |
this.fields = { | |
nome: { | |
name: "funcionario", | |
value: function (value) { | |
return "Ola " + value; | |
} | |
}, | |
cargo: { | |
name: "contratado", | |
value: function (value) { | |
return "Contratado como " + value.titulo + " em " + value.contratacao; | |
} | |
} | |
}; | |
this.hide = ['id']; | |
this.get = function () { | |
return entityData; | |
} | |
}; | |
DataTransformer = function () | |
{ | |
var fields, | |
hide = []; | |
this.getData = function (data) { | |
var jsonString = JSON.stringify(data), | |
parsedData = JSON.parse(jsonString, this.transformer); | |
return parsedData; | |
}; | |
this.setFields = function (value) { | |
fields = value; | |
}; | |
this.setHide = function (value) { | |
if (typeof value === "object") { | |
hide = value; | |
} else { | |
hide.push(value); | |
} | |
}; | |
this.transformer = function (key, value) { | |
if (!(key in fields) && (hide.indexOf(key)>-1)) { | |
return undefined; | |
} else if (typeof fields[key] === "function") { | |
return fields[key](value); | |
} else if (typeof fields[key] === "object") { | |
this[fields[key]["name"]] = fields[key]["value"](value); | |
return undefined; | |
} | |
return value; | |
} | |
}; | |
var data = [ | |
{ | |
id: 3, | |
nome: "klaus", | |
cargo: { | |
id: 2, | |
titulo: "programador", | |
contratacao: "2015-09-22" | |
} | |
}, | |
{ | |
id: 3, | |
nome: "Pedro" | |
}, | |
{ | |
id: 3, | |
cargo: { | |
id: 2, | |
titulo: "logrador", | |
contratacao: "2015-09-22" | |
} | |
}, | |
{ | |
nome: "klaus", | |
cargo: { | |
id: 2, | |
titulo: "programador", | |
contratacao: "2015-09-22" | |
} | |
} | |
]; | |
var rest = new Rest(); | |
var person = rest.get("Person", data); | |
console.log(person); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment