1 //this block is used to make this module works with Node (CommonJS module format)
2 if (typeof define !== 'function') {
3 var define = require('amdefine')(module)
6 define(['lodash'], function (_) {
8 function handleNestedFields(object, key, params, paramType) {
9 var attributes = key.split('.');
10 var field = attributes[0];
12 if (attributes.length > 1 && paramType[params.join('.')] == 'Object') {
13 var nestedField = attributes.slice(1).join('.');
16 if (typeof object[field] == 'object') {
17 object[field][nestedField] = object[key];
19 handleNestedFields(object[field], nestedField, params, paramType);
24 function handleNestedFieldsForAllParams(param, paramType) {
25 var result = Object.assign({}, param);
26 Object.keys(result).forEach(function (key) {
27 handleNestedFields(result, key, [], paramType);
32 function handleArraysAndObjectFields(param, paramType) {
33 var result = Object.assign({}, param);
34 Object.keys(paramType).forEach(function (key) {
35 if (result[key] && (paramType[key].endsWith('[]') || paramType[key] === 'Object')) {
37 result[key] = JSON.parse(result[key]);
44 function tryParsingAsType(object, path, type) {
45 var val = _.get(object, path);
46 if (val !== undefined) {
47 if (type === 'Boolean') {
49 _.set(object, path, true);
50 } else if (val === 'false') {
51 _.set(object, path, false);
53 console.warn('Failed to parse object value at path [' + path + ']. Value: (' + val + '). Type: (' + type + ')');
55 } else if (type === 'Number') {
56 var parsedInt = parseInt(val, 10);
57 if (!_.isNaN(parsedInt)) {
58 _.set(object, path, parsedInt);
60 console.warn('Failed to parse object value at path [' + path + ']. Value: (' + val + '). Type: (' + type + ')');
66 function handleNestedAndParsingFields(param, paramType) {
67 var result = handleArraysAndObjectFields(param, paramType);
68 result = handleNestedFieldsForAllParams(result, paramType);
72 function tryParsingWithTypes(param, paramType) {
73 var result = Object.assign({}, param);
74 Object.keys(paramType).forEach(function (key) {
75 tryParsingAsType(result, key, paramType[key]);
80 // Converts path params in the {param} format to the accepted :param format, used before inserting the URL params.
81 function convertPathParams(url) {
82 return url.replace(/{(.+?)}/g, ':$1');
85 return {handleNestedAndParsingFields,convertPathParams,tryParsingWithTypes};