diff --git a/README.md b/README.md index 9a01913..0705599 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,8 @@ This is the [Pusher Channels](https://pusher.com/channels) React Native client. -For tutorials and more in-depth information about Pusher Channels, visit our [official docs](https://pusher.com/docs/channels). +For tutorials and more in-depth information about Pusher Channels, visit +our [official docs](https://pusher.com/docs/channels). ## Supported Mobile platforms @@ -16,7 +17,8 @@ For tutorials and more in-depth information about Pusher Channels, visit our [of ### Deployment targets - iOS 13.0 and above -- Android 7 and above. Android 6 will require [desugaring](https://developer.android.com/studio/write/java8-support#library-desugaring). +- Android 7 and above. Android 6 will + require [desugaring](https://developer.android.com/studio/write/java8-support#library-desugaring). ## Example Application @@ -37,22 +39,22 @@ a minimal application to connect to a channel and send events. - [Android specific installation](#android-specific-installation) - [Initialization](#initialization) - [Configuration](#configuration) - - [`activityTimeout (double)`](#activitytimeout-double) - - [`apiKey (string)`](#apikey-string) - - [`authEndpoint (string)`](#authendpoint-string) - - [`cluster (string)`](#cluster-string) - - [`useTLS (bool)`](#usetls-bool) + - [`activityTimeout (double)`](#activitytimeout-double) + - [`apiKey (string)`](#apikey-string) + - [`authEndpoint (string)`](#authendpoint-string) + - [`cluster (string)`](#cluster-string) + - [`useTLS (bool)`](#usetls-bool) - [Event Callback parameters](#event-callback-parameters) - - [`onEvent`](#onevent) - - [`onSubscriptionSucceeded`](#onsubscriptionsucceeded) - - [`onSubscriptionError`](#onsubscriptionerror) - - [`onDecryptionFailure`](#ondecryptionfailure) - - [`onSubscriptionCount`](#onsubscriptioncount) - - [`onMemberAdded`](#onmemberadded) - - [`onMemberRemoved`](#onmemberremoved) - - [`onAuthorizer`](#onauthorizer) - - [`onConnectionStateChange`](#onconnectionstatechange) - - [`onError`](#onerror) + - [`onEvent`](#onevent) + - [`onSubscriptionSucceeded`](#onsubscriptionsucceeded) + - [`onSubscriptionError`](#onsubscriptionerror) + - [`onDecryptionFailure`](#ondecryptionfailure) + - [`onSubscriptionCount`](#onsubscriptioncount) + - [`onMemberAdded`](#onmemberadded) + - [`onMemberRemoved`](#onmemberremoved) + - [`onAuthorizer`](#onauthorizer) + - [`onConnectionStateChange`](#onconnectionstatechange) + - [`onError`](#onerror) - [Connection handling](#connection-handling) - [Connecting](#connecting) - [Disconnecting](#disconnecting) @@ -85,7 +87,9 @@ to add the plugin to your `package.json`: ```bash npm install @pusher/pusher-websocket-react-native ``` + or + ```bash yarn add @pusher/pusher-websocket-react-native ``` @@ -110,7 +114,8 @@ pusher-websocket-java dependency. ## Initialization The Pusher class is a singleton that -can be instantiated with `getInstance()`. Then you need to initialize the client with several configuration options. Here is a quick example with several callbacks options: +can be instantiated with `getInstance()`. Then you need to initialize the client with several configuration options. +Here is a quick example with several callbacks options: ```typescript import { @@ -153,26 +158,28 @@ You can subscribe to channels before calling `connect()`. There are a few configuration parameters which can be set for the Pusher client. The following table describes available parameters for each platform: -| parameter | Android | iOS | -| -------------------------- | ------- | --- | -| activityTimeout | ✅ | ✅ | -| apiKey | ✅ | ✅ | -| authEndpoint | ✅ | ✅ | -| cluster | ✅ | ✅ | -| maxReconnectGapInSeconds | ✅ | ✅ | -| maxReconnectionAttempts | ✅ | ✅ | -| pongTimeout | ✅ | ✅ | -| proxy | ✅ | ⬜️ | -| useTLS | ✅ | ✅ | -| authorizerTimeoutInSeconds | ⬜️ | ✅ | +| Parameter | Android | iOS | +|----------------------------|:-------:|:---:| +| activityTimeout | ✅ | ✅ | +| apiKey | ✅ | ✅ | +| authEndpoint | ✅ | ✅ | +| cluster | ✅ | ✅ | +| maxReconnectGapInSeconds | ✅ | ✅ | +| maxReconnectionAttempts | ✅ | ✅ | +| pongTimeout | ✅ | ✅ | +| proxy | ✅ | ⬜️ | +| useTLS | ✅ | ✅ | +| authorizerTimeoutInSeconds | ⬜️ | ✅ | #### `activityTimeout (double)` -If no messages are received after this time period (in seconds), the ping message is sent to check if the connection is still working. The server supplies the default value, low values result in unnecessary traffic. +If no messages are received after this time period (in seconds), the ping message is sent to check if the connection is +still working. The server supplies the default value, low values result in unnecessary traffic. #### `apiKey (string)` -You can get your `APP_KEY` and `APP_CLUSTER` from the the App page on the App Keys section in your [Pusher Channels Dashboard](https://dashboard.pusher.com/) +You can get your `APP_KEY` and `APP_CLUSTER` from the App page on the App Keys section in +your [Pusher Channels Dashboard](https://dashboard.pusher.com/) #### `authEndpoint (string)` @@ -183,7 +190,8 @@ an authorization service](https://pusher.com/docs/channels/server_api/authentica #### `cluster (string)` -Specifies the cluster that pusher-js should connect to. Here's the full list of [Pusher clusters](https://pusher.com/docs/clusters). If you do not specify a cluster, `mt1` will be used by default. +Specifies the cluster that pusher-js should connect to. Here's the full list +of [Pusher clusters](https://pusher.com/docs/clusters). If you do not specify a cluster, `mt1` will be used by default. #### `useTLS (bool)` @@ -191,8 +199,8 @@ Whether or not you would like to use TLS encrypted transport or not, default is #### `authorizerTimeoutInSeconds (double)` -If onAuthorizer callback is not called in Javascript before this time period (in seconds), the authorization for the channel will timeout on the native side. Default value: 10 seconds. iOS only. - +If onAuthorizer callback is not called in Javascript before this time period (in seconds), the authorization for the +channel will time out on the native side. Default value: 10 seconds. iOS only. ## Event Callback parameters @@ -201,7 +209,7 @@ The following functions are callbacks that can be passed to the `init()` method. #### `onEvent` ```typescript -function onEvent(PusherEvent event) { +void function onEvent(event: PusherEvent) { console.log(`onEvent: ${event}`); } ``` @@ -212,47 +220,53 @@ The global event handler will trigger events from any channel. #### `onSubscriptionSucceeded` ```typescript -function onSubscriptionSucceeded(channelName:string, data:any) { +void function onSubscriptionSucceeded(channelName: string, data: any) { console.log(`onSubscriptionSucceeded: ${channelName} data: ${data}`); } ``` -Use this if you want to be informed when a channel has successfully been subscribed to. This is useful if you want to perform actions that are only relevant after a subscription has succeeded. For example, querying the members for presence channel. +Use this if you want to be informed when a channel has successfully been subscribed to. This is useful if you want to +perform actions that are only relevant after a subscription has succeeded. For example, querying the members for +presence channel. #### `onSubscriptionError` ```typescript -function onSubscriptionError(channelName: string, message:string, e:any) { +void function onSubscriptionError(channelName: string, message: string, e: any) { console.log(`onSubscriptionError: ${message} channelName: ${channelName} Exception: ${e}`); } ``` -Use this if you want to be informed of a failed subscription attempt. You can use this to re-attempt the subscription or make a call to a service you use to track errors. +Use this if you want to be informed of a failed subscription attempt. You can use this to re-attempt the subscription or +make a call to a service you use to track errors. #### `onDecryptionFailure` ```typescript -function onDecryptionFailure(event:string, string reason:string) { +void function onDecryptionFailure(event: string, reason: string) { console.log(`onDecryptionFailure: ${event} reason: ${reason}`); } ``` + Used with private channels only. Use this if you want to be notified if any messages fail to decrypt. #### `onSubscriptionCount` ```typescript -function onSubscriptionCount(subscriptionCount:number) { +void function onSubscriptionCount(subscriptionCount: number) { console.log(`onSubscriptionSucceeded: ${subscriptionCount}`); } ``` -is an event that can be manually enabled on the server to count the number of connections that are currently subscribed to a particular channel. They work with all channel types, except presence channels. -See [Counting live users at scale with subscription_count events](https://blog.pusher.com/counting-live-users-at-scale-with-subscription-count-events/) for more information. +is an event that can be manually enabled on the server to count the number of connections that are currently subscribed +to a particular channel. They work with all channel types, except presence channels. +See [Counting live users at scale with subscription_count events](https://blog.pusher.com/counting-live-users-at-scale-with-subscription-count-events/) +for more information. #### `onMemberAdded` ```typescript -function onMemberAdded(channelName:string, member:PusherMember) { +void function onMemberAdded(channelName: string, member: PusherMember) { console.log(`onMemberAdded: ${channelName} member: ${member}`); } ``` @@ -262,7 +276,7 @@ Called when a member is added to the presence channel. #### `onMemberRemoved` ```typescript -function onMemberRemoved(channelName:string, member:PusherMember) { +void function onMemberRemoved(channelName: string, member: PusherMember) { console.log(`onMemberRemoved: ${channelName} member: ${member}`); } ``` @@ -271,11 +285,12 @@ Called when a member is removed from the presence channel. #### `onAuthorizer` -When passing the `onAuthorizer()` callback to the `init()` method, this callback is called to request auth information. Learn how +When passing the `onAuthorizer()` callback to the `init()` method, this callback is called to request auth information. +Learn how to [generate the correct auth signatures](https://pusher.com/docs/channels/library_auth_reference/auth-signatures/) ```typescript -async function onAuthorizer(channelName:string, socketId:string):Promise { +void async function onAuthorizer(channelName: string, socketId: string): Promise { return { auth: "foo:bar", channel_data: '{"user_id": 1}', @@ -287,7 +302,7 @@ async function onAuthorizer(channelName:string, socketId:string):Promise { console.log(`Subscribed to ${channelName}`); - console.log(`I can now access me: ${myChannel.me}`) - console.log(`And here are the channel members: ${myChannel.members}`) + console.log(`I can now access me: ${myChannel.me}`); + console.log(`And here are the channel members: ${myChannel.members}`); }, onMemberAdded: (member) => { console.log(`Member added: ${member}`); @@ -434,19 +468,25 @@ const myChannel = await pusher.subscribe( onEvent: (event) => { console.log(`Event received: ${event}`); }, -); +}); ``` -Note that both private and presence channels require the user to be authenticated to subscribe to the channel. This authentication can either happen inside the library if you configured your Pusher object with your app's secret, or an authentication request is made to an authentication endpoint that you provide, again when initializing your Pusher object. +Note that both private and presence channels require the user to be authenticated to subscribe to the channel. This +authentication can either happen inside the library if you configured your Pusher object with your app's secret, or an +authentication request is made to an authentication endpoint that you provide, again when initializing your Pusher +object. -We recommend that you use an authentication endpoint over including your app's secret in your app in the vast majority of use cases. If you are completely certain that there's no risk to you including your app's secret in your app. For example, if your app is just for internal use at your company, then it can make things easier than setting up an authentication endpoint. +We recommend that you use an authentication endpoint over including your app's secret in your app in the vast majority +of use cases. If you are completely certain that there's no risk to you including your app's secret in your app. For +example, if your app is just for internal use at your company, then it can make things easier than setting up an +authentication endpoint. ### Unsubscribing To unsubscribe from a channel, call the `unsubscribe()` method: ```typescript -await pusher.unsubscribe({channelName:"my-channel"}); +await pusher.unsubscribe({ channelName: "my-channel" }); ``` ## Binding to events @@ -481,9 +521,9 @@ const pusher = Pusher.getInstance(); await pusher.init({ apiKey: API_KEY, cluster: API_CLUSTER, - onEvent: (event) { + onEvent: (event) => { console.log(`Got event: ${event}`); - } + }, }); const myChannel = await pusher.subscribe({ channelName: "my-channel" @@ -496,49 +536,58 @@ The callbacks you bind receive a `PusherEvent`: ```typescript class PusherEvent { - channelName:string; // Name of the channel. - eventName:string; // Name of the event. - data:any; // Data, usually JSON string. See [parsing event data](#parsing-event-data). - userId:string; // UserId of the sending event, only for client events on presence channels. + channelName: string; // Name of the channel. + eventName: string; // Name of the event. + data: any; // Data, usually JSON string. See [parsing event data](#parsing-event-data). + userId: string; // UserId of the sending event, only for client events on presence channels. } ``` #### Parsing event data -The `data` property of [`PusherEvent`](#pusherevent) contains the string representation of the data that you passed when you triggered the event. If you passed an object then that object will have been serialized to JSON. You can parse that JSON as appropriate. +The `data` property of [`PusherEvent`](#pusherevent) contains the string representation of the data that you passed when +you triggered the event. If you passed an object then that object will have been serialized to JSON. You can parse that +JSON as appropriate. ### Receiving errors Errors received from Pusher Channels can be accessed via the `onError` callback. ```typescript -void onError(message:string, code:int, e:any) { +void function onError(message: string, code: int, e: any) { console.log(`onError: ${message} code: ${code} exception: ${e}`); } ``` ## Triggering events -Once a [private](https://pusher.com/docs/channels/using_channels/private-channels) or [presence](https://pusher.com/docs/channels/using_channels/presence-channels) subscription has been authorized (see [authenticating users](https://pusher.com/docs/channels/server_api/authenticating-users)) and the subscription has succeeded, it is possible to trigger events on those channels. You can do this per channel, or +Once a [private](https://pusher.com/docs/channels/using_channels/private-channels) +or [presence](https://pusher.com/docs/channels/using_channels/presence-channels) subscription has been authorized ( +see [authenticating users](https://pusher.com/docs/channels/server_api/authenticating-users)) and the subscription has +succeeded, it is possible to trigger events on those channels. You can do this per channel, or on the global `Pusher` instance. ```typescript -await myChannel.trigger({eventName: "client-my-event", data: {"myName": "Bob"}}); +await myChannel.trigger({ eventName: "client-my-event", data: { "myName": "Bob" } }); ``` Or on the global pusher instance: ```typescript -await pusher.trigger({channelName: "my-channel", eventName: "client-my-event", data: {"myName": "Bob"}}); +await pusher.trigger({ channelName: "my-channel", eventName: "client-my-event", data: { "myName": "Bob" } }); ``` -Events triggered by clients are called [client events](https://pusher.com/docs/channels/using_channels/events#triggering-client-events). Because they are being triggered from a client which may not be trusted, there are a number of enforced rules when using them. Some of these rules include: +Events triggered by clients are +called [client events](https://pusher.com/docs/channels/using_channels/events#triggering-client-events). Because they +are being triggered from a client which may not be trusted, there are a number of enforced rules when using them. Some +of these rules include: - Event names must have a `client-` prefix - Rate limits - You can only trigger an event when the subscription has succeeded -For more details, refer to [client events](https://pusher.com/docs/channels/using_channels/events#triggering-client-events). +For more details, refer +to [client events](https://pusher.com/docs/channels/using_channels/events#triggering-client-events). ## Get a channel by name @@ -568,4 +617,5 @@ Pusher is owned and maintained by [Pusher](https://pusher.com). ## License -Pusher is released under the MIT license. Refer to [LICENSE](https://github.com/pusher/pusher-websocket-react-native/blob/master/LICENSE) for more details. +Pusher is released under the MIT license. Refer +to [LICENSE](https://github.com/pusher/pusher-websocket-react-native/blob/master/LICENSE) for more details.