Subscribe a device to a channel
One script reply has been approved by the moderators Verified

Subscribe either a single device or all devices associated with a client ID to receive push notifications from messages sent to a channel.

Created by hugo697 185 days ago
Submitted by hugo697 Bun
Verified 185 days ago
1
//native
2
type Ably = {
3
  apiKey: string;
4
};
5
/**
6
 * Subscribe a device to a channel
7
 * Subscribe either a single device or all devices associated with a client ID to receive push notifications from messages sent to a channel.
8
 */
9
export async function main(
10
  auth: Ably,
11
  format: "json" | "jsonp" | "msgpack" | "html" | undefined,
12
  X_Ably_Version: string,
13
  body:
14
    | { channel?: string; deviceId?: string }
15
    | { channel?: string; clientId?: string },
16
) {
17
  const url = new URL(`https://rest.ably.io/push/channelSubscriptions`);
18
  for (const [k, v] of [["format", format]]) {
19
    if (v !== undefined && v !== "" && k !== undefined) {
20
      url.searchParams.append(k, v);
21
    }
22
  }
23
  const response = await fetch(url, {
24
    method: "POST",
25
    headers: {
26
      "X-Ably-Version": X_Ably_Version,
27
      "Content-Type": "application/json",
28
      Authorization: "Bearer " + auth.apiKey,
29
    },
30
    body: JSON.stringify(body),
31
  });
32
  if (!response.ok) {
33
    const text = await response.text();
34
    throw new Error(`${response.status} ${text}`);
35
  }
36
  return await response.json();
37
}
38