Get the service time
One script reply has been approved by the moderators Verified

This returns the service time in milliseconds since the epoch.

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 the service time
7
 * This returns the service time in milliseconds since the epoch.
8
 */
9
export async function main(
10
  auth: Ably,
11
  format: "json" | "jsonp" | "msgpack" | "html" | undefined,
12
  X_Ably_Version: string,
13
) {
14
  const url = new URL(`https://rest.ably.io/time`);
15
  for (const [k, v] of [["format", format]]) {
16
    if (v !== undefined && v !== "" && k !== undefined) {
17
      url.searchParams.append(k, v);
18
    }
19
  }
20
  const response = await fetch(url, {
21
    method: "GET",
22
    headers: {
23
      "X-Ably-Version": X_Ably_Version,
24
      Authorization: "Bearer " + auth.apiKey,
25
    },
26
    body: undefined,
27
  });
28
  if (!response.ok) {
29
    const text = await response.text();
30
    throw new Error(`${response.status} ${text}`);
31
  }
32
  return await response.json();
33
}
34