@veedstudio/veed-node
Version:
Node JS Library for Veed API
118 lines (117 loc) • 4.19 kB
JavaScript
;
/*
Veed API wrapper
@author Philip Obosi <@worldclassdev>
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var request_promise_1 = __importDefault(require("request-promise"));
var config_1 = require("./config");
function Veed(key) {
if (!(this instanceof Veed)) {
return new Veed(key);
}
this.API_URL = config_1.API_URL;
this.key = key;
this.import();
}
var resources = {
assets: require("./resources/assets"),
render: require("./resources/render")
};
Veed.prototype = {
extend: function (func) {
var me = this;
return function () {
var data = arguments[0] || {};
// check method
var method = ["post", "get", "put", "delete"].includes(func.method)
? func.method
: (function () {
throw new Error("Method not Allowed! - Resource declaration error");
})();
var API_URL = me.API_URL + func.route, qs = {};
// Highest priority should go to path variables parsing and validation
var argsInAPI_URL = API_URL.match(/{[^}]+}/g);
if (argsInAPI_URL) {
argsInAPI_URL.map(function (arg) {
arg = arg.replace(/\W/g, "");
if (!(arg in data)) {
throw new Error("Argument '" + arg + "' is required");
}
else {
API_URL = API_URL.replace("{" + arg + "}", data["" + arg]);
// to avoid error, remove the path arg from body | qs params
// by deleting it from the data object before body | qs params are set
delete data[arg];
}
});
}
// incase of API_URLs with no params requirement
if (func.params) {
// check args
func.params.filter(function (param) {
if (!param.includes("*"))
return;
param = param.replace("*", "");
if (!(param in data)) {
throw new Error("Parameter '" + param + "' is required");
}
return;
});
}
// incase of API_URLs with no args requirement
if (func.args) {
// check args
func.args.filter(function (a) {
// remove unwanted properties
if (!a.includes("*")) {
if (a in data) {
qs["" + a] = data["" + a];
}
return;
}
a = a.replace("*", "");
if (!(a in data)) {
throw new Error("Argument '" + a + "' is required");
}
else {
qs["" + a] = data["" + a];
}
return;
});
}
// Create request
var options = {
url: API_URL,
json: true,
method: method.toUpperCase(),
headers: {
Authorization: me.key
}
};
console.log(options);
if (method == "post" || method == "put") {
options.body = data;
}
else {
options.qs = qs;
}
return request_promise_1.default(options);
};
},
import: function () {
for (var i in resources) {
var anon = function () { };
for (var j in resources[i]) {
anon.prototype[j] = this.extend(resources[i][j]);
}
Veed.prototype[i] = new anon();
}
},
};
module.exports = Veed;
// Allow use of default import syntax in TypeScript
module.exports.default = Veed;