Edits history of script submission #15790 for ' Initiates a direct external upload (discourse)'

  • bun
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    type Discourse = {
      apiKey: string;
      defaultHost: string;
      apiUsername: string;
    };
    /**
     * Initiates a direct external upload
     * Direct external uploads bypass the usual method of creating uploads
    via the POST /uploads route, and upload directly to an external provider,
    which by default is S3.
     */
    export async function main(
      auth: Discourse,
      body: {
        type:
          | "avatar"
          | "profile_background"
          | "card_background"
          | "custom_emoji"
          | "composer";
        file_name: string;
        file_size: number;
        metadata?: { "sha1-checksum"?: string };
      },
    ) {
      const url = new URL(
        `https://${auth.defaultHost}/uploads/generate-presigned-put.json`,
      );
    
      const response = await fetch(url, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "API-KEY": auth.apiKey,
          "API-USERNAME": auth.apiUsername,
        },
        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 235 days ago