0.1.8 • Published 1 year ago

@code-exitos/react-native-proxy-client v0.1.8

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

@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:

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

Using yarn:

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

Using pnpm:

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

Installing the pod

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:

NameTypeDescription
endpointstringThe endpoint of the request.
optionsIRequestOptionsThe options of the request.

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

Example:

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:

NameTypeDescription
endpointstringThe endpoint of the request.
bodyanyThe body of the request.
optionsIRequestOptionsThe options of the request.

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

Example:

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:

NameTypeDescription
endpointstringThe endpoint of the request.
bodyanyThe body of the request.
optionsIRequestOptionsThe options of the request.

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

Example:

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:

NameTypeDescription
endpointstringThe endpoint of the request.
bodyanyThe body of the request.
optionsIRequestOptionsThe options of the request.

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

Example:

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:

NameTypeDescription
endpointstringThe endpoint of the request.
optionsIRequestOptionsThe options of the request.

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

Example:

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:

NameTypeDescription
endpointstringThe endpoint of the request.
headersRecord<string, any>The options of the request.
optionsIProxyOptionsThe options of the request.

Example:

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:

NameTypeDescription
eventstringThe event of the request.
listenerEventSourceListenerCallbackThe listener of the request.

Returns: void

Example:

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:

NameTypeDescription
eventstringThe event of the request.

Returns: void

Example:

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:

NameTypeDescription
onMessageCallbackEventSourceListenerCallbackThe listener of the request.

Returns: void

Example:

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:

NameTypeDescription
onOpenCallback() => voidThe listener of the request.

Returns: void

Example:

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:

NameTypeDescription
onCompleteCallbackEventSourceCompleteCallbackThe listener of the request.

Returns: void

Example:

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:

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:

NameTypeDescription
endpointstringThe endpoint of the request.
fileFormDataThe file to be uploaded.
optionsIFileRequestOptionsThe options of the request.

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

Example:

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:

NameTypeDescription
fromstringThe endpoint of the file.
tostringThe path to save the file.
optionsIFileRequestOptionsThe options of the request.

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

Example:

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:

append

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

Parameters:

NameTypeDescription
keystringThe key of the data.
datastring | FileDataThe data to be appended.

Returns: void

Example:

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:

NameTypeDescription
keystringThe key of the data.

Returns: void

Example:

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:

NameTypeDescription
keystringThe key of the data.

Returns: string | FileData

Example:

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:

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:

NameTypeDescription
keystringThe key of the data.

Returns: boolean

Example:

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>

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 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.

PropertyTypeDescription
hoststringThe host of the proxy.
portnumberThe port of the proxy.
authIProxyAuthOptionsThe authentication info of the proxy.
IProxyAuthOptions

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

PropertyTypeDescription
usernamestringThe username of the proxy.
passwordstringThe password of the proxy.

IRequestOptions

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

PropertyTypeDescription
headersRecord<string, any>The headers of the request.
queryRecord<string, any>The query parameters of the request.
timeoutnumberThe timeout of the request.
retriesnumberThe number of retries of the request.
proxyIProxyOptionsThe proxy of the request.
bodyanyThe body of the request.

IClientResponse

The IClientResponse interface defines the response to the requests.

PropertyTypeDescription
dataTThe data of the response.
statusCodenumberThe status of the response.
headersRecord<string, any>The headers of the response.
endpointstringThe endpoint of the response.
methodstringThe method of the response.
queryRecord<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:

PropertyTypeDescription
idstringThe id of the event.
eventstringThe name of the event.
datastringThe data of the event.

Returns: void

EventSourceCompleteCallback

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

Parameters:

PropertyTypeDescription
errorErrorThe possible error of the reason why the connection ended.
statusCodenumberThe status code of the response.
shouldReconnectbooleanWhether 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.

PropertyTypeDescription
typestringThe type of the socket.
headersRecord<string, any>The headers of the socket.
queryRecord<string, any>The query parameters of the socket.
autoConnectbooleanWhether the socket should be connected automatically.
timeoutnumberThe timeout of the socket.
reconnectionbooleanWhether the socket should be reconnected.
reconnectionAttemptsnumberThe number of reconnection attempts.
reconnectionDelaynumberThe delay of the reconnection.

SocketEmitErrorCallback

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

Parameters:

PropertyTypeDescription
argsobjectThe arguments with the possible error.

Returns: void

SocketOnEventListenerCallback

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

Parameters:

PropertyTypeDescription
argsobjectThe data sent by the emitter

Returns: void

IFileData

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

PropertyTypeDescription
filenamestringThe name of the file.
mimetypestringThe mime type of the file.
sizenumberThe size of the file.
pathstringThe path of the file.
uristringThe uri of the file.

IFileRequestOptions

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

PropertyTypeDescription
headersRecord<string, any>The headers of the request.
queryRecord<string, any>The query parameters of the request.
timeoutnumberThe timeout of the request.
retriesnumberThe number of retries of the request.
proxyIProxyOptionsThe proxy of the request.

Contributing

See the contributing guide to learn how to contribute to the repository and the development workflow.

License

MIT


Made with create-react-native-library

0.1.8

1 year ago

0.1.7

1 year ago

0.1.6

1 year ago

0.1.5

1 year ago

0.1.4

1 year ago

0.1.3

1 year ago

0.1.2

1 year ago

0.1.1

1 year ago

0.1.0

1 year ago

0.0.5

1 year ago

0.0.4

1 year ago

0.0.3

1 year ago

0.0.2

1 year ago

0.0.1

1 year ago