JSFiddle - React, Tailwind, and code Playground
by Amresh Venugopal
HTML
Junk: <pre id='0'></pre>
User: <pre id='1'></pre>
Country: <pre id='2'></pre>
JavaScript
function apiHelper (baseUrl, id) {
var allowedMethods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'];
function routeIsValid (route) {
if (typeof route !== 'string') throw new Error("Route is not valid");
if (route[0] !== '/') throw new Error("Route must start with '/'");
return route;
}
function methodExists (method) {
if (typeof method !== 'string') throw new Error("Pass method as string!");
if (allowedMethods.indexOf(method.toUpperCase()) === -1) throw new Error("Method is not allowed!")
return method;
}
return function (route, method) {
$.ajax({
url: baseUrl + routeIsValid(route),
method: methodExists(method)
}).then(function(data) {
console.log(data);
document.getElementById(id).innerHTML = JSON.stringify(data, null, ' ');
});
}
}
var freeApi = apiHelper('https://jsonplaceholder.typicode.com', '0');
var userApi = apiHelper('https://randomuser.me/api', '1');
var countryApi = apiHelper('https://restcountries.eu/rest/v2/name', '2');
freeApi('/posts/1', 'get');
userApi('/', 'get');
countryApi('/Maldives', 'get');