Get message history for a channel
One script reply has been approved by the moderators Verified

Get message history for a channel

Created by hugo697 138 days ago
Submitted by hugo697 Bun
Verified 138 days ago
1
//native
2
type Ably = {
3
  apiKey: string;
4
};
5
/**
6
 * Get message history for a channel
7
 * Get message history for a channel
8
 */
9
export async function main(
10
  auth: Ably,
11
  channel_id: string,
12
  format: "json" | "jsonp" | "msgpack" | "html" | undefined,
13
  start: string | undefined,
14
  limit: string | undefined,
15
  end: string | undefined,
16
  direction: "forwards" | "backwards" | undefined,
17
  X_Ably_Version: string,
18
) {
19
  const url = new URL(`https://rest.ably.io/channels/${channel_id}/messages`);
20
  for (const [k, v] of [
21
    ["format", format],
22
    ["start", start],
23
    ["limit", limit],
24
    ["end", end],
25
    ["direction", direction],
26
  ]) {
27
    if (v !== undefined && v !== "" && k !== undefined) {
28
      url.searchParams.append(k, v);
29
    }
30
  }
31
  const response = await fetch(url, {
32
    method: "GET",
33
    headers: {
34
      "X-Ably-Version": X_Ably_Version,
35
      Authorization: "Bearer " + auth.apiKey,
36
    },
37
    body: undefined,
38
  });
39
  if (!response.ok) {
40
    const text = await response.text();
41
    throw new Error(`${response.status} ${text}`);
42
  }
43
  return await response.json();
44
}
45