0

Attach File to a specific document

by
Published Oct 17, 2025

Attach File to a specific document.

Script holded Verified

The script

Submitted by hugo697 Bun
Verified 235 days ago
1
//native
2
type Holded = {
3
  apiKey: string;
4
};
5
type Base64 = string;
6
/**
7
 * Attach File to a specific document
8
 * Attach File to a specific document.
9
 */
10
export async function main(
11
  auth: Holded,
12
  docType: string,
13
  documentId: string,
14
  body: {
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
    setMain?: false | true;
31
  },
32
) {
33
  const url = new URL(
34
    `https://api.holded.com/api/invoicing/v1/documents/${docType}/${documentId}/attach`,
35
  );
36

37
  const formData = new FormData();
38
  for (const [k, v] of Object.entries(body)) {
39
    if (v !== undefined) {
40
      if (["file"].includes(k)) {
41
        const { base64, type, name } = v as {
42
          base64: Base64;
43
          type: string;
44
          name: string;
45
        };
46
        formData.append(
47
          k,
48
          new Blob([Uint8Array.from(atob(base64), (m) => m.codePointAt(0)!)], {
49
            type,
50
          }),
51
          name,
52
        );
53
      } else {
54
        formData.append(k, String(v));
55
      }
56
    }
57
  }
58
  const response = await fetch(url, {
59
    method: "POST",
60
    headers: {
61
      key: auth.apiKey,
62
    },
63
    body: formData,
64
  });
65
  if (!response.ok) {
66
    const text = await response.text();
67
    throw new Error(`${response.status} ${text}`);
68
  }
69
  return await response.json();
70
}
71