bc-node-sdk
Version:
BetterCommerce's NodeJS SDK encapsulates the base framework for all the Next.js applications.
64 lines (63 loc) • 3.06 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const api_1 = __importDefault(require("../infrastructure/api"));
const app_util_1 = __importDefault(require("./app-util"));
const parse_util_1 = __importDefault(require("./parse-util"));
const constants_1 = require("../domain/constants");
/**
* Class {@link ApiUtil} encapsulates utility methods required to make API calls and handle responses.
*/
class ApiUtil {
/**
* Makes an API call using the provided Axios request configuration.
* Logs the request configuration information.
*
* @param {AxiosRequestConfig<any>} config - The Axios request configuration object.
* @returns {Promise<any>} The result of the API call.
*/
static async callApi(config) {
app_util_1.default.logInfo(config, '--- callApi ---');
const result = await (0, api_1.default)(config);
return result;
}
/**
* Generates a headers object from the given cookies by extracting all cookies into a
* JavaScript object where each property is a cookie name and the corresponding value is
* the cookie's value.
*
* @param {ReadonlyRequestCookies} cookies - The cookies object to get the headers from.
* @returns {object} A JavaScript object containing all the cookies, where each
* property is a cookie name and the corresponding value is the cookie's value.
*/
static generateNextApiHeaders(cookies) {
const headers = Object.assign({}, app_util_1.default.allCookies(cookies));
return headers;
}
/**
* Generates the base URL from the given headers by combining the 'x-forwarded-proto' and 'host' headers.
*
* @param {ReadonlyHeaders} headers - The headers object to get the base URL from.
* @returns {string} The base URL of the Next.js API endpoint.
*/
static getAppBaseUrl(headers) {
const baseUrl = `${headers.get('x-forwarded-proto')}://${headers.get('host')}`;
return baseUrl;
}
/**
* Generates the full URL of a Next.js API endpoint by combining the base URL
* (obtained from the headers) with the endpoint URL and any additional parameters.
*
* @param {string} endpointUrl - The URL of the Next.js API endpoint.
* @param {ReadonlyHeaders} headers - The headers object to get the base URL from.
* @param {Object} moreParams - Additional parameters to include in the URL. Defaults to an empty object.
* @returns {string} The full URL of the Next.js API endpoint.
*/
static generateNextApiEndpointUrl(endpointUrl, headers, moreParams = constants_1.Defaults.Object.Value) {
const baseUrl = ApiUtil.getAppBaseUrl(headers);
return parse_util_1.default.stringFormat(`${baseUrl}${endpointUrl}`, Object.assign({}, moreParams));
}
}
exports.default = ApiUtil;