Javascript WebAPI / REST API module

Date: 2016-03-21

A simple extendable webapi AMD module using Bluebird and JQuery.


define(['bluebird', 'jquery', 'config', 'tools/all'], function() {
	'use strict';
    var exports = {};
        
    var tools = require('tools/all');
    var Promise = require('bluebird');
    var $ = require('jquery');
    var config = require('config');
    
    var trimr = tools.strings.trimr;
    var triml = tools.strings.triml;
    
    var baseUrl = trimr(config.webApiBaseUrl, '/');
    
    var request = function(method, path, data, settings) {
        return new Promise(function(resolve,reject){
			path = triml(path);
			
			var requestSettings = {
				url: baseUrl + '/' + path,
				type: method,
				data: data,
				dataType: 'json'
			};
			
			// merge settings into requestSettings
			if (settings) {
				for(var p in settings) {
					if (settings.hasOwnProperty(p)) {
						requestSettings[p] = settings[p];
					}
				}
			}
			
			$.ajax(requestSettings).done(function(data) {
				resolve(data);
			}).fail(function(error) {
				reject(error);
			});
        });
    };
    
    exports.request = request;
    
    exports.get = function(path, data, settings) {
        return request('GET', path, data, settings);
    };
    
    exports.post = function(path, data, settings) {
        return request('POST', path, data, settings);
    };
    
    exports.put = function(path, data, settings) {
        return request('PUT', path, data, settings);
    };
    
    exports.delete = function(path, data, settings) {
        return request('DELETE', path, data, settings);
    };
    
    return exports;
});
1640cookie-checkJavascript WebAPI / REST API module