|
| 1 | +const fs = require("node:fs"); |
| 2 | +const path = require("node:path"); |
| 3 | + |
| 4 | +/** |
| 5 | + * Create a file |
| 6 | + * |
| 7 | + * @param {object} file - Required. The file object. |
| 8 | + * @param {object} metadata - Optional. User-provided metadata associated with the file. |
| 9 | + * @returns {Promise<object>} - Resolves with the file data |
| 10 | + */ |
| 11 | +async function createFile(file, metadata = {}) { |
| 12 | + const form = new FormData(); |
| 13 | + |
| 14 | + let fileName; |
| 15 | + let fileType; |
| 16 | + let fileStream; |
| 17 | + if (file instanceof Blob) { |
| 18 | + fileName = file.name || `blob_${Date.now()}`; |
| 19 | + fileType = file.type || "application/octet-stream"; |
| 20 | + fileStream = file.stream(); |
| 21 | + } else if (file instanceof File) { |
| 22 | + fileName = file.name || path.basename(file.path); |
| 23 | + fileType = file.type || "application/octet-stream"; |
| 24 | + fileStream = fs.createReadStream(file.path); |
| 25 | + } else { |
| 26 | + throw new Error("Invalid file argument, must be a Blob or File"); |
| 27 | + } |
| 28 | + |
| 29 | + form.append("content", fs.createReadStream(file.path), { |
| 30 | + filename: fileName, |
| 31 | + type: fileType, |
| 32 | + }); |
| 33 | + form.append("metadata", JSON.stringify(metadata), { |
| 34 | + type: "application/json", |
| 35 | + }); |
| 36 | + |
| 37 | + const response = await fetch("/files", { |
| 38 | + method: "POST", |
| 39 | + body: form, |
| 40 | + }); |
| 41 | + |
| 42 | + return response.json(); |
| 43 | +} |
| 44 | + |
| 45 | +/** |
| 46 | + * List all files |
| 47 | + * |
| 48 | + * @returns {Promise<object>} - Resolves with the files data |
| 49 | + */ |
| 50 | +async function listFiles() { |
| 51 | + const response = await fetch("/files", { |
| 52 | + method: "GET", |
| 53 | + }); |
| 54 | + |
| 55 | + return response.json(); |
| 56 | +} |
| 57 | + |
| 58 | +/** |
| 59 | + * Get a file |
| 60 | + * |
| 61 | + * @param {string} file_id - Required. The ID of the file. |
| 62 | + * @returns {Promise<object>} - Resolves with the file data |
| 63 | + */ |
| 64 | +async function getFile(file_id) { |
| 65 | + const response = await fetch(`/files/${file_id}`, { |
| 66 | + method: "GET", |
| 67 | + }); |
| 68 | + |
| 69 | + return response.json(); |
| 70 | +} |
| 71 | + |
| 72 | +/** |
| 73 | + * Delete a file |
| 74 | + * |
| 75 | + * @param {string} file_id - Required. The ID of the file. |
| 76 | + * @returns {Promise<object>} - Resolves with the deletion confirmation |
| 77 | + */ |
| 78 | +async function deleteFile(file_id) { |
| 79 | + const response = await fetch(`/files/${file_id}`, { |
| 80 | + method: "DELETE", |
| 81 | + }); |
| 82 | + |
| 83 | + return response.json(); |
| 84 | +} |
| 85 | + |
| 86 | +module.exports = { |
| 87 | + create: createFile, |
| 88 | + list: listFiles, |
| 89 | + get: getFile, |
| 90 | + delete: deleteFile, |
| 91 | +}; |
0 commit comments