Created
December 28, 2013 06:21
-
-
Save KaeruCT/8156630 to your computer and use it in GitHub Desktop.
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
(function (exports, undefined) { | |
var baseUrl, | |
resourceMap, | |
type; | |
exports.ub = { | |
init: function (options) { | |
baseUrl = options.baseUrl; | |
type = options.type; | |
resourceMap = options.resourceMap; | |
}, | |
get: function () { | |
var args = Array.prototype.slice.call(arguments), | |
resource = args.shift(), | |
pregex = /:\w+/, | |
param, | |
url = resourceMap[resource]; | |
if (url === undefined) { | |
throw new Error('Resource ' + resource + ' not found in resource map'); | |
} | |
while (url.match(pregex)) { | |
param = args.shift(); | |
if (param === undefined) { | |
throw new Error('Not enough parameters for resource ' + resource); | |
} | |
url = url.replace(pregex, param); | |
} | |
if (type === 'jsonp') { | |
url += '?callback=JSON_CALLBACK'; | |
} | |
return baseUrl + url; | |
} | |
}; | |
}(window, void 0)); | |
// sample usage | |
ub.init({ | |
baseUrl: 'http://archive.neritic.net/', | |
type: 'jsonp', | |
resourceMap: { | |
'categories': 'categories', | |
'category': 'categories/:p', | |
'forums-by-category': 'categories/:p/forums', | |
'forum': 'forums/:p', | |
'threads-by-forum': 'forums/:p/threads', | |
'thread': 'threads/:p', | |
'posts-by-thread': 'threads/:p/posts', | |
'users': 'users', | |
'user': 'users/:p' | |
} | |
}); | |
console.log(ub.get('posts-by-thread', 1)); | |
console.log(ub.get('categories')); | |
console.log(ub.get('user', 1)); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment