@powersync/react-native
Version:
PowerSync React Native SDK. Sync Postgres, MongoDB or MySQL with SQLite in your React Native app
67 lines (66 loc) • 2.62 kB
JavaScript
import { AbstractRemote, DEFAULT_REMOTE_LOGGER, FetchImplementationProvider } from '@powersync/common';
import { Platform } from 'react-native';
// Note docs for React Native https://github.com/mongodb/js-bson?tab=readme-ov-file#react-native
import { BSON } from 'bson';
import { fetch } from 'react-native-fetch-api';
export const STREAMING_POST_TIMEOUT_MS = 30_000;
/**
* Directly imports fetch implementation from react-native-fetch-api.
* This removes the requirement for the global `fetch` to be overridden by
* a polyfill.
*/
class ReactNativeFetchProvider extends FetchImplementationProvider {
getFetch() {
return fetch.bind(globalThis);
}
}
export class ReactNativeRemote extends AbstractRemote {
connector;
logger;
constructor(connector, logger = DEFAULT_REMOTE_LOGGER, options) {
super(connector, logger, {
...(options ?? {}),
fetchImplementation: options?.fetchImplementation ?? new ReactNativeFetchProvider()
});
this.connector = connector;
this.logger = logger;
}
getUserAgent() {
return [
super.getUserAgent(),
`powersync-react-native`,
`react-native/${Platform.constants.reactNativeVersion.major}.${Platform.constants.reactNativeVersion.minor}`,
`${Platform.OS}/${Platform.Version}`
].join(' ');
}
async getBSON() {
return BSON;
}
async postStreamRaw(options, mapLine) {
const timeout = Platform.OS == 'android'
? setTimeout(() => {
this.logger.warn(`HTTP Streaming POST is taking longer than ${Math.ceil(STREAMING_POST_TIMEOUT_MS / 1000)} seconds to resolve. If using a debug build, please ensure Flipper Network plugin is disabled.`);
}, STREAMING_POST_TIMEOUT_MS)
: null;
try {
return await super.postStreamRaw({
...options,
fetchOptions: {
...options.fetchOptions,
/**
* The `react-native-fetch-api` polyfill provides streaming support via
* this non-standard flag
* https://github.com/react-native-community/fetch#enable-text-streaming
*/
// @ts-expect-error https://github.com/react-native-community/fetch#enable-text-streaming
reactNative: { textStreaming: true }
}
}, mapLine);
}
finally {
if (timeout) {
clearTimeout(timeout);
}
}
}
}