Last active
September 27, 2016 06:42
-
-
Save emyann/c410b824141f1913e45752622cab587e to your computer and use it in GitHub Desktop.
AutoMapper.js with predicate applying
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
function DataMapper(schema, items) { | |
let _schema = _.clone(schema); | |
let transformer = (items) => { | |
return _.chain(items) | |
.map((obj) => { | |
return _.mapValues(_schema, (transformation) => { | |
if(!_.isObject(transformation)){ | |
return _.get(obj, transformation); | |
} | |
else if(_.isFunction(transformation)){ | |
let delta = _.get(obj, transformation.path); | |
return transformation(delta); | |
} | |
else{ | |
let delta = _.get(obj, transformation.path); | |
return transformation.fn(delta); | |
} | |
}); | |
}).value(); | |
}; | |
if (items === undefined) { | |
return (items) => { | |
return transformer(items); | |
} | |
} else { | |
return transformer(items); | |
} | |
} | |
class Comment { | |
constructor(id, message, owner, comment, creationTime){} | |
} | |
class User { | |
constructor(id,firstname,lastname,hasAvatar){} | |
} | |
let turd = { | |
data : { user : { | |
id : 123, | |
firstname : 'john' | |
} }, | |
message: 'some content', | |
id:'message-id-1' | |
} | |
let schema = { | |
id:'id', | |
message:'message', | |
owner: { | |
path: 'data.user', | |
fn: (user) => { return _.assignIn(new User(), user); } | |
} | |
}; | |
let transformedData = DataMapper(schema, [turd]); | |
let comment = _.assignIn(new Comment(),transformedData[0]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment