Edits history of script submission #15241 for ' Create or update attachment (confluence)'

  • bun
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    type Confluence = {
    	email: string
    	apiToken: string
    	domain: string
    }
    type Base64 = string
    /**
     * Create or update attachment
     * Adds an attachment to a piece of content.
     */
    export async function main(
    	auth: Confluence,
    	id: string,
    	status: 'current' | 'draft' | undefined,
    	body: {
    		file: {
    			base64: Base64
    			type:
    				| 'image/png'
    				| 'image/jpeg'
    				| 'image/gif'
    				| 'application/pdf'
    				| 'appication/json'
    				| 'text/csv'
    				| 'text/plain'
    				| 'audio/mpeg'
    				| 'audio/wav'
    				| 'video/mp4'
    			name: string
    		}
    		comment?: {
    			base64: Base64
    			type:
    				| 'image/png'
    				| 'image/jpeg'
    				| 'image/gif'
    				| 'application/pdf'
    				| 'appication/json'
    				| 'text/csv'
    				| 'text/plain'
    				| 'audio/mpeg'
    				| 'audio/wav'
    				| 'video/mp4'
    			name: string
    		}
    		minorEdit: {
    			base64: Base64
    			type:
    				| 'image/png'
    				| 'image/jpeg'
    				| 'image/gif'
    				| 'application/pdf'
    				| 'appication/json'
    				| 'text/csv'
    				| 'text/plain'
    				| 'audio/mpeg'
    				| 'audio/wav'
    				| 'video/mp4'
    			name: string
    		}
    	}
    ) {
    	const url = new URL(`https://${auth.domain}/wiki/rest/api/content/${id}/child/attachment`)
    	for (const [k, v] of [['status', status]]) {
    		if (v !== undefined && v !== '' && k !== undefined) {
    			url.searchParams.append(k, v)
    		}
    	}
    	const formData = new FormData()
    	for (const [k, v] of Object.entries(body)) {
    		if (v !== undefined) {
    			if (['file', 'comment', 'minorEdit'].includes(k)) {
    				const { base64, type, name } = v as {
    					base64: Base64
    					type: string
    					name: string
    				}
    				formData.append(
    					k,
    					new Blob([Uint8Array.from(atob(base64), (m) => m.codePointAt(0)!)], {
    						type
    					}),
    					name
    				)
    			} else {
    				formData.append(k, String(v))
    			}
    		}
    	}
    	const response = await fetch(url, {
    		method: 'PUT',
    		headers: {
    			Authorization: 'Basic ' + btoa(`${auth.email}:${auth.apiToken}`)
    		},
    		body: formData
    	})
    	if (!response.ok) {
    		const text = await response.text()
    		throw new Error(`${response.status} ${text}`)
    	}
    	return await response.json()
    }
    

    Submitted by hugo697 235 days ago