0

Retrieve usage statistics for an application

by
Published Oct 17, 2025

The Ably system can be queried to obtain usage statistics for a given application, and results are provided aggregated across all channels in use in the application in the specified period. Stats may be used to track usage against account quotas.

Script ably Verified

The script

Submitted by hugo697 Bun
Verified 240 days ago
1
//native
2
type Ably = {
3
  apiKey: string;
4
};
5
/**
6
 * Retrieve usage statistics for an application
7
 * The Ably system can be queried to obtain usage statistics for a given application, and results are provided aggregated across all channels in use in the application in the specified period. Stats may be used to track usage against account quotas.
8
 */
9
export async function main(
10
  auth: Ably,
11
  format: "json" | "jsonp" | "msgpack" | "html" | undefined,
12
  start: string | undefined,
13
  limit: string | undefined,
14
  end: string | undefined,
15
  direction: "forwards" | "backwards" | undefined,
16
  unit: "minute" | "hour" | "day" | "month" | undefined,
17
  X_Ably_Version: string,
18
) {
19
  const url = new URL(`https://rest.ably.io/stats`);
20
  for (const [k, v] of [
21
    ["format", format],
22
    ["start", start],
23
    ["limit", limit],
24
    ["end", end],
25
    ["direction", direction],
26
    ["unit", unit],
27
  ]) {
28
    if (v !== undefined && v !== "" && k !== undefined) {
29
      url.searchParams.append(k, v);
30
    }
31
  }
32
  const response = await fetch(url, {
33
    method: "GET",
34
    headers: {
35
      "X-Ably-Version": X_Ably_Version,
36
      Authorization: "Bearer " + auth.apiKey,
37
    },
38
    body: undefined,
39
  });
40
  if (!response.ok) {
41
    const text = await response.text();
42
    throw new Error(`${response.status} ${text}`);
43
  }
44
  return await response.json();
45
}
46