Skip to content

Commit f048d87

Browse files
committed
feat: add the support of URLs for the nearImage() method
1 parent ef950c4 commit f048d87

File tree

1 file changed

+27
-1
lines changed

1 file changed

+27
-1
lines changed

src/utils/base64.ts

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import fs from 'fs';
2+
import { httpClient } from '../connection/http.js';
23

34
const isFilePromise = (file: string | Buffer): Promise<boolean> =>
45
new Promise((resolve, reject) => {
@@ -22,6 +23,29 @@ const isFilePromise = (file: string | Buffer): Promise<boolean> =>
2223
});
2324
});
2425

26+
const isUrl = (file: string | Buffer): boolean => {
27+
if (typeof file !== 'string') return false;
28+
try {
29+
const url = new URL(file);
30+
return !!url;
31+
} catch {
32+
return false;
33+
}
34+
};
35+
36+
const downloadImageAsBase64 = async (url: string): Promise<string> => {
37+
try {
38+
const client = httpClient({
39+
headers: { 'Content-Type': 'image/*' },
40+
host: '',
41+
});
42+
const response = await client.externalGet(url);
43+
return Buffer.from(response, 'binary').toString('base64');
44+
} catch (error) {
45+
throw new Error(`Failed to download image from URL: ${url}`);
46+
}
47+
};
48+
2549
const isBuffer = (file: string | Buffer): file is Buffer => file instanceof Buffer;
2650

2751
const fileToBase64 = (file: string | Buffer): Promise<string> =>
@@ -37,14 +61,16 @@ const fileToBase64 = (file: string | Buffer): Promise<string> =>
3761
})
3862
: isBuffer(file)
3963
? Promise.resolve(file.toString('base64'))
64+
: isUrl(file)
65+
? downloadImageAsBase64(file)
4066
: Promise.resolve(file)
4167
);
4268

4369
/**
4470
* This function converts a file buffer into a base64 string so that it can be
4571
* sent to Weaviate and stored as a media field.
4672
*
47-
* @param {string | Buffer} file The media to convert either as a base64 string, a file path string, or as a buffer. If you passed a base64 string, the function does nothing and returns the string as is.
73+
* @param {string | Buffer} file The media to convert either as a base64 string, a file path string, an url, or as a buffer. If you passed a base64 string, the function does nothing and returns the string as is.
4874
* @returns {string} The base64 string
4975
*/
5076
export const toBase64FromMedia = (media: string | Buffer): Promise<string> => fileToBase64(media);

0 commit comments

Comments
 (0)