Created
July 27, 2015 13:50
-
-
Save apisurfer/d1eebc253c7ed2bfd76b to your computer and use it in GitHub Desktop.
Example of lambda functions usage to create flexible ajax utility module
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
var _ = require('lodash'); | |
var $ = require('jquery'); | |
var apis = { | |
main: '/api/v1/', | |
tracker: '/tracking/v1/', | |
}; | |
/** | |
* Default data sent with every request; | |
* can be overwritten per request using the same key name | |
* @return {object} default data | |
*/ | |
function defaultData () { | |
return { | |
_: (new Date()).getTime(), | |
} | |
} | |
/** | |
* Returns function which returns jquery deffered upon ajax request | |
* @param {string} APIRoot root url of the API for relative url creation | |
* @param {string} type request type(GET, POST...) | |
* @param {string} url API endpoint. Appended to APIRoot | |
* @return {function} data gets sent with request | |
*/ | |
function request (APIRoot, type, url) { | |
return function (data) { | |
return $.ajax({ | |
url: apis[APIRoot] + url, | |
type: type, | |
data: _.assign(defaultData(), data), | |
dataType: 'json', | |
}); | |
} | |
// main API requests | |
function xMain (type, url) { | |
return request('main', type, url); | |
} | |
// tracker API requests | |
function xTracker(type, url) { | |
return request('tracker', type, url); | |
} | |
module.exports = { | |
app: { | |
getBundle: xMain('GET', 'get-bundle'), | |
}, | |
tracker: { | |
getMostActiveUsers: xTracker('GET', 'most-active/users'), | |
}, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment