UNPKG

@pubby/sdk

Version:
91 lines (88 loc) 3.8 kB
import { __assign, __awaiter, __generator } from 'tslib'; import axios from 'axios'; var Rest = /** @class */ (function () { function Rest(api, path, options) { var _this = this; if (options === void 0) { options = {}; } this.api = api; this.axios = Rest.axios.create(__assign({ baseURL: this.baseURL + "/" + path }, options)); this.axios.interceptors.request.use(function (req) { return __awaiter(_this, void 0, void 0, function () { var token; var _a; return __generator(this, function (_b) { switch (_b.label) { case 0: if (!!req.public) return [3 /*break*/, 2]; return [4 /*yield*/, this.api.pubby.auth.strategy.getToken()]; case 1: token = _b.sent(); if (token) { req.headers.authorization = (_a = req.headers.authorization) !== null && _a !== void 0 ? _a : "Bearer " + token; } _b.label = 2; case 2: return [2 /*return*/, req]; } }); }); }); } Object.defineProperty(Rest.prototype, "baseURL", { get: function () { return this.api.pubby.config.current.baseURL; }, enumerable: false, configurable: true }); Rest.prototype.request = function (options) { if (options === void 0) { options = {}; } return this.axios.request(options).then(function (res) { return res.data; }); }; Rest.prototype.find = function (params, config) { if (params === void 0) { params = {}; } if (config === void 0) { config = {}; } return this.request(__assign({ method: "get", url: "/", params: params }, config)); }; Rest.prototype.findOne = function (id, params, config) { if (params === void 0) { params = {}; } if (config === void 0) { config = {}; } return this.request(__assign({ method: "get", url: String(id), params: params }, config)); }; Rest.prototype.create = function (data, params, config) { if (params === void 0) { params = {}; } if (config === void 0) { config = {}; } return this.request(__assign({ method: "post", url: "/", data: data, params: params }, config)); }; Rest.prototype.update = function (data, params, config) { if (params === void 0) { params = {}; } if (config === void 0) { config = {}; } return this.request(__assign({ method: "patch", url: String(data.id), data: data, params: params }, config)); }; Rest.prototype.delete = function (id, params, config) { if (params === void 0) { params = {}; } if (config === void 0) { config = {}; } return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.request(__assign({ method: "delete", url: String(id), params: params }, config))]; case 1: _a.sent(); return [2 /*return*/]; } }); }); }; Rest.prototype.save = function (data, params, config) { if (params === void 0) { params = {}; } if (config === void 0) { config = {}; } if (!data.id) { return this.create(data, params, config); } else { return this.update(data, params, config); } }; Rest.axios = axios; return Rest; }()); export { Rest };