Skip to content

Commit

Permalink
add: checkInternetConnection, configure method type
Browse files Browse the repository at this point in the history
  • Loading branch information
1ike committed Apr 8, 2020
1 parent d7c5448 commit 8a6a4a7
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 3 deletions.
3 changes: 2 additions & 1 deletion README.md
Expand Up @@ -548,7 +548,8 @@ Utility function that allows you to query for internet connectivity on demand. I
checkInternetConnection(
url?: string = 'https://www.google.com/',
pingTimeout?: number = 10000,
shouldPing?: boolean = true
shouldPing?: boolean = true,
method?: HTTPMethod = 'HEAD'
): Promise<boolean>
```

Expand Down
15 changes: 13 additions & 2 deletions src/utils/checkInternetConnection.ts
@@ -1,22 +1,33 @@
import NetInfo from '@react-native-community/netinfo';
import checkInternetAccess from './checkInternetAccess';
import { DEFAULT_PING_SERVER_URL, DEFAULT_TIMEOUT } from './constants';
import {
DEFAULT_PING_SERVER_URL,
DEFAULT_TIMEOUT,
DEFAULT_HTTP_METHOD,
} from './constants';
import { HTTPMethod } from '../types';

/**
* Utility that allows to query for internet connectivity on demand
* @param url
* @param timeout
* @param shouldPing
* @param method
* @returns {Promise<boolean>}
*/
export default async function checkInternetConnection(
url: string = DEFAULT_PING_SERVER_URL,
timeout: number = DEFAULT_TIMEOUT,
shouldPing = true,
method: HTTPMethod = DEFAULT_HTTP_METHOD,
): Promise<boolean> {
return NetInfo.fetch().then(async connectionState => {
if (shouldPing) {
const hasInternetAccess = await checkInternetAccess({ timeout, url });
const hasInternetAccess = await checkInternetAccess({
timeout,
url,
method,
});
return hasInternetAccess;
}
return connectionState.isConnected;
Expand Down
3 changes: 3 additions & 0 deletions test/checkInternetConnection.test.ts
Expand Up @@ -5,6 +5,7 @@ import checkInternetAccess from '../src/utils/checkInternetAccess';
import {
DEFAULT_PING_SERVER_URL,
DEFAULT_TIMEOUT,
DEFAULT_HTTP_METHOD,
} from '../src/utils/constants';

jest.mock('../src/utils/checkInternetAccess');
Expand All @@ -21,6 +22,7 @@ describe('checkInternetConnection', () => {
it(`calls checkInternetAccess and resolves the promise with its returned value`, async () => {
const isConnected = await checkInternetConnection('foo.com', 3000, true);
expect(checkInternetAccess).toHaveBeenCalledWith({
method: DEFAULT_HTTP_METHOD,
timeout: 3000,
url: 'foo.com',
});
Expand All @@ -43,6 +45,7 @@ describe('checkInternetConnection', () => {
fetch.mockImplementationOnce(() => Promise.resolve({ isConnected: true }));
const isConnected = await checkInternetConnection();
expect(checkInternetAccess).toHaveBeenCalledWith({
method: DEFAULT_HTTP_METHOD,
timeout: DEFAULT_TIMEOUT,
url: DEFAULT_PING_SERVER_URL,
});
Expand Down

0 comments on commit 8a6a4a7

Please sign in to comment.