22 lines
751 B
TypeScript
22 lines
751 B
TypeScript
/**
|
|
* @fileoverview This file provides a utility function for fetching a remote
|
|
* image and encoding it in base64.
|
|
*/
|
|
|
|
/**
|
|
* Fetches an image from a URL and returns
|
|
* its MIME type and base64-encoded data.
|
|
*
|
|
* @param url - The URL of the image to fetch.
|
|
* @returns A promise that resolves to an object containing the MIME type and
|
|
* base64-encoded image data.
|
|
* @throws Throws an error if the image fetch fails.
|
|
*/
|
|
export async function fetchAndEncode(url: string) {
|
|
const res = await fetch(url);
|
|
if (!res.ok) throw new Error(`Failed to fetch image: ${url}`);
|
|
const buf = Buffer.from(await res.arrayBuffer());
|
|
const mimeType = res.headers.get('content-type') ?? 'image/png';
|
|
return { mimeType, data: buf.toString('base64') };
|
|
}
|