UNPKG

@mozaic-io/mozaic-sdk-node

Version:

The Mozaic Node SDK enables you to pay your creators easily via the Mozaic API.

77 lines (76 loc) 3.3 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.BaseResource = void 0; const axios_1 = require("axios"); const MozaicError_1 = require("./MozaicError"); /** * All classes in the resource folder should implement this interface so that they * can be instantiated in the main barrel. */ class BaseResource { getValueOrDefault(value, defaultValue) { if (value === null || value === undefined) return defaultValue; return value; } /** * A helper function that will either return the variable's value or throw an exception * if the value is null or undefined. Unit testing is simplified by avoiding ?? * @param name The name of the variable being checked * @param value The value of the variable being checked * @returns The value of the variable if it is available, otherwise an exception is thrown. */ throwIfNullOrUndefined(name, value) { if (value === null || value === undefined) throw new Error(`${name} is null or undefined`); return value; } /** * A helper function to validate limit and paging parameters. * @param limit Must be between 1 and 100 inclusive. * @param page Must be greater than 0 */ throwIfLimitOrPageAreInvalid(limit, page) { if (limit < 1) throw new Error("Please specify a limit greater than 0"); if (limit > 100) throw new Error("Please specify a limit less than or equal to 100"); if (page < 1) throw new Error("Please specify a page greater than 0"); } /** * A helper function to ensure that API calls are successful and return a valid status code. * @param call The API call to guard for exceptions and bad return codes. * @returns A promise of the type returned by Axios in the data field. */ execute(call) { return __awaiter(this, void 0, void 0, function* () { let result; try { result = yield call(); } catch (ex) { if (ex instanceof axios_1.AxiosError) { throw MozaicError_1.MozaicError.create(ex); } else if (ex instanceof Error) { throw MozaicError_1.MozaicError.create(ex); } throw MozaicError_1.MozaicError.create(ex); } if (result.status != 200) throw MozaicError_1.MozaicError.create(result); return result.data; }); } } exports.BaseResource = BaseResource;