Add attachment
One script reply has been approved by the moderators Verified

Adds one or more attachments to an issue.

Created by hugo697 879 days ago
Submitted by hugo697 Typescript (fetch-only)
Verified 327 days ago
1
type Jira = {
2
  username: string;
3
  password: string;
4
  domain: string;
5
};
6
/**
7
 * Add attachment
8
 * Adds one or more attachments to an issue.
9
 */
10
export async function main(
11
  auth: Jira,
12
  issueIdOrKey: string,
13
  body: {
14
    bytes?: string[];
15
    contentType?: string;
16
    empty?: boolean;
17
    inputStream?: { [k: string]: unknown };
18
    name?: string;
19
    originalFilename?: string;
20
    resource?: {
21
      description?: string;
22
      file?: string;
23
      filename?: string;
24
      inputStream?: { [k: string]: unknown };
25
      open?: boolean;
26
      readable?: boolean;
27
      uri?: string;
28
      url?: string;
29
    };
30
    size?: number;
31
  }[]
32
) {
33
  const url = new URL(
34
    `https://${auth.domain}.atlassian.net/rest/api/2/issue/${issueIdOrKey}/attachments`
35
  );
36

37
  const formData = new FormData();
38
  for (const [k, v] of Object.entries(body)) {
39
    if (v !== undefined && v !== "") {
40
      formData.append(k, String(v));
41
    }
42
  }
43
  const response = await fetch(url, {
44
    method: "POST",
45
    headers: {
46
      Authorization: "Basic " + btoa(`${auth.username}:${auth.password}`),
47
    },
48
    body: formData,
49
  });
50
  if (!response.ok) {
51
    const text = await response.text();
52
    throw new Error(`${response.status} ${text}`);
53
  }
54
  return await response.json();
55
}
56