Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { AsyncStorage } from 'react-native';
- import jsrsasign from 'jsrsasign';
- import HttpError from './HttpError';
- import { Alert } from 'react-native';
- export default async function request(url, body = {}, params = {}, type = 'POST') {
- const pubKey = await AsyncStorage.getItem('@EncryptStore:publicKey');
- const privateKey = await AsyncStorage.getItem('@EncryptStore:privateKey');
- let token = await AsyncStorage.getItem('@TopUpStore:Token');
- token = token ? token : '';
- if (pubKey === null || privateKey === null) {
- return;
- }
- params.token = token;
- url += (url.indexOf('?') === -1 ? '?' : '&') + queryParams(params);
- const bodyString = type === 'POST' || type === 'DELETE' ? JSON.stringify(body) : '';
- const signature = jsrsasign.KJUR.crypto.Util.md5(pubKey);
- const sig = new jsrsasign.KJUR.crypto.Signature({ alg: 'SHA256withRSA' });
- sig.init(privateKey);
- sig.updateString(bodyString);
- const sigValueHex = sig.sign();
- const base64Sign = jsrsasign.hextob64(sigValueHex);
- const post = {
- method: type,
- headers: {
- Accept: 'application/json',
- 'Content-Type': 'application/json',
- Sign: base64Sign,
- Signature: signature
- },
- };
- if (type === 'POST' || type === 'DELETE') post.body = bodyString;
- LOG('\n===== START HTTP REQUEST =====');
- LOG(`HTTP send url: ${url}`);
- LOG(`HTTP send body: ${bodyString}`);
- const response = await fetch(url, post);
- const responseStatus = await response.status;
- LOG(`HTTP response code: ${responseStatus}`);
- if (responseStatus !== 200) {
- const responseBody = await response.json();
- let errorText = '';
- if (responseBody.Message !== undefined) {
- errorText = responseBody.Message;
- }
- if (responseBody.ModelState !== undefined) {
- if (Object.keys(responseBody.ModelState)[0]) {
- errorText =
- responseBody.ModelState[Object.keys(responseBody.ModelState)[0]][0];
- }
- }
- LOG(`HTTP error body: ${JSON.stringify(responseBody)}`);
- LOG('===== END HTTP REQUEST =====\n');
- Alert.alert('Error', errorText);
- throw new HttpError(errorText);
- }
- LOG(`HTTP response code: ${responseStatus}`);
- LOG('===== END HTTP REQUEST =====\n');
- return response;
- }
- function queryParams(params) {
- return Object.keys(params)
- .map(k => encodeURIComponent(k) + '=' + encodeURIComponent(params[k]))
- .join('&');
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement