Skip to content

Instantly share code, notes, and snippets.

@daniellizik
Created January 14, 2016 06:40
Show Gist options
  • Save daniellizik/adb99d8deb05c5794d98 to your computer and use it in GitHub Desktop.
Save daniellizik/adb99d8deb05c5794d98 to your computer and use it in GitHub Desktop.
custom $resource-ish factory
module.exports = ["$http", "$q", function($http, $q) {
/**
* @param opts {object} - hash of options
* url
* method
* params
* body
*
* @returns promise
*/
function Resource() {
var proto = resource.prototype = this.prototype;
return resource;
function resource(opts) {
var url, args, method;
if (!opts.hasOwnProperty("url") || !opts.hasOwnProperty("method"))
throw new Error("must specify url and method in resource")
url = urlGen(opts.params, opts.url, proto.baseUrl || "");
args = opts.body ? [url, opts.body] : [url];
method = opts.method.toLowerCase();
return $q(function(resolve, reject) {
$http[method].call(null, args).then(function(res) {
resolve(res.data)
});
});
}
}
Resource.prototype = {
baseUrl: "/"
};
function urlGen(params, dirty, baseUrl) {
var arr = dirty.split("/");
var clean = "";
var i;
var slug;
var ready;
for (i = 0; i < arr.length; i++) {
slug = arr[i].substring(1, arr[i].length);
if (arr[i].indexOf(":") > -1 && params.hasOwnProperty(slug))
clean += params[slug] + "/";
else if (arr[i].indexOf(":") < 0)
clean += arr[i] + "/";
}
if (clean.charAt(clean.length - 1) === "/")
ready = clean.substring(0, clean.length - 1);
else
ready = clean;
return baseUrl + ready;
}
return Resource.call(Resource);
}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment