UNPKG

@react-native-kakao/core

Version:

React Native Kakao Core SDK

67 lines (63 loc) 2.46 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.kFetchFormUrlEncoded = exports.kFetch = void 0; var _returnFetch = _interopRequireDefault(require("return-fetch")); var _kCreateWebError = require("./kCreateWebError"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // Use as a replacer of `RequestInit` // Use as a replacer of `Response` // this resembles the default behavior of axios json parser // https://github.com/axios/axios/blob/21a5ad34c4a5956d81d338059ac0dd34a19ed094/lib/defaults/index.js#L25 const parseJsonSafely = text => { try { return JSON.parse(text); } catch (e) { if (e.name !== 'SyntaxError') { throw e; } return text.trim(); } }; function jsonToFormUrlEncoded(json) { return Object.keys(json).map(key => key + '=' + json[key]).join('&'); } // Write your own high order function to serialize request body and deserialize response body. const returnFetchJson = (args, formUrlEncoded = false) => { const fetch = (0, _returnFetch.default)(args); return async (url, init) => { var _init$method; const response = await fetch(url, { ...init, body: (init === null || init === void 0 ? void 0 : init.body) && (!formUrlEncoded ? JSON.stringify(init.body) : jsonToFormUrlEncoded(init.body)), headers: { ...((init === null || init === void 0 || (_init$method = init.method) === null || _init$method === void 0 ? void 0 : _init$method.toLowerCase()) === 'post' ? { 'Content-type': formUrlEncoded ? 'application/x-www-form-urlencoded;charset=utf-8' : 'application/json;charset=utf-8' } : {}), ...(init === null || init === void 0 ? void 0 : init.headers) } }); if (response.status === 401) { throw (0, _kCreateWebError.kCreateWebError)({ code: -401 + '', isAuthFailed: true, msg: 'this access token does not exist' }); } const body = parseJsonSafely(await response.text()); return { headers: response.headers, ok: response.ok, redirected: response.redirected, status: response.status, statusText: response.statusText, type: response.type, url: response.url, body }; }; }; const kFetch = exports.kFetch = returnFetchJson({}, false); const kFetchFormUrlEncoded = exports.kFetchFormUrlEncoded = returnFetchJson({}, true); //# sourceMappingURL=kFetch.js.map