UNPKG

axios-case-converter

Version:

Axios transformer/interceptor that converts snake_case/camelCase

446 lines (420 loc) 18.6 kB
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('axios')) : typeof define === 'function' && define.amd ? define(['exports', 'axios'], factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.AxiosCaseConverter = {}, global.axios)); })(this, (function (exports, axios) { 'use strict'; /****************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ var __assign = function() { __assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; function __values(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); } function __read(o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error: error }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e) throw e.error; } } return ar; } function __spreadArray(to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); } typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { var e = new Error(message); return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; }; /** * Source: ftp://ftp.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt */ /** * Lower case as a function. */ function lowerCase(str) { return str.toLowerCase(); } // Support camel case ("camelCase" -> "camel Case" and "CAMELCase" -> "CAMEL Case"). var DEFAULT_SPLIT_REGEXP = [/([a-z0-9])([A-Z])/g, /([A-Z])([A-Z][a-z])/g]; // Remove all non-word characters. var DEFAULT_STRIP_REGEXP = /[^A-Z0-9]+/gi; /** * Normalize the string into something other libraries can manipulate easier. */ function noCase(input, options) { if (options === void 0) { options = {}; } var _a = options.splitRegexp, splitRegexp = _a === void 0 ? DEFAULT_SPLIT_REGEXP : _a, _b = options.stripRegexp, stripRegexp = _b === void 0 ? DEFAULT_STRIP_REGEXP : _b, _c = options.transform, transform = _c === void 0 ? lowerCase : _c, _d = options.delimiter, delimiter = _d === void 0 ? " " : _d; var result = replace(replace(input, splitRegexp, "$1\0$2"), stripRegexp, "\0"); var start = 0; var end = result.length; // Trim the delimiter from around the output string. while (result.charAt(start) === "\0") start++; while (result.charAt(end - 1) === "\0") end--; // Transform each token independently. return result.slice(start, end).split("\0").map(transform).join(delimiter); } /** * Replace `re` in the input string with the replacement value. */ function replace(input, re, value) { if (re instanceof RegExp) return input.replace(re, value); return re.reduce(function (input, re) { return input.replace(re, value); }, input); } function pascalCaseTransform(input, index) { var firstChar = input.charAt(0); var lowerChars = input.substr(1).toLowerCase(); if (index > 0 && firstChar >= "0" && firstChar <= "9") { return "_" + firstChar + lowerChars; } return "" + firstChar.toUpperCase() + lowerChars; } function pascalCase(input, options) { if (options === void 0) { options = {}; } return noCase(input, __assign({ delimiter: "", transform: pascalCaseTransform }, options)); } function camelCaseTransform(input, index) { if (index === 0) return input.toLowerCase(); return pascalCaseTransform(input, index); } function camelCase(input, options) { if (options === void 0) { options = {}; } return pascalCase(input, __assign({ transform: camelCaseTransform }, options)); } function dotCase(input, options) { if (options === void 0) { options = {}; } return noCase(input, __assign({ delimiter: "." }, options)); } function snakeCase(input, options) { if (options === void 0) { options = {}; } return dotCase(input, __assign({ delimiter: "_" }, options)); } /** * Upper case the first character of an input string. */ function upperCaseFirst(input) { return input.charAt(0).toUpperCase() + input.substr(1); } function capitalCaseTransform(input) { return upperCaseFirst(input.toLowerCase()); } function capitalCase(input, options) { if (options === void 0) { options = {}; } return noCase(input, __assign({ delimiter: " ", transform: capitalCaseTransform }, options)); } function headerCase(input, options) { if (options === void 0) { options = {}; } return capitalCase(input, __assign({ delimiter: "-" }, options)); } var applyCaseOptions = function (fn, defaultOptions) { return function (input, options) { return fn(input, __assign(__assign({}, defaultOptions), options)); }; }; var preserveSpecificKeys = function (fn, keys) { var condition = typeof keys === 'function' ? keys : function (input) { return keys.includes(input); }; return function (input, options) { return condition(input, options) ? input : fn(input, options); }; }; var isURLSearchParams = function (value) { return (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams); }; var isFormData = function (value) { return typeof FormData !== 'undefined' && value instanceof FormData; }; var isPlainObject = function (value) { if (value == null) { return false; } var proto = Object.getPrototypeOf(value); return proto === null || proto === Object.prototype; }; var isTransformable = function (value) { return (Array.isArray(value) || isPlainObject(value) || isFormData(value) || isURLSearchParams(value)); }; var isAxiosHeaders = function (value) { if (value == null) { return false; } return value instanceof axios.AxiosHeaders; }; var caseFunctions = { snake: snakeCase, camel: camelCase, header: headerCase, }; var transformObjectUsingCallbackRecursive = function (data, fn, overwrite) { var e_1, _a, e_2, _b, e_3, _c; if (!isTransformable(data)) { return data; } /* eslint-disable no-console */ // Check FormData/URLSearchParams compatibility if ((isFormData(data) || isURLSearchParams(data)) && (!data.entries || (overwrite && !data.delete))) { var type = isFormData(data) ? 'FormData' : 'URLSearchParams'; var polyfill = isFormData(data) ? 'https://github.com/jimmywarting/FormData' : 'https://github.com/jerrybendy/url-search-params-polyfill'; if (typeof navigator !== 'undefined' && navigator.product === 'ReactNative') { // You cannot transform FormData/URLSearchParams on React Native console.warn("Be careful that ".concat(type, " cannot be transformed on React Native. If you intentionally implemented, ignore this kind of warning: https://facebook.github.io/react-native/docs/debugging.html")); } else { if (!data.entries) { // You need to polyfill `entries` method console.warn("You must use polyfill of ".concat(type, ".prototype.entries() on Internet Explorer or Safari: ").concat(polyfill)); } if (overwrite && !data.delete) { // You need to polyfill `delete` method for overwriting console.warn("You must use polyfill of ".concat(type, ".prototype.delete() on Internet Explorer or Safari: ").concat(polyfill)); } } return data; } /* eslint-enable no-console */ var prototype = Object.getPrototypeOf(data); // Storage of new values. // New instances are created when overwriting is disabled. var store = overwrite ? data : !prototype ? Object.create(null) : new prototype.constructor(); // We need to clean up all entries before overwriting. var series; if (isFormData(data) || isURLSearchParams(data)) { // Create native iterator from FormData/URLSearchParams series = data.entries(); if (overwrite) { // When overwriting, native iterator needs to be copied as array. series = __spreadArray([], __read(series), false); try { for (var series_1 = __values(series), series_1_1 = series_1.next(); !series_1_1.done; series_1_1 = series_1.next()) { var _d = __read(series_1_1.value, 1), key = _d[0]; data.delete(key); } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (series_1_1 && !series_1_1.done && (_a = series_1.return)) _a.call(series_1); } finally { if (e_1) throw e_1.error; } } } } else { // Create array from objects series = Object.entries(data); // Array keys never change, so we don't need to clean up if (overwrite && !Array.isArray(data)) { try { for (var series_2 = __values(series), series_2_1 = series_2.next(); !series_2_1.done; series_2_1 = series_2.next()) { var _e = __read(series_2_1.value, 1), key = _e[0]; delete data[key]; } } catch (e_2_1) { e_2 = { error: e_2_1 }; } finally { try { if (series_2_1 && !series_2_1.done && (_b = series_2.return)) _b.call(series_2); } finally { if (e_2) throw e_2.error; } } } } try { for (var series_3 = __values(series), series_3_1 = series_3.next(); !series_3_1.done; series_3_1 = series_3.next()) { var _f = __read(series_3_1.value, 2), key = _f[0], value = _f[1]; if (isFormData(store) || isURLSearchParams(store)) { store.append(fn(key), value); } else if (key !== '__proto__') { store[Array.isArray(data) ? Number(key) : fn("".concat(key))] = transformObjectUsingCallbackRecursive(value, fn, overwrite); } } } catch (e_3_1) { e_3 = { error: e_3_1 }; } finally { try { if (series_3_1 && !series_3_1.done && (_c = series_3.return)) _c.call(series_3); } finally { if (e_3) throw e_3.error; } } return store; }; var transformObjectUsingCallback = function (data, fn, options) { fn = applyCaseOptions(fn, __assign({ stripRegexp: /[^A-Z0-9[\]]+/gi }, options === null || options === void 0 ? void 0 : options.caseOptions)); if (options === null || options === void 0 ? void 0 : options.preservedKeys) { fn = preserveSpecificKeys(fn, options.preservedKeys); } return transformObjectUsingCallbackRecursive(data, fn, (options === null || options === void 0 ? void 0 : options.overwrite) || false); }; var createObjectTransformer = function (fn) { return function (data, options) { return transformObjectUsingCallback(data, fn, options); }; }; var createObjectTransformerOf = function (functionName, options) { return createObjectTransformer((options === null || options === void 0 ? void 0 : options[functionName]) || caseFunctions[functionName]); }; var createObjectTransformers = function (options) { var e_4, _a; var functionNames = Object.keys(caseFunctions); var objectTransformers = {}; try { for (var functionNames_1 = __values(functionNames), functionNames_1_1 = functionNames_1.next(); !functionNames_1_1.done; functionNames_1_1 = functionNames_1.next()) { var functionName = functionNames_1_1.value; objectTransformers[functionName] = createObjectTransformerOf(functionName, options); } } catch (e_4_1) { e_4 = { error: e_4_1 }; } finally { try { if (functionNames_1_1 && !functionNames_1_1.done && (_a = functionNames_1.return)) _a.call(functionNames_1); } finally { if (e_4) throw e_4.error; } } return objectTransformers; }; var createSnakeParamsInterceptor = function (options) { var snake = createObjectTransformers(options === null || options === void 0 ? void 0 : options.caseFunctions).snake; return function (config) { if (!(options === null || options === void 0 ? void 0 : options.ignoreParams) && config.params) { config.params = snake(config.params, options); } return config; }; }; var createSnakeRequestTransformer = function (options) { var _a = createObjectTransformers(options === null || options === void 0 ? void 0 : options.caseFunctions), snake = _a.snake, header = _a.header; return function (data, headers) { overwriteHeadersOrNoop(headers, header, options, [ 'common', 'delete', 'get', 'head', 'post', 'put', 'patch', ]); return snake(data, options); }; }; var createCamelResponseTransformer = function (options) { var camel = createObjectTransformers(options === null || options === void 0 ? void 0 : options.caseFunctions).camel; return function (data, headers) { overwriteHeadersOrNoop(headers, camel, options); return camel(data, options); }; }; var overwriteHeadersOrNoop = function (headers, fn, options, excludedKeys) { var e_1, _a, _b, _c; if ((options === null || options === void 0 ? void 0 : options.ignoreHeaders) || (!isPlainObject(headers) && !isAxiosHeaders(headers))) { return; } try { for (var _d = __values(Object.entries(headers)), _e = _d.next(); !_e.done; _e = _d.next()) { var _f = __read(_e.value, 2), key = _f[0], value = _f[1]; fn(value, __assign({ overwrite: true }, options)); if ((excludedKeys || []).includes(key)) { continue; } if (isAxiosHeaders(headers)) { headers.delete(key); headers.set(Object.keys(fn((_b = {}, _b[key] = null, _b), options))[0], value, true); } else { delete headers[key]; headers[Object.keys(fn((_c = {}, _c[key] = null, _c), options))[0]] = value; } } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (_e && !_e.done && (_a = _d.return)) _a.call(_d); } finally { if (e_1) throw e_1.error; } } }; var applyCaseMiddleware$1 = function (axios, options) { var _a, _b, _c; axios.defaults.transformRequest = __spreadArray([ ((_a = options === null || options === void 0 ? void 0 : options.caseMiddleware) === null || _a === void 0 ? void 0 : _a.requestTransformer) || createSnakeRequestTransformer(options) ], __read((Array.isArray(axios.defaults.transformRequest) ? axios.defaults.transformRequest : axios.defaults.transformRequest !== undefined ? [axios.defaults.transformRequest] : [])), false); axios.defaults.transformResponse = __spreadArray(__spreadArray([], __read((Array.isArray(axios.defaults.transformResponse) ? axios.defaults.transformResponse : axios.defaults.transformResponse !== undefined ? [axios.defaults.transformResponse] : [])), false), [ ((_b = options === null || options === void 0 ? void 0 : options.caseMiddleware) === null || _b === void 0 ? void 0 : _b.responseTransformer) || createCamelResponseTransformer(options), ], false); axios.interceptors.request.use(((_c = options === null || options === void 0 ? void 0 : options.caseMiddleware) === null || _c === void 0 ? void 0 : _c.requestInterceptor) || createSnakeParamsInterceptor(options)); return axios; }; var applyCaseMiddleware = applyCaseMiddleware$1; exports["default"] = applyCaseMiddleware; Object.defineProperty(exports, '__esModule', { value: true }); })); //# sourceMappingURL=axios-case-converter.js.map