After creating the initial layout, let's implement the API access layer by encapsulating it in its own dedicated file and namespace:
- Create a file named api.js and implement the REST API query calls:
'use-strict';
(function (window) {
const ns = window.api = window.api || {};
// EDIT the URL with the the address of your REST API -
const baseUrl = 'http://localhost:55564/api';
// build the URL for a REST API call and include the parameters
function getApiAction(action, parameters = null) {
const p = (!parameters || parameters.length === 0)
? ''
: `/${Object.values(parameters).join('/')}`;
return `${baseUrl}/${action}${p}`;
}
// iterate through products returned from REST API and set the primary image accordingly for each product
function visitProducts(products, callback) {
products.forEach(p => {
if (p.media && p.media.length > 0) {
p.primaryImage = p.media[0].url;
}
});
if (callback) callback(products);
}
// expose a function to load products from the REST API as part of the namespace object
ns.getProducts = function (category, callback) {
return $.getJSON(getApiAction('products/searchcategory', category),
data => visitProducts(data, callback));
}
// expose a function to load categories from the REST API as part of the namespace object
ns.getCategories = function (callback) {
return $.getJSON(getApiAction('products/categories'), callback);
}
})(window);
- Edit the baseUrl constant with the base URL of your hosted REST API:
// EDIT the URL with the the address of your REST API -
const baseUrl = 'http://localhost:55564/api';