Constructor
Constructor
The Ably Realtime library constructor is overloaded allowing it to be instantiated using a ClientOptions
object, or more simply using a string containing an API key or Token, as shown below:
new Ably.Realtime(ClientOptions clientOptions)
This will instantiate the library using the specified ClientOptions.
new Ably.Realtime(String keyOrTokenId)
This will instantiate the Realtime library with the provided API key or Token ID string.
The Realtime constructor is used to instantiate the library. The Realtime library may be instantiated multiple times with the same or different ClientOptions
in any given context. Except where specified otherwise, instances operate independently of one another.
Authentication
The Realtime library needs to have credentials to be able to authenticate with the Ably service. Ably supports both Basic and Token based authentication schemes. Read more on authentication.
Basic Authentication
You can pass a full-length API key in as ClientOptions#key
(or just straight into the constructor instead of a ClientOptions
instance), as obtained from the application dashboard. Use this option if you wish to use Basic authentication, or if you want to be able to request Ably Tokens without needing to defer to a separate entity to sign Ably TokenRequests. Note that initializing the library with a key
does not necessarily mean that the library will use Basic auth; it is also able to create and sign Ably TokenRequests, and can use token authentication for itself if it needs to or if ClientOptions#useTokenAuth
is enabled.
Token Authentication
The ClientOptions#token
option takes a token
string or tokenDetails
object, which may have been obtained from some other instance that requested the Ably Token. This option is rarely used in production since tokens are short-lived, so generally you would not start with a token without the means to refresh it. The authUrl
and authCallback
options allow the library to request new Ably-compatible tokens or Ably TokenRequests as it needs to; using these options allows the library to be instantiated without a key
or token
, and an initial token will be obtained automatically when required.
Read more on authentication.
Ably.Realtime Properties
The Realtime client exposes the following public properties:
auth
A reference to the Auth
authentication object configured for this client library.
push
A reference to the Push
object in this client library.
channels
Channels
is a reference to the Channel
collection instance for this library indexed by the channel name. You can use the Get
method of this to get a Channel
instance. See channels and messages for more information.
connection
A reference to the Connection
object for this library instance.
Ably.Realtime Methods
connect
connect(): void
Explicitly calling connect
is unnecessary unless the ClientOptions
autoConnect
is disabled. This method calls connection.connect()
and causes the connection to open, entering the connecting
state.
close
close(): void
This calls connection.close()
and causes the connection to close, entering the closing
state. Once closed
, the library will not attempt to re-establish the connection without an explicit call to connect()
.
stats
stats(Object params?): Promise<PaginatedResult<Stats>>
This call queries the REST /stats
API and retrieves your application’s usage statistics. A PaginatedResult is returned, containing an array of Stats for the first page of results. PaginatedResult objects are iterable providing a means to page through historical statistics. See an example set of raw stats returned via the REST API.
See statistics for more information.
Parameters
- params
- an optional object set of parameters used to specify which statistics are retrieved. If not specified the default parameters will be used
params
properties
The following options, as defined in the REST /stats
API endpoint, are permitted:
- start
- beginning of time earliest time in milliseconds since the epoch for any stats retrievedType:
Number
- end
- current time latest time in milliseconds since the epoch for any stats retrievedType:
Number
- direction
- backwards
forwards
orbackwards
Type:String
- limit
- 100 maximum number of stats to retrieve up to 1,000Type:
Number
- unit
- minute
minute
,hour
,day
ormonth
. Based on the unit selected, the given start or end times are rounded down to the start of the relevant interval depending on the unit granularity of the queryType:StatsIntervalGranularity
Returns
Returns a promise. On success, the promise is fulfilled with a PaginatedResult
object containing an array of Stats
objects. On failure, the promise is rejected with an ErrorInfo
object.
time
time(): Promise<Number>
Obtains the time from the Ably service as milliseconds since epoch. (Clients that do not have access to a sufficiently well maintained time source and wish to issue Ably TokenRequests with a more accurate timestamp should use the queryTime
clientOptions instead of this method).
Returns
Returns a promise. On success, the promise is fulfilled with the time as milliseconds since the Unix epoch. On failure, the promise is rejected with an ErrorInfo
object.
request
request(method, path, version, params?, body?, headers?): Promise<HttpPaginatedResponse>
Makes a REST request to a provided path. This is provided as a convenience for developers who wish to use REST API functionality that is either not documented or is not yet included in the public API, without having to handle authentication, paging, fallback hosts, MsgPack and JSON support, etc. themselves.
Parameters
- method
- either
get
,post
,put
,patch
ordelete
.Type: String - path
- the path to query.Type: String
- version
- version of the REST API to use.Type: Number
- params
- (optional) any querystring parameters needed.Type: Object
- body
- (optional; for
post
,put
andpatch
methods) the body of the request, as anything that can be serialized into JSON, such as anObject
orArray
.Type: Serializable - headers
- (optional) any headers needed. If provided, these will be mixed in with the default library headers.Type: Object
Returns
Returns a promise. On success, the promise is fulfilled with the HttpPaginatedResponse
object returned by the HTTP request. The response object will contain an empty or JSON-encodable object. On failure, the promise is rejected with an ErrorInfo
object.
Example
const response = await rest.request(
'get',
'/channels/someChannel/messages',
3,
{ limit: 1, direction: 'forwards' },
);
console.log('Success! status code was ' + response.statusCode);
console.log(response.items.length + ' items returned');
if (response.hasNext()) {
const nextPage = await response.next();
console.log(nextPage.items.length + ' more items returned');
}
CopyCopied!
batchPublish
There are two overloaded versions of this method:
batchPublish(BatchPublishSpec spec): Promise<BatchResult<BatchPublishSuccessResult | BatchPublishFailureResult>>
Publishes a BatchPublishSpec
object to one or more channels, up to a maximum of 100 channels.
batchPublish(BatchPublishSpec[] specs): Promise<BatchResult<BatchPublishSuccessResult | BatchPublishFailureResult>[]>
Publishes one or more BatchPublishSpec
objects to one or more channels, up to a maximum of 100 channels.
Parameters
- spec
- an object describing the messages to be batch published and to which channels__Type:
BatchPublishSpec
- specs
- an array of objects describing the messages to be batch published and to which channels__Type:
BatchPublishSpec
[]
Returns
Returns a promise. On success, the promise is fulfilled with a BatchResult
object, or an array of BatchResult
objects, containing information about the result of the batch publish operation for each channel. The successful results of specific channels are returned as BatchPublishSuccessResult
objects, whilst failures are BatchPublishFailureResult
objects. If an array of BatchResult
objects are returned, they are in the same order as the provided BatchPublishSpec
. On failure, the promise is rejected with an ErrorInfo
object.
batchPresence
batchPresence(String[] channels): Promise<BatchResult<BatchPresenceSuccessResult | BatchPresenceFailureResult>[]>
Retrieves the presence state for one or more channels, up to a maximum of 100 channels. Presence state includes the clientId
of members and their current PresenceAction
.
Parameters
- channels
- an array of one or more channel names, up to a maximum of 100 channelsType:
String[]
Returns
Returns a promise. On success, the promise is fulfilled with a BatchResult
object containing information about the result of the batch presence request for each channel. The successful results of specific channels are returned as BatchPresenceSuccessResult
objects, whilst failures are BatchPresenceFailureResult
objects. On failure, the promise is rejected with an ErrorInfo
object.
Related types
ClientOptions
ClientOptions
is a plain JavaScript object and is used in the Ably.Realtime
constructor’s options
argument. The following attributes can be defined on the object:
Properties
- key
- The full key string, as obtained from the application dashboard. Use this option if you wish to use Basic authentication, or wish to be able to issue Ably Tokens without needing to defer to a separate entity to sign Ably TokenRequests. Read more about Basic authenticationType:
String
- token
- An authenticated token. This can either be a
TokenDetails
object, aTokenRequest
object, or token string (obtained from thetoken
property of aTokenDetails
component of an Ably TokenRequest response, or a JSON Web Token satisfying the Ably requirements for JWTs). This option is mostly useful for testing: since tokens are short-lived, in production you almost always want to use an authentication method that allows the client library to renew the token automatically when the previous one expires, such asauthUrl
orauthCallback
. Read more about Token authenticationType:String
,TokenDetails
orTokenRequest
- authCallback
- A function with the form
function(tokenParams, callback(err, tokenOrTokenRequest))
which is called when a new token is required. The role of the callback is to obtain a fresh token, one of: an Ably Token string (in plain text format); a signedTokenRequest
; aTokenDetails
(in JSON format); an Ably JWT. See our authentication documentation for details of the Ably TokenRequest format and associated API calls.Type:Callable
- authUrl
- A URL that the library may use to obtain a fresh token, one of: an Ably Token string (in plain text format); a signed
TokenRequest
; aTokenDetails
(in JSON format); an Ably JWT. For example, this can be used by a client to obtain signed Ably TokenRequests from an application server.Type:String
- authMethod
GET
The HTTP verb to use for the request, eitherGET
orPOST
Type:String
- authHeaders
- A set of key value pair headers to be added to any request made to the
authUrl
. Useful when an application requires these to be added to validate the request or implement the response. If theauthHeaders
object contains anauthorization
key, thenwithCredentials
will be set on the xhr request.Type:Object
- authParams
- A set of key value pair params to be added to any request made to the
authUrl
. When theauthMethod
isGET
, query params are added to the URL, whereas whenauthMethod
isPOST
, the params are sent as URL encoded form data. Useful when an application require these to be added to validate the request or implement the response.Type:Object
- tokenDetails
- An authenticated
TokenDetails
object (most commonly obtained from an Ably Token Request response). This option is mostly useful for testing: since tokens are short-lived, in production you almost always want to use an authentication method that allows the client library to renew the token automatically when the previous one expires, such asauthUrl
orauthCallback
. Use this option if you wish to use Token authentication. Read more about Token authenticationType:TokenDetails
- tls
- true A boolean value, indicating whether or not a TLS (“SSL“) secure connection should be used. An insecure connection cannot be used with Basic authentication as it would lead to a possible compromise of the private API key while in transit. Find out more about TLSType:
Boolean
- clientId
- A client ID, used for identifying this client when publishing messages or for presence purposes. The
clientId
can be any non-empty string. This option is primarily intended to be used in situations where the library is instantiated with a key; note that aclientId
may also be implicit in a token used to instantiate the library; an error will be raised if aclientId
specified here conflicts with theclientId
implicit in the token. Find out more about client identitiesType:String
- useTokenAuth
- false When true, forces Token authentication to be used by the library. Please note that if a
clientId
is not specified in theClientOptions
orTokenParams
, then the Ably Token issued will be anonymous. Type:Boolean
- environment
- null Enables enterprise customers to use their own custom environments, which support dedicated, isolated clusters and regional message routing and storage constraints. See our platform customization guide for more details.Type:
String
- idempotentRestPublishing
- false When true, enables idempotent publishing by assigning a unique message ID client-side, allowing the Ably servers to discard automatic publish retries following a failure such as a network fault. We recommend you enable this by default. In version 1.2 onwards, idempotent publishing for retries will be enabled by default.Type:
Boolean
- fallbackHosts
[a.ably-realtime.com, b.ably-realtime.com, c.ably-realtime.com, d.ably-realtime.com, e.ably-realtime.com]
An array of fallback hosts to be used in the case of an error necessitating the use of an alternative host. When a custom environment is specified, the fallback host functionality is disabled. If your customer success manager has provided you with a set of custom fallback hosts, please specify them here.Type:String []
- transportParams
- Optional. Can be used to pass in arbitrary connection parameters, such as
heartbeatInterval
andremainPresentFor
Type:Object
- logLevel
- A number controlling the verbosity of the log output of the library. Valid values are: 0 (no logs), 1 (errors only), 2 (errors plus connection and channel state changes), 3 (high-level debug output), and 4 (full debug output).Type:
Integer
- logHandler
- A function to handle each line of the library’s log output. If
logHandler
is not specified,console.log
is used.Type:Callable
- transports
- An optional array of transports to use, in descending order of preference. In the browser environment the available transports are:
web_socket
,xhr_polling
.Type:String []
- useBinaryProtocol
- false If set to true, will enable the binary protocol (MessagePack) if it is supported. It’s disabled by default on browsers for performance considerations (browsers are optimized for decoding JSON). Find out more about the benefits of binary encodingType:
Boolean
- queueMessages
- true If false, this disables the default behavior whereby the library queues messages on a connection in the disconnected or connecting states. The default behavior allows applications to submit messages immediately upon instancing the library without having to wait for the connection to be established. Applications may use this option to disable queueing if they wish to have application-level control over the queueing under those conditionsType:
Boolean
- echoMessages
- true If false, prevents messages originating from this connection being echoed back on the same connectionType:
Boolean
- autoConnect
- true By default as soon as the client library is instantiated it will connect to Ably. You can optionally set this to false and explicitly connect to Ably when require using the
connect
methodType:Boolean
- recover
- This option allows a connection to inherit the state of a previous connection that may have existed under a different instance of the Realtime library. This might typically be used by clients of the browser library to ensure connection state can be preserved when the user refreshes the page. A recovery key string can be explicitly provided, or alternatively if a callback function is provided, the client library will automatically persist the recovery key between page reloads and call the callback when the connection is recoverable. The callback is then responsible for confirming whether the connection should be recovered or not. See connection state recovery for further informationType:
String
,Callable
- closeOnUnload
- true When true, the client library will automatically send a close request to Ably whenever the
window beforeunload
event fires. By enabling this option, the close request sent to Ably ensures the connection state will not be retained and all channels associated with the connection will be detached. This is commonly used by developers who want presence leave events to fire immediately i.e. if a user navigates to another page or closes their browser, then enabling this option will result in the presence member leaving immediately. Without this option or an explicit call to theclose
method of theConnection object
, Ably expects that the abruptly disconnected connection could later be recovered and therefore does not immediately remove the user from presence. Instead, to avoid “twitchy” presence behavior an abruptly disconnected client is removed from channels in which they are present after 15 seconds, and the connection state is retained for two minutesType:Boolean
- queryTime
- false If true, the library will query the Ably servers for the current time when issuing TokenRequests instead of relying on a locally-available time of day. Knowing the time accurately is needed to create valid signed Ably TokenRequests, so this option is useful for library instances on auth servers where for some reason the server clock cannot be kept synchronized through normal means, such as an NTP daemon . The server is queried for the current time once per client library instance (which stores the offset from the local clock), so if using this option you should avoid instancing a new version of the library for each request.Type:
Boolean
- defaultTokenParams
- When a TokenParams object is provided, it will override the client library defaults when issuing new Ably Tokens or Ably TokenRequestsType:
TokenParams
- disconnectedRetryTimeout
- 15,000ms When the connection enters the
DISCONNECTED
state, after this delay in milliseconds, if the state is stillDISCONNECTED
, the client library will attempt to reconnect automaticallyType:Integer
- suspendedRetryTimeout
- 30,000ms When the connection enters the
SUSPENDED
state, after this delay in milliseconds, if the state is stillSUSPENDED
, the client library will attempt to reconnect automaticallyType:Integer
- pushServiceWorkerUrl
- A URL pointing to a service worker script which is used as the target for web push notificationsType:
String
Stats object
A Stats
object represents an application’s statistics for the specified interval and time period. Ably aggregates statistics globally for all accounts and applications, and makes these available both through our statistics API as well as your application dashboard.
Properties
- appId
- the ID of the Ably application the statistics relate to.Type:
String
- entries
- The statistics for the requested time interval and time period. The
schema
property provides further informationType:Partial<Record<String, Number>>
- inProgress
- Optional. For entires that are still in progress, such as the current month, the last sub-interval included in the stats entry. In the format
yyyy-mm-dd:hh:mm:ss
Type:String
- intervalId
- The UTC time period that the stats coverage begins at. If
unit
was requested asminute
this will be in the formatYYYY-mm-dd:HH:MM
, ifhour
it will beYYYY-mm-dd:HH
, ifday
it will beYYYY-mm-dd:00
and ifmonth
it will beYYYY-mm-01:00
Type:String
- schema
- The URL of a JSON schema describing the structure of the
Stats
objectType:String
StatsIntervalGranularity
StatsIntervalGranularity
is an enum specifying the granularity of a Stats interval
.
const StatsIntervalGranularity = [
'minute',
'hour',
'day',
'month'
]
CopyCopied!
HttpPaginatedResponse
An HttpPaginatedResponse
is a superset of PaginatedResult
, which is a type that represents a page of results plus metadata indicating the relative queries available to it. HttpPaginatedResponse
additionally carries information about the response to an HTTP request. It is used when making custom HTTP requests.
Properties
- statusCode
- the HTTP status code of the responseType:
Number
- success
- whether the HTTP status code indicates success. This is equivalent to
200 <= statusCode < 300
Type:Boolean
- headers
- the headers of the responseType:
Object
- errorCode
- the error code if the
X-Ably-Errorcode
HTTP header is sent in the responseType:Number
- errorMessage
- the error message if the
X-Ably-Errormessage
HTTP header is sent in the responseType:String
Methods
first
first(): Promise<HttpPaginatedResponse>
Returns a promise. On success, the promise is fulfilled with a new HttpPaginatedResponse
for the first page of results. On failure, the promise is rejected with an ErrorInfo
object that details the reason why it was rejected.
hasNext
Boolean hasNext()
Returns true
if there are more pages available by calling next
and returns false
if this page is the last page available.
isLast
Boolean isLast()
Returns true
if this page is the last page and returns false
if there are more pages available by calling next
available.
next
next(): Promise<HttpPaginatedResponse>
Returns a promise. On success, the promise is fulfilled with a new HttpPaginatedResponse
loaded with the next page of results. If there are no further pages, then null
is returned. On failure, the promise is rejected with an ErrorInfo
object that details the reason why it was rejected.
current
current(): Promise<HttpPaginatedResponse>
Returns a promise. On success, the promise is fulfilled with a new HttpPaginatedResponse
loaded with the current page of results. On failure, the promise is rejected with an ErrorInfo
object that details the reason why it was rejected.
Example
The HttpPaginatedResponse
interface is a superset of PaginatedResult
, see the PaginatedResult
example
BatchPublishSpec
A BatchPublishSpec
describes the messages that should be published by a batch publish operation, and the channels to which they should be published.
Properties
- channels
- The names of the channels to publish the
messages
toType:String[]
- messages
- An array of
Message
objectsType:Message[]
BatchResult
A BatchResult
contains information about the results of a batch operation.
Properties
- successCount
- The number of successful operations in the requestType:
Number
- failureCount
- The number of unsuccessful operations in the requestType:
Number
- messages
- An array of results for the batch operation (for example, an array of
BatchPublishSuccessResult
orBatchPublishFailureResult
for a channel batch publish request)Type: Object[]
BatchPublishSuccessResult
A BatchPublishSuccessResult
contains information about the result of successful publishes to a channel requested by a single BatchPublishSpec
.
Properties
- channel
- The name of the channel the message(s) was published toType:
String
- messageId
- A unique ID prefixed to the
Message.id
of each published messageType:String
BatchPublishFailureResult
A BatchPublishFailureResult
contains information about the result of unsuccessful publishes to a channel requested by a single BatchPublishSpec
.
Properties
- channel
- The name of the channel the message(s) failed to be published toType:
String
- error
- Describes the reason for which the message(s) failed to publish to the channel as an
ErrorInfo
objectType:ErrorInfo
BatchPresenceSuccessResult
A BatchPresenceSuccessResult
contains information about the result of a successful batch presence request for a single channel.
Properties
- channel
- The channel name the presence state was retrieved forType:
String
- presence
- An array of
PresenceMessage
describing members present on the channel__Type:PresenceMessage[]
BatchPresenceFailureResult
A BatchPresenceFailureResult
contains information about the result of an unsuccessful batch presence request for a single channel.