Edits history of script submission #23031 for ' Create File From Text (gdrive)'

  • bunnative
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    
    /**
     * Create File From Text
     * Create a file from a string. Leave `mime_type` as text/plain for a .txt file, or set `convert_to_google_doc` to create an editable Google Doc from the text.
     */
    export async function main(
      auth: RT.Gdrive,
      name: string,
      content: string,
      folder_id: string | undefined,
      mime_type: string = "text/plain",
      convert_to_google_doc: boolean = false
    ) {
      const metadata: { [key: string]: any } = { name }
      if (folder_id !== undefined && folder_id !== "")
        metadata.parents = [folder_id]
      if (convert_to_google_doc)
        metadata.mimeType = "application/vnd.google-apps.document"
    
      // multipart/related: JSON metadata part, then the content part.
      const boundary = crypto.randomUUID()
      const body = [
        `--${boundary}`,
        "Content-Type: application/json; charset=UTF-8",
        "",
        JSON.stringify(metadata),
        `--${boundary}`,
        `Content-Type: ${mime_type}; charset=UTF-8`,
        "",
        content,
        `--${boundary}--`,
      ].join("\r\n")
    
      const url = new URL("https://www.googleapis.com/upload/drive/v3/files")
      url.searchParams.append("uploadType", "multipart")
      url.searchParams.append("supportsAllDrives", "true")
    
      const response = await fetch(url, {
        method: "POST",
        headers: {
          Authorization: `Bearer ${auth.token}`,
          "Content-Type": `multipart/related; boundary=${boundary}`,
          Accept: "application/json",
        },
        body,
      })
    
      if (!response.ok) {
        throw new Error(`${response.status} ${await response.text()}`)
      }
    
      return await response.json()
    }
    

    Submitted by hugo989 1 hour ago