Edits history of script submission #14032 for ' Publish a push notification to device(s) (ably)'

  • bun
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    type Ably = {
      apiKey: string;
    };
    /**
     * Publish a push notification to device(s)
     * A convenience endpoint to deliver a push notification payload to a single device or set of devices identified by their client identifier.
     */
    export async function main(
      auth: Ably,
      format: "json" | "jsonp" | "msgpack" | "html" | undefined,
      X_Ably_Version: string,
      body: {
        recipient: {
          transportType?: "apns" | "fcm" | "gcm" | "web";
          deviceToken?: string;
          registrationToken?: string;
          encryptionKey?: {};
          clientId?: string;
          deviceId?: string;
        };
        push?: {
          data?: string;
          notification?: {
            title?: string;
            body?: string;
            icon?: string;
            sound?: string;
            collapseKey?: string;
          };
          apns?: {
            notification?: {
              title?: string;
              body?: string;
              icon?: string;
              sound?: string;
              collapseKey?: string;
            };
          };
          fcm?: {
            notification?: {
              title?: string;
              body?: string;
              icon?: string;
              sound?: string;
              collapseKey?: string;
            };
          };
          web?: {
            notification?: {
              title?: string;
              body?: string;
              icon?: string;
              sound?: string;
              collapseKey?: string;
            };
          };
        };
      },
    ) {
      const url = new URL(`https://rest.ably.io/push/publish`);
      for (const [k, v] of [["format", format]]) {
        if (v !== undefined && v !== "" && k !== undefined) {
          url.searchParams.append(k, v);
        }
      }
      const response = await fetch(url, {
        method: "POST",
        headers: {
          "X-Ably-Version": X_Ably_Version,
          "Content-Type": "application/json",
          Authorization: "Bearer " + auth.apiKey,
        },
        body: JSON.stringify(body),
      });
      if (!response.ok) {
        const text = await response.text();
        throw new Error(`${response.status} ${text}`);
      }
      return await response.json();
    }
    

    Submitted by hugo697 220 days ago