|
| 1 | +/** |
| 2 | + * Created by codeslayer on 3/13/16. |
| 3 | + */ |
| 4 | + |
| 5 | +var JSONMapper = { |
| 6 | + |
| 7 | + /** |
| 8 | + * Routes request to mapObject function after sanitation checks in input/mapping |
| 9 | + * |
| 10 | + * @param {JSON} input, {JSON} mapping |
| 11 | + * @return {JSON} |
| 12 | + */ |
| 13 | + map: function(input, mapping){ |
| 14 | + if(Utils.isEmpty(input) || Utils.isEmpty(mapping)){ |
| 15 | + return null |
| 16 | + } |
| 17 | + |
| 18 | + return JSONMapper.mapObject(input,mapping); |
| 19 | + }, |
| 20 | + |
| 21 | + /** |
| 22 | + * This function iterates the specified mapping and populates the desired keys from the input |
| 23 | + * |
| 24 | + * @param {JSON} input, {JSON} mapping |
| 25 | + * @return {JSON} |
| 26 | + */ |
| 27 | + mapObject: function(input, mapping){ |
| 28 | + var mappedObject = {}; |
| 29 | + |
| 30 | + for(var actualKey in mapping){ |
| 31 | + /* |
| 32 | + -> if an object or array needs to be mapped, we take the desired key name and data to be mapped inside an object, |
| 33 | + and parse all the keys in data one by one and set the mapped output against the desired key name |
| 34 | + -> if a single variable needs to be mapped, we set the desired value against the desired key |
| 35 | + */ |
| 36 | + if(Utils.isObject(mapping[actualKey])){ |
| 37 | + var desiredKeyName = mapping[actualKey]['desiredKey']; |
| 38 | + var desiredDataMapping = mapping[actualKey]['desiredData']; |
| 39 | + |
| 40 | + if(Utils.isObject(desiredDataMapping)){ |
| 41 | + mappedObject[desiredKeyName] = JSONMapper.mapObject(input[actualKey],desiredDataMapping); |
| 42 | + } |
| 43 | + else if(Utils.isArray(desiredDataMapping)){ |
| 44 | + mappedObject[desiredKeyName] = JSONMapper.mapArray(input[actualKey],desiredDataMapping[0]); |
| 45 | + } |
| 46 | + } |
| 47 | + else{ |
| 48 | + var desiredKeyName = mapping[actualKey]; |
| 49 | + mappedObject[desiredKeyName] = input[actualKey]; |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + return mappedObject; |
| 54 | + }, |
| 55 | + |
| 56 | + /** |
| 57 | + * This function iterates an array and maps each object of the array one by one |
| 58 | + * |
| 59 | + * @param {JSON} input, {JSON} mapping |
| 60 | + * @return {JSON Array} |
| 61 | + */ |
| 62 | + mapArray: function(input, mapping){ |
| 63 | + var mappedArray = []; |
| 64 | + for(var index in input){ |
| 65 | + var inputObject = input[index]; |
| 66 | + var mappedObject = JSONMapper.mapObject(inputObject,mapping); |
| 67 | + mappedArray.push(mappedObject); |
| 68 | + } |
| 69 | + |
| 70 | + return mappedArray; |
| 71 | + } |
| 72 | + |
| 73 | +}; |
| 74 | + |
| 75 | +module.exports = JSONMapper; |
0 commit comments