0
Upload an attachment
One script reply has been approved by the moderators Verified

Upload an attachment.

Created by hugo697 390 days ago Viewed 9041 times
0
Submitted by hugo697 Typescript (fetch-only)
Verified 390 days ago
1
type Asana = {
2
  token: string;
3
};
4
type Base64 = string;
5
/**
6
 * Upload an attachment
7
 * Upload an attachment.
8
 */
9
export async function main(
10
  auth: Asana,
11
  opt_pretty: string | undefined,
12
  opt_fields: string | undefined,
13
  body: {
14
    connect_to_app?: boolean;
15
    file?: {
16
      base64: Base64;
17
      type:
18
        | "image/png"
19
        | "image/jpeg"
20
        | "image/gif"
21
        | "application/pdf"
22
        | "appication/json"
23
        | "text/csv"
24
        | "text/plain"
25
        | "audio/mpeg"
26
        | "audio/wav"
27
        | "video/mp4";
28
      name: string;
29
    };
30
    name?: string;
31
    parent?: string;
32
    resource_subtype?:
33
      | "asana"
34
      | "dropbox"
35
      | "gdrive"
36
      | "onedrive"
37
      | "box"
38
      | "vimeo"
39
      | "external";
40
    url?: string;
41
    [k: string]: unknown;
42
  }
43
) {
44
  const url = new URL(`https://app.asana.com/api/1.0/attachments`);
45
  for (const [k, v] of [
46
    ["opt_pretty", opt_pretty],
47
    ["opt_fields", opt_fields],
48
  ]) {
49
    if (v !== undefined && v !== "") {
50
      url.searchParams.append(k, v);
51
    }
52
  }
53
  const formData = new FormData();
54
  for (const [k, v] of Object.entries(body)) {
55
    if (v !== undefined && v !== "") {
56
      if (["file"].includes(k)) {
57
        const { base64, type, name } = v as {
58
          base64: Base64;
59
          type: string;
60
          name: string;
61
        };
62
        formData.append(
63
          k,
64
          new Blob([Uint8Array.from(atob(base64), (m) => m.codePointAt(0)!)], {
65
            type,
66
          }),
67
          name
68
        );
69
      } else {
70
        formData.append(k, String(v));
71
      }
72
    }
73
  }
74
  const response = await fetch(url, {
75
    method: "POST",
76
    headers: {
77
      Authorization: "Bearer " + auth.token,
78
    },
79
    body: formData,
80
  });
81
  if (!response.ok) {
82
    const text = await response.text();
83
    throw new Error(`${response.status} ${text}`);
84
  }
85
  return await response.json();
86
}
87