Edits history of script submission #9847 for ' Upload a file to the corpus (vectara)'

  • bun
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    type Vectara = {
    	apiKey: string
    }
    /**
     * Upload a file to the corpus
     * Upload files such as PDFs and Word Documents.
     */
    export async function main(
    	auth: Vectara,
    	corpus_key: string,
    	body: {
    		metadata?: {}
    		filename?: string
    		file: {
    			base64: string
    			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://api.vectara.io/v2/corpora/${corpus_key}/upload_file`)
    
    	const formData = new FormData()
    	for (const [k, v] of Object.entries(body)) {
    		if (v !== undefined && v !== '') {
    			if (['file'].includes(k)) {
    				const { base64, type, name } = v as {
    					base64: string
    					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: 'POST',
    		headers: {
    			'x-api-key': auth.apiKey
    		},
    		body: formData
    	})
    	if (!response.ok) {
    		const text = await response.text()
    		throw new Error(`${response.status} ${text}`)
    	}
    	return await response.json()
    }
    

    Submitted by hugo697 581 days ago