Advertisement
Guest User

Untitled

a guest
Jul 23rd, 2016
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.15 KB | None | 0 0
  1. /**
  2. * Lib draft
  3. */
  4.  
  5. const objectPicker = _.pickBy(_.isObject);
  6.  
  7. const mapper = (arg) => {
  8. const mapping = arg.mapping ? arg.mapping : arg;
  9.  
  10. const transformFlatKeys = _.mapKeys(key => {
  11. const mappingVal = mapping[key];
  12. if (mappingVal) {
  13. if (_.isString(mappingVal)) return mappingVal;
  14. if (_.isObject(mappingVal) && mappingVal.key) return mappingVal.key;
  15. }
  16. return key;
  17. });
  18.  
  19. const mapValuesWithKey = _.mapValues.convert({ cap: false});
  20.  
  21. const transformSubObjects = mapValuesWithKey((val, key) => {
  22. const mappingVal = mapping[key];
  23. if (_.isObject(val) && _.isObject(mappingVal)) {
  24. return mapper(mappingVal)(val);
  25. }
  26. return val;
  27. });
  28.  
  29.  
  30. const flow = [];
  31.  
  32. if (arg.picker) {
  33. if (typeof arg.picker == 'function') flow.push(arg.picker);
  34. else flow.push(_.pick(arg.picker));
  35. }
  36.  
  37. if (arg.defaults) {
  38. flow.push((obj) => {
  39. console.log('defaults => ', obj);
  40. const a = _.defaults(arg.defaults)(obj);
  41. console.log('defaults after => ', a);
  42. return a;
  43. });
  44. }
  45.  
  46. if (arg.omiter) {
  47. if (typeof arg.omiter == 'function') flow.push(arg.omiter);
  48. else flow.push(_.omit(arg.omiter));
  49. }
  50.  
  51. flow.push(transformSubObjects);
  52. flow.push(transformFlatKeys);
  53.  
  54. const ff = _.flow(flow);
  55.  
  56. return obj => ff(obj);
  57. }
  58.  
  59.  
  60. /**
  61. *
  62. * Sample code
  63. *
  64. */
  65.  
  66.  
  67. // mappings
  68. const adressMapping = {
  69. cityPlace: 'city'
  70. }
  71.  
  72. const contactMapping = {
  73. managerId: 'manager_id',
  74. test: '100',
  75. adress: {
  76. key: 'location',
  77. picker: ['cityPlace', 'postal'],
  78. mapping: adressMapping,
  79. defaults: {
  80. number: '100',
  81. }
  82. }
  83. };
  84.  
  85. const userMapping = {
  86. n1Id: 'n1_id',
  87. contact: {
  88. omiter: ['fieldIdontWant'],
  89. defaults:{
  90. firstname: 'Cyndie',
  91. adress: {},
  92. },
  93. mapping: contactMapping,
  94. },
  95. };
  96.  
  97.  
  98. // data
  99. const user = {
  100. n1Id: 10,
  101. firstname: 'Alex',
  102. contact: {
  103. managerId: 10,
  104. id: 10,
  105. fieldIdontWant: 'COUCOU',
  106. adress: {
  107. cityPlace: 'Orsay'
  108. }
  109. },
  110. };
  111.  
  112.  
  113. const transformer = mapper({
  114. mapping: userMapping,
  115. picker: ['n1Id', 'firstname', 'contact'],
  116. defaults: {
  117. lastname: '',
  118. }
  119. });
  120.  
  121.  
  122. const sU = transformer(user);
  123.  
  124. console.log(sU);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement