-
Notifications
You must be signed in to change notification settings - Fork 92
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
move default constructGetUri function to its own file
- Loading branch information
Showing
2 changed files
with
102 additions
and
79 deletions.
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
'use strict'; | ||
|
||
var debug = require('debug')('Fetcher:defaultConstructGetUri'); | ||
var lodash = { | ||
forEach: require('lodash/collection/forEach'), | ||
isArray: require('lodash/lang/isArray'), | ||
isObject: require('lodash/lang/isObject') | ||
}; | ||
|
||
function jsonifyComplexType(value) { | ||
if (lodash.isArray(value) || lodash.isObject(value)) { | ||
return JSON.stringify(value); | ||
} | ||
return value; | ||
} | ||
|
||
/** | ||
* Construct xhr GET URI. | ||
* @method defaultConstructGetUri | ||
* @param {String} uri base URI | ||
* @param {String} resource Resource name | ||
* @param {Object} params Parameters to be serialized | ||
* @param {Object} config Configuration object | ||
* @param {String} config.id_param Name of the id parameter | ||
* @param {Object} context Context object, which will become query params | ||
*/ | ||
module.exports = function defaultConstructGetUri(baseUri, resource, params, config, context) { | ||
var query = []; | ||
var matrix = []; | ||
var id_param = config.id_param; | ||
var id_val; | ||
var final_uri = baseUri + '/' + resource; | ||
|
||
if (params) { | ||
lodash.forEach(params, function eachParam(v, k) { | ||
if (k === id_param) { | ||
id_val = encodeURIComponent(v); | ||
} else { | ||
try { | ||
matrix.push(k + '=' + encodeURIComponent(jsonifyComplexType(v))); | ||
} catch (err) { | ||
debug('jsonifyComplexType failed: ' + err); | ||
} | ||
} | ||
}); | ||
} | ||
|
||
if (context) { | ||
lodash.forEach(context, function eachContext(v, k) { | ||
query.push(k + '=' + encodeURIComponent(jsonifyComplexType(v))); | ||
}); | ||
} | ||
|
||
if (id_val) { | ||
final_uri += '/' + id_param + '/' + id_val; | ||
} | ||
if (matrix.length > 0) { | ||
final_uri += ';' + matrix.sort().join(';'); | ||
} | ||
if (query.length > 0) { | ||
final_uri += '?' + query.sort().join('&'); | ||
} | ||
debug('constructed get uri:', final_uri); | ||
return final_uri; | ||
}; |