google-translate-api icon indicating copy to clipboard operation
google-translate-api copied to clipboard

Is proxying supported in react native?

Open Seu07 opened this issue 3 months ago • 1 comments

this "https-proxy-agent" is not support with react native. Could you give any suggestions?

Seu07 avatar Mar 22 '24 01:03 Seu07

@Seu07 I'm not very experienced with react native, but I'm pretty sure react-native-blob-util can be used to polyfill xhr requests with trusty: true then you can do something like this with Axios:

import { translate } from 'google-translate-api-x';
import axios from 'axios';

function proxiedFetch(url, init) {
	// we essentially need to emulate fetch behavior with axios
	const axiosOptions = init.requestOptions ?? {};

	axiosOptions.data = axiosOptions.body; // axios calls the `body` in fetch `data`

	axiosOptions.proxy = {
		protocol: 'https',
		host: PROXY_URL,
		port: '5353', // or whatever port
		auth: { // if your proxy needs it
			username: PROXY_USERNAME,
			password: PROXY_PASSWORD,
		},
	};

	axios.transformResponse = res => res; // prevent axios from parsing json by default

	return axios(url, axiosOptions).then(res => {
		if (res.status >= 200 && res.status < 300) {
			res.ok = true;
		} else {
			res.ok = false;
		}

		res.text = () => res.data;
		res.json = () => JSON.parse(res.data);

		return res;
	});
}

const res = await translate('cat', {from: 'en', to: 'es', requestFunction: proxiedFetch});
console.log(res);

Please let me know if you get it to work!

AidanWelch avatar Mar 27 '24 12:03 AidanWelch