@react-native-kakao/core
Version:
React Native Kakao Core SDK
61 lines (57 loc) • 2.13 kB
JavaScript
import returnFetch from 'return-fetch';
import { kCreateWebError } from './kCreateWebError';
// 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 = returnFetch(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 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
};
};
};
export const kFetch = returnFetchJson({}, false);
export const kFetchFormUrlEncoded = returnFetchJson({}, true);
//# sourceMappingURL=kFetch.js.map