Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Lib draft
- */
- const objectPicker = _.pickBy(_.isObject);
- const mapper = (arg) => {
- const mapping = arg.mapping ? arg.mapping : arg;
- const transformFlatKeys = _.mapKeys(key => {
- const mappingVal = mapping[key];
- if (mappingVal) {
- if (_.isString(mappingVal)) return mappingVal;
- if (_.isObject(mappingVal) && mappingVal.key) return mappingVal.key;
- }
- return key;
- });
- const mapValuesWithKey = _.mapValues.convert({ cap: false});
- const transformSubObjects = mapValuesWithKey((val, key) => {
- const mappingVal = mapping[key];
- if (_.isObject(val) && _.isObject(mappingVal)) {
- return mapper(mappingVal)(val);
- }
- return val;
- });
- const flow = [];
- if (arg.picker) {
- if (typeof arg.picker == 'function') flow.push(arg.picker);
- else flow.push(_.pick(arg.picker));
- }
- if (arg.defaults) {
- flow.push((obj) => {
- console.log('defaults => ', obj);
- const a = _.defaults(arg.defaults)(obj);
- console.log('defaults after => ', a);
- return a;
- });
- }
- if (arg.omiter) {
- if (typeof arg.omiter == 'function') flow.push(arg.omiter);
- else flow.push(_.omit(arg.omiter));
- }
- flow.push(transformSubObjects);
- flow.push(transformFlatKeys);
- const ff = _.flow(flow);
- return obj => ff(obj);
- }
- /**
- *
- * Sample code
- *
- */
- // mappings
- const adressMapping = {
- cityPlace: 'city'
- }
- const contactMapping = {
- managerId: 'manager_id',
- test: '100',
- adress: {
- key: 'location',
- picker: ['cityPlace', 'postal'],
- mapping: adressMapping,
- defaults: {
- number: '100',
- }
- }
- };
- const userMapping = {
- n1Id: 'n1_id',
- contact: {
- omiter: ['fieldIdontWant'],
- defaults:{
- firstname: 'Cyndie',
- adress: {},
- },
- mapping: contactMapping,
- },
- };
- // data
- const user = {
- n1Id: 10,
- firstname: 'Alex',
- contact: {
- managerId: 10,
- id: 10,
- fieldIdontWant: 'COUCOU',
- adress: {
- cityPlace: 'Orsay'
- }
- },
- };
- const transformer = mapper({
- mapping: userMapping,
- picker: ['n1Id', 'firstname', 'contact'],
- defaults: {
- lastname: '',
- }
- });
- const sU = transformer(user);
- console.log(sU);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement