# @code-exitos/react-native-proxy-client

> test

Latest version **0.1.8** (published 2023-01-23) · MIT license · 0 weekly downloads

## Install

```sh
npm install @code-exitos/react-native-proxy-client
pnpm add @code-exitos/react-native-proxy-client
yarn add @code-exitos/react-native-proxy-client
bun add @code-exitos/react-native-proxy-client
```

## Health

**Score 30/100 (F)** — status: abandoned.

Positive: has types; esm support; no vulnerabilities; high quality score.

Warnings: low downloads; pre 1.0.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 0.1.8 |
| Published | 2023-01-23 |
| First published | 2023-01-09 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | ESM + CommonJS |
| Node | >= 14.21.0 |
| Dependencies | 1 |
| Unpacked size | 457.7 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Author | Darwin Luque |
| Maintainers | detroitpro, je-martinez, darwinluque, codexitos-dev |
| Keywords | react-native, ios, android |

## Links

- npm: https://www.npmjs.com/package/@code-exitos/react-native-proxy-client
- Repository: https://github.com/code-exitos/react-native-proxy-client
- Homepage: https://github.com/code-exitos/react-native-proxy-client#readme
- Issues: https://github.com/code-exitos/react-native-proxy-client/issues
- npm.io page: https://npm.io/package/@code-exitos/react-native-proxy-client

## Dependencies (1)

- [base64-js](https://npm.io/package/base64-js.md) ^1.5.1

## Alternatives

- [@sindresorhus/slugify](https://npm.io/package/@sindresorhus/slugify.md) — 3.7M weekly downloads
- [solid-js](https://npm.io/package/solid-js.md) — 2.7M weekly downloads
- [expo-glass-effect](https://npm.io/package/expo-glass-effect.md) — 2.5M weekly downloads
- [nanoassert](https://npm.io/package/nanoassert.md) — 780.8K weekly downloads
- [@ffmpeg/ffmpeg](https://npm.io/package/@ffmpeg/ffmpeg.md) — 529.5K weekly downloads

## Recent versions

- 0.1.8 (latest) — 2023-01-23
- 0.1.7 — 2023-01-23
- 0.1.6 — 2023-01-17
- 0.1.5 — 2023-01-17
- 0.1.4 — 2023-01-11
- 0.1.3 — 2023-01-11
- 0.1.2 — 2023-01-11
- 0.1.1 — 2023-01-11
- 0.1.0 — 2023-01-10
- 0.0.5 — 2023-01-09
- 0.0.4 — 2023-01-09
- 0.0.3 — 2023-01-09
- 0.0.2 — 2023-01-09
- 0.0.1 — 2023-01-09

## README

# @code-exitos/react-native-proxy-client

This is a framework to interact with server-side applications that are accessible through proxies for React Native.

## Installation

### Installing the package

**Using _npm_**:

```sh
npm install @code-exitos/react-native-proxy-client
```

**Using _yarn_**:

```sh
yarn add @code-exitos/react-native-proxy-client
```

**Using _pnpm_**:

```sh
pnpm add @code-exitos/react-native-proxy-client
```

### Installing the pod

```sh
npx pod-install

# or

cd ios && pod install
```

## About

This package offers a series of module that allows the implementation of different type of clients. The modules are:

- `ProxyClient`: the module offers a class with a set of methods to make the basic HTTP requests.
- `ProxyEventSource`: the module offers a class that enables methods to connect and listen to events sent by a Server-Sent Events.
- `ProxyWebSocket`: the module offers a class that enables methods to connect and listen to events sent by a WebSocket. This module can be configured to use raw WebSocket or Socket.IO.
  `ProxyFileManager`: the module offers a class that enables methods to upload and download files.

> ### Note
>
> All of the modules can be configured to use a proxy to perform their respective task.

## API

The following guide provides a brief overview of the usage and an example of the modules.

### ProxyClient

The `ProxyClient` module offers a class with a set of methods to make basic HTTP requests. The class can be configured to use a proxy to perform the requests.

#### get

The `get` method allows performing GET requests to a server.

**Parameters:**

| Name       | Type                                  | Description                  |
| :--------- | :------------------------------------ | :--------------------------- |
| `endpoint` | `string`                              | The endpoint of the request. |
| `options`  | [`IRequestOptions`](#irequestoptions) | The options of the request.  |

**Returns:** `Promise<[IClientResponse](#iclientresponse)>`

**Example:**

```ts
import { ProxyClient } from '@code-exitos/react-native-proxy-client';

const proxyClient = new ProxyClient();

const response = await proxyClient.get('https://example.com', {
  headers: {
    'Content-Type': 'application/json',
  },
  query: {
    foo: 'bar',
  },
  timeout: 10000,
  retries: 3,
  proxy: {
    host: 'localhost',
    port: 8080,
  },
});
```

#### post

The `post` method allows performing POST requests to a server.

**Parameters:**

| Name       | Type                                  | Description                  |
| :--------- | :------------------------------------ | :--------------------------- |
| `endpoint` | `string`                              | The endpoint of the request. |
| `body`     | `any`                                 | The body of the request.     |
| `options`  | [`IRequestOptions`](#irequestoptions) | The options of the request.  |

**Returns:** `Promise<[IClientResponse](#iclientresponse)>`

**Example:**

```ts
import { ProxyClient } from '@code-exitos/react-native-proxy-client';

const proxyClient = new ProxyClient();

const response = await proxyClient.post(
  'https://example.com',
  {
    foo: 'bar',
  },
  {
    headers: {
      'Content-Type': 'application/json',
    },
    query: {
      foo: 'bar',
    },
    timeout: 10000,
    retries: 3,
    proxy: {
      host: 'localhost',
      port: 8080,
    },
  }
);
```

#### put

The `put` method allows performing PUT requests to a server.

**Parameters:**

| Name       | Type                                  | Description                  |
| :--------- | :------------------------------------ | :--------------------------- |
| `endpoint` | `string`                              | The endpoint of the request. |
| `body`     | `any`                                 | The body of the request.     |
| `options`  | [`IRequestOptions`](#irequestoptions) | The options of the request.  |

**Returns:** `Promise<[IClientResponse](#iclientresponse)>`

**Example:**

```ts
import { ProxyClient } from '@code-exitos/react-native-proxy-client';

const proxyClient = new ProxyClient();

const response = await proxyClient.put(
  'https://example.com',
  {
    foo: 'bar',
  },
  {
    headers: {
      'Content-Type': 'application/json',
    },
    query: {
      foo: 'bar',
    },
    timeout: 10000,
    retries: 3,
    proxy: {
      host: 'localhost',
      port: 8080,
    },
  }
);
```

#### patch

The `patch` method allows performing PATCH requests to a server.

**Parameters:**

| Name       | Type                                  | Description                  |
| :--------- | :------------------------------------ | :--------------------------- |
| `endpoint` | `string`                              | The endpoint of the request. |
| `body`     | `any`                                 | The body of the request.     |
| `options`  | [`IRequestOptions`](#irequestoptions) | The options of the request.  |

**Returns:** `Promise<[IClientResponse](#iclientresponse)>`

**Example:**

```ts
import { ProxyClient } from '@code-exitos/react-native-proxy-client';

const proxyClient = new ProxyClient();

const response = await proxyClient.patch(
  'https://example.com',
  {
    foo: 'bar',
  },
  {
    headers: {
      'Content-Type': 'application/json',
    },
    query: {
      foo: 'bar',
    },
    timeout: 10000,
    retries: 3,
    proxy: {
      host: 'localhost',
      port: 8080,
    },
  }
);
```

#### delete

The `delete` method allows performing DELETE requests to a server.

**Parameters:**

| Name       | Type                                  | Description                  |
| :--------- | :------------------------------------ | :--------------------------- |
| `endpoint` | `string`                              | The endpoint of the request. |
| `options`  | [`IRequestOptions`](#irequestoptions) | The options of the request.  |

**Returns:** `Promise<[IClientResponse](#iclientresponse)>`

**Example:**

```ts
import { ProxyClient } from '@code-exitos/react-native-proxy-client';

const proxyClient = new ProxyClient();

const response = await proxyClient.delete('https://example.com', {
  headers: {
    'Content-Type': 'application/json',
  },
  query: {
    foo: 'bar',
  },
  timeout: 10000,
  retries: 3,
  proxy: {
    host: 'localhost',
    port: 8080,
  },
});
```

### ProxyEventSource

The `ProxyEventSource` module offers a class that allows to create a connection and listen to events on a given endpoint. The class can be configured to use a proxy to perform the requests.

> **Note:** The `ProxyEventSource` module has a pending work in progress. We need to assign a unique id per so that we can manage multiple instances.

#### Constructor

The `ProxyEventSource` class can be instantiated with the following parameters:

| Name       | Type                              | Description                  |
| :--------- | :-------------------------------- | :--------------------------- |
| `endpoint` | `string`                          | The endpoint of the request. |
| `headers`  | `Record<string, any>`             | The options of the request.  |
| `options`  | [`IProxyOptions`](#iproxyoptions) | The options of the request.  |

**Example:**

```ts
import { ProxyEventSource } from '@code-exitos/react-native-proxy-client';

const proxyEventSource = new ProxyEventSource(
  'https://example.com/sse',
  {
    Authorization: 'Bearer your-token-goes-here',
  },
  {
    host: 'localhost',
    port: 8080,
  }
);
```

#### addEventListener

The `addEventListener` method allows to add a custom listener to the event source.

**Parameters:**

| Name       | Type                                                          | Description                  |
| :--------- | :------------------------------------------------------------ | :--------------------------- |
| `event`    | `string`                                                      | The event of the request.    |
| `listener` | [`EventSourceListenerCallback`](#eventsourcelistenercallback) | The listener of the request. |

**Returns:** `void`

**Example:**

```ts
import { ProxyEventSource } from '@code-exitos/react-native-proxy-client';

const proxyEventSource = new ProxyEventSource('https://example.com/sse');

proxyEventSource.addEventListener('custom-event', (id, event, data) => {
  console.log({ id, event, data });
});
```

#### removeEventListener

The `removeEventListener` method allows to remove a custom listener from the event source.

**Parameters:**

| Name    | Type     | Description               |
| :------ | :------- | :------------------------ |
| `event` | `string` | The event of the request. |

**Returns:** `void`

**Example:**

```ts
import { ProxyEventSource } from '@code-exitos/react-native-proxy-client';

const proxyEventSource = new ProxyEventSource('https://example.com/sse');

proxyEventSource.removeEventListener('custom-event');
```

#### onMessage

The `onMessage` method allows to add a listener to the `message` event of the event source.

**Parameters:**

| Name                | Type                                                          | Description                  |
| :------------------ | :------------------------------------------------------------ | :--------------------------- |
| `onMessageCallback` | [`EventSourceListenerCallback`](#eventsourcelistenercallback) | The listener of the request. |

**Returns:** `void`

**Example:**

```ts
import { ProxyEventSource } from '@code-exitos/react-native-proxy-client';

const proxyEventSource = new ProxyEventSource('https://example.com/sse');

proxyEventSource.onMessage((id, event, data) => {
  console.log({ id, event, data });
});
```

#### onOpen

The `onOpen` method allows to add a listener to the `open` event of the event source.

**Parameters:**

| Name             | Type         | Description                  |
| :--------------- | :----------- | :--------------------------- |
| `onOpenCallback` | `() => void` | The listener of the request. |

**Returns:** `void`

**Example:**

```ts
import { ProxyEventSource } from '@code-exitos/react-native-proxy-client';

const proxyEventSource = new ProxyEventSource('https://example.com/sse');

proxyEventSource.onOpen(() => {
  console.log('Connection opened');
});
```

#### onComplete

The `onComplete` method allows to add a listener when the connection has ended.

**Parameters:**

| Name                 | Type                                                          | Description                  |
| :------------------- | :------------------------------------------------------------ | :--------------------------- |
| `onCompleteCallback` | [`EventSourceCompleteCallback`](#eventsourcecompletecallback) | The listener of the request. |

**Returns:** `void`

**Example:**

```ts
import { ProxyEventSource } from '@code-exitos/react-native-proxy-client';

const proxyEventSource = new ProxyEventSource('https://example.com/sse');

proxyEventSource.onComplete((error, statusCode, shouldReconnect) => {
  console.log({ error, statusCode, shouldReconnect });
});
```

#### disconnect

The `disconnect` method allows to disconnect the connection.

**Returns:** `void`

**Example:**

```ts
import { ProxyEventSource } from '@code-exitos/react-native-proxy-client';

const proxyEventSource = new ProxyEventSource('https://example.com/sse');

proxyEventSource.disconnect();
```

### ProxyFileManager

The `ProxyFileManager` module offers a class that enables methods to upload and download files.

#### upload

The `upload` method allows to upload a file to a remote server. The method is hardcoded to use the `POST` method and a `Content-Type` of `multipart/form-data`.

**Parameters:**

| Name       | Type                                          | Description                  |
| :--------- | :-------------------------------------------- | :--------------------------- |
| `endpoint` | `string`                                      | The endpoint of the request. |
| `file`     | `FormData`                                    | The file to be uploaded.     |
| `options`  | [`IFileRequestOptions`](#ifilerequestoptions) | The options of the request.  |

**Returns:** `Promise<[IClientResponse](#iclientresponse)<T>>`

**Example:**

```ts
import { ProxyFileManager } from '@code-exitos/react-native-proxy-client';
import { FormData, FileData } from '@code-exitos/react-native-proxy-client';

const formData = new FormData();

formData.append('key', 'value');
formData.append(
  'file',
  new FileData(
    'file.txt',
    'text/plain',
    123455,
    '/file.txt',
    'file:///file.txt'
  )
);

const proxyFileManager = new ProxyFileManager();

proxyFileManager.upload('https://example.com/upload', formData, {
  headers: {
    Authorization: 'Bearer your-token-goes-here',
  },
});
```

#### download

The `download` method allows to download a file from a remote server. The method is hardcoded to use the `GET` method.

**Parameters:**

| Name      | Type                                          | Description                 |
| :-------- | :-------------------------------------------- | :-------------------------- |
| `from`    | `string`                                      | The endpoint of the file.   |
| `to`      | `string`                                      | The path to save the file.  |
| `options` | [`IFileRequestOptions`](#ifilerequestoptions) | The options of the request. |

**Returns:** `Promise<[IClientResponse](#iclientresponse)<T>>`

**Example:**

```ts
import { ProxyFileManager } from '@code-exitos/react-native-proxy-client';

const proxyFileManager = new ProxyFileManager();

const res = await proxyFileManager.download(
  'https://example.com/file.txt',
  '/file.txt',
  {
    headers: {
      Authorization: 'Bearer your-token-goes-here',
    },
  }
);

const path = res.data;
```

### FormData

The `FormData` class enables an alternative to the native JS `FormData` API. The problem that we have with this native class is that is to unpredictable as to what data is being appended to it.

To fix this, we created are own custom form data class that enforces the data that we can handle on the module.

The data that can be appended to the form data is:

- `string`
- [`FileData`](#filedata)

#### append

The `append` method allows to append data to the form data.

**Parameters:**

| Name   | Type                                | Description              |
| :----- | :---------------------------------- | :----------------------- |
| `key`  | `string`                            | The key of the data.     |
| `data` | `string` \| [`FileData`](#filedata) | The data to be appended. |

**Returns:** `void`

**Example:**

```ts
import { FormData, FileData } from '@code-exitos/react-native-proxy-client';

const formData = new FormData();

formData.append('key', 'value');
formData.append(
  'file',
  new FileData(
    'file.txt',
    'text/plain',
    123455,
    '/file.txt',
    'file:///file.txt'
  )
);
```

#### FormData.delete

The `delete` method allows to delete a key from the form data.

**Parameters:**

| Name  | Type     | Description          |
| :---- | :------- | :------------------- |
| `key` | `string` | The key of the data. |

**Returns:** `void`

**Example:**

```ts
import { FormData } from '@code-exitos/react-native-proxy-client';

const formData = new FormData();

formData.append('key', 'value');

formData.delete('key');
```

#### FormData.get

The `get` method allows to get the data of a key from the form data.

**Parameters:**

| Name  | Type     | Description          |
| :---- | :------- | :------------------- |
| `key` | `string` | The key of the data. |

**Returns:** `string` \| [`FileData`](#filedata)

**Example:**

```ts
import { FormData, FileData } from '@code-exitos/react-native-proxy-client';

const formData = new FormData();

formData.append('key', 'value');

const data = formData.get('key');
```

#### getAll

The `getAll` method allows to get all the data from the form data.

**Returns:** `Array<string \| FileData>`

**Example:**

```ts
import { FormData, FileData } from '@code-exitos/react-native-proxy-client';

const formData = new FormData();

formData.append('key', 'value');
formData.append(
  'file',
  new FileData(
    'file.txt',
    'text/plain',
    123455,
    '/file.txt',
    'file:///file.txt'
  )
);

const data = formData.getAll();
```

#### has

The `has` method allows to check if the form data has a key.

**Parameters:**

| Name  | Type     | Description          |
| :---- | :------- | :------------------- |
| `key` | `string` | The key of the data. |

**Returns:** `boolean`

**Example:**

```ts
import { FormData } from '@code-exitos/react-native-proxy-client';

const formData = new FormData();

formData.append('key', 'value');

const hasKey = formData.has('key');
```

#### value

The `value` getter exposes the value of the form data in the form of an object.

**Returns:** `Record<string, string \| FileData>`

```ts
import { FormData, FileData } from '@code-exitos/react-native-proxy-client';

const formData = new FormData();

formData.append('key', 'value');
formData.append(
  'file',
  new FileData(
    'file.txt',
    'text/plain',
    123455,
    '/file.txt',
    'file:///file.txt'
  )
);

const data = formData.value;
```

#### FileData

The `FileData` class defines an instance of the data that is going to be used to upload a file. The class implements the [`IFileData`](#ifiledata) interface.

### ProxySocket

The `ProxySocket` module offers a class that enables methods to connect to a remote server via a socket. The module can be configured to use either raw WebSockets or Socket.IO.

> **Note**
> The module doesn't work completely when applying proxies.
> | OS | Raw WebSockets with proxy | Socket.IO with proxy | Raw WebSockets without proxy | Socket.IO without proxy |
> | :--- | :--- | :--- | :--- | :--- |
> | Android | ❌ | ✅ | ✅ | ✅ |
> | iOS | ❌ | ❌ | ✅ | ✅ |

### General Typings

#### IProxyOptions

The `IProxyOptions` interface defines the options that can be used to configure the proxies.

| Property | Type                                      | Description                           |
| :------- | :---------------------------------------- | :------------------------------------ |
| `host`   | `string`                                  | The host of the proxy.                |
| `port`   | `number`                                  | The port of the proxy.                |
| `auth`   | [`IProxyAuthOptions`](#iproxyauthoptions) | The authentication info of the proxy. |

##### IProxyAuthOptions

The `IProxyAuthOptions` interface defines the options that can be used to configure the authentication of the proxies.

| Property   | Type     | Description                |
| :--------- | :------- | :------------------------- |
| `username` | `string` | The username of the proxy. |
| `password` | `string` | The password of the proxy. |

#### IRequestOptions

The `IRequestOptions` interface defines the options that can be used to configure the requests.

| Property  | Type                              | Description                           |
| :-------- | :-------------------------------- | :------------------------------------ |
| `headers` | `Record<string, any>`             | The headers of the request.           |
| `query`   | `Record<string, any>`             | The query parameters of the request.  |
| `timeout` | `number`                          | The timeout of the request.           |
| `retries` | `number`                          | The number of retries of the request. |
| `proxy`   | [`IProxyOptions`](#iproxyoptions) | The proxy of the request.             |
| `body`    | `any`                             | The body of the request.              |

#### IClientResponse

The `IClientResponse` interface defines the response to the requests.

| Property     | Type                  | Description                          |
| :----------- | :-------------------- | :----------------------------------- |
| `data`       | `T`                   | The data of the response.            |
| `statusCode` | `number`              | The status of the response.          |
| `headers`    | `Record<string, any>` | The headers of the response.         |
| `endpoint`   | `string`              | The endpoint of the response.        |
| `method`     | `string`              | The method of the response.          |
| `query`      | `Record<string, any>` | The query parameters of the request. |

#### EventSourceListenerCallback

The `EventSourceListenerCallback` interface defines the callback that will be called when an event is received.

**Parameters:**

| Property | Type     | Description            |
| :------- | :------- | :--------------------- |
| `id`     | `string` | The id of the event.   |
| `event`  | `string` | The name of the event. |
| `data`   | `string` | The data of the event. |

**Returns:** `void`

#### EventSourceCompleteCallback

The `EventSourceCompleteCallback` interface defines the callback that will be called when the connection is closed.

**Parameters:**

| Property          | Type      | Description                                                |
| :---------------- | :-------- | :--------------------------------------------------------- |
| `error`           | `Error`   | The possible error of the reason why the connection ended. |
| `statusCode`      | `number`  | The status code of the response.                           |
| `shouldReconnect` | `boolean` | Whether the connection should be reconnected.              |

**Returns:** `void`

#### SocketType

The `SocketType` enum defines the different types of sockets that can be used to perform the requests.

**Values:**

- `SocketIO` = `'socket.io'`
- `WS` = `'ws'`

#### ISocketOptions

The `ISocketOptions` interface defines the options that can be used to configure the sockets.

| Property               | Type                  | Description                                           |
| :--------------------- | :-------------------- | :---------------------------------------------------- |
| `type`                 | `string`              | The type of the socket.                               |
| `headers`              | `Record<string, any>` | The headers of the socket.                            |
| `query`                | `Record<string, any>` | The query parameters of the socket.                   |
| `autoConnect`          | `boolean`             | Whether the socket should be connected automatically. |
| `timeout`              | `number`              | The timeout of the socket.                            |
| `reconnection`         | `boolean`             | Whether the socket should be reconnected.             |
| `reconnectionAttempts` | `number`              | The number of reconnection attempts.                  |
| `reconnectionDelay`    | `number`              | The delay of the reconnection.                        |

#### SocketEmitErrorCallback

The `SocketEmitErrorCallback` interface defines the callback that will be called when an error is received.

**Parameters:**

| Property | Type     | Description                            |
| :------- | :------- | :------------------------------------- |
| `args`   | `object` | The arguments with the possible error. |

**Returns:** `void`

#### SocketOnEventListenerCallback

The `SocketOnEventListenerCallback` interface defines the callback that will be called when an event is received.

**Parameters:**

| Property | Type     | Description                  |
| :------- | :------- | :--------------------------- |
| `args`   | `object` | The data sent by the emitter |

**Returns:** `void`

#### IFileData

The `IFileData` interface defines the data that can be used to create a file.

| Property   | Type     | Description                |
| :--------- | :------- | :------------------------- |
| `filename` | `string` | The name of the file.      |
| `mimetype` | `string` | The mime type of the file. |
| `size`     | `number` | The size of the file.      |
| `path`     | `string` | The path of the file.      |
| `uri`      | `string` | The uri of the file.       |

#### IFileRequestOptions

The `IFileRequestOptions` interface defines the options that can be used to configure the file requests.

| Property  | Type                              | Description                           |
| :-------- | :-------------------------------- | :------------------------------------ |
| `headers` | `Record<string, any>`             | The headers of the request.           |
| `query`   | `Record<string, any>`             | The query parameters of the request.  |
| `timeout` | `number`                          | The timeout of the request.           |
| `retries` | `number`                          | The number of retries of the request. |
| `proxy`   | [`IProxyOptions`](#iproxyoptions) | The proxy of the request.             |

## Contributing

See the [contributing guide](CONTRIBUTING.md) to learn how to contribute to the repository and the development workflow.

## License

MIT

---

Made with [create-react-native-library](https://github.com/callstack/react-native-builder-bob)

---
_Source: https://npm.io/package/@code-exitos/react-native-proxy-client · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
