|
| 1 | +const fs = require('fs'); |
| 2 | +const path = require('path'); |
| 3 | +const axios = require('axios'); |
| 4 | +const fetch = require('node-fetch'); |
| 5 | +const { logger } = require('~/config'); |
| 6 | +const { getAzureContainerClient } = require('./initialize'); |
| 7 | + |
| 8 | +const defaultBasePath = 'images'; |
| 9 | + |
| 10 | +/** |
| 11 | + * Uploads a buffer to Azure Blob Storage. |
| 12 | + * |
| 13 | + * Files will be stored at the path: {basePath}/{userId}/{fileName} within the container. |
| 14 | + * |
| 15 | + * @param {Object} params |
| 16 | + * @param {string} params.userId - The user's id. |
| 17 | + * @param {Buffer} params.buffer - The buffer to upload. |
| 18 | + * @param {string} params.fileName - The name of the file. |
| 19 | + * @param {string} [params.basePath='images'] - The base folder within the container. |
| 20 | + * @param {string} [params.containerName] - The Azure Blob container name. |
| 21 | + * @returns {Promise<string>} The URL of the uploaded blob. |
| 22 | + */ |
| 23 | +async function saveBufferToAzure({ |
| 24 | + userId, |
| 25 | + buffer, |
| 26 | + fileName, |
| 27 | + basePath = defaultBasePath, |
| 28 | + containerName, |
| 29 | +}) { |
| 30 | + try { |
| 31 | + const containerClient = getAzureContainerClient(containerName); |
| 32 | + // Create the container if it doesn't exist. This is done per operation. |
| 33 | + await containerClient.createIfNotExists({ |
| 34 | + access: process.env.AZURE_STORAGE_PUBLIC_ACCESS ? 'blob' : undefined, |
| 35 | + }); |
| 36 | + const blobPath = `${basePath}/${userId}/${fileName}`; |
| 37 | + const blockBlobClient = containerClient.getBlockBlobClient(blobPath); |
| 38 | + await blockBlobClient.uploadData(buffer); |
| 39 | + return blockBlobClient.url; |
| 40 | + } catch (error) { |
| 41 | + logger.error('[saveBufferToAzure] Error uploading buffer:', error); |
| 42 | + throw error; |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +/** |
| 47 | + * Saves a file from a URL to Azure Blob Storage. |
| 48 | + * |
| 49 | + * @param {Object} params |
| 50 | + * @param {string} params.userId - The user's id. |
| 51 | + * @param {string} params.URL - The URL of the file. |
| 52 | + * @param {string} params.fileName - The name of the file. |
| 53 | + * @param {string} [params.basePath='images'] - The base folder within the container. |
| 54 | + * @param {string} [params.containerName] - The Azure Blob container name. |
| 55 | + * @returns {Promise<string>} The URL of the uploaded blob. |
| 56 | + */ |
| 57 | +async function saveURLToAzure({ |
| 58 | + userId, |
| 59 | + URL, |
| 60 | + fileName, |
| 61 | + basePath = defaultBasePath, |
| 62 | + containerName, |
| 63 | +}) { |
| 64 | + try { |
| 65 | + const response = await fetch(URL); |
| 66 | + const buffer = await response.buffer(); |
| 67 | + return await saveBufferToAzure({ userId, buffer, fileName, basePath, containerName }); |
| 68 | + } catch (error) { |
| 69 | + logger.error('[saveURLToAzure] Error uploading file from URL:', error); |
| 70 | + throw error; |
| 71 | + } |
| 72 | +} |
| 73 | + |
| 74 | +/** |
| 75 | + * Retrieves a blob URL from Azure Blob Storage. |
| 76 | + * |
| 77 | + * @param {Object} params |
| 78 | + * @param {string} params.fileName - The file name. |
| 79 | + * @param {string} [params.basePath='images'] - The base folder used during upload. |
| 80 | + * @param {string} [params.userId] - If files are stored in a user-specific directory. |
| 81 | + * @param {string} [params.containerName] - The Azure Blob container name. |
| 82 | + * @returns {Promise<string>} The blob's URL. |
| 83 | + */ |
| 84 | +async function getAzureURL({ fileName, basePath = defaultBasePath, userId, containerName }) { |
| 85 | + try { |
| 86 | + const containerClient = getAzureContainerClient(containerName); |
| 87 | + const blobPath = userId ? `${basePath}/${userId}/${fileName}` : `${basePath}/${fileName}`; |
| 88 | + const blockBlobClient = containerClient.getBlockBlobClient(blobPath); |
| 89 | + return blockBlobClient.url; |
| 90 | + } catch (error) { |
| 91 | + logger.error('[getAzureURL] Error retrieving blob URL:', error); |
| 92 | + throw error; |
| 93 | + } |
| 94 | +} |
| 95 | + |
| 96 | +/** |
| 97 | + * Deletes a blob from Azure Blob Storage. |
| 98 | + * |
| 99 | + * @param {Object} params |
| 100 | + * @param {string} params.fileName - The name of the file. |
| 101 | + * @param {string} [params.basePath='images'] - The base folder where the file is stored. |
| 102 | + * @param {string} params.userId - The user's id. |
| 103 | + * @param {string} [params.containerName] - The Azure Blob container name. |
| 104 | + */ |
| 105 | +async function deleteFileFromAzure({ |
| 106 | + fileName, |
| 107 | + basePath = defaultBasePath, |
| 108 | + userId, |
| 109 | + containerName, |
| 110 | +}) { |
| 111 | + try { |
| 112 | + const containerClient = getAzureContainerClient(containerName); |
| 113 | + const blobPath = `${basePath}/${userId}/${fileName}`; |
| 114 | + const blockBlobClient = containerClient.getBlockBlobClient(blobPath); |
| 115 | + await blockBlobClient.delete(); |
| 116 | + logger.debug('[deleteFileFromAzure] Blob deleted successfully from Azure Blob Storage'); |
| 117 | + } catch (error) { |
| 118 | + logger.error('[deleteFileFromAzure] Error deleting blob:', error.message); |
| 119 | + if (error.statusCode === 404) { |
| 120 | + return; |
| 121 | + } |
| 122 | + throw error; |
| 123 | + } |
| 124 | +} |
| 125 | + |
| 126 | +/** |
| 127 | + * Uploads a file from the local file system to Azure Blob Storage. |
| 128 | + * |
| 129 | + * This function reads the file from disk and then uploads it to Azure Blob Storage |
| 130 | + * at the path: {basePath}/{userId}/{fileName}. |
| 131 | + * |
| 132 | + * @param {Object} params |
| 133 | + * @param {object} params.req - The Express request object. |
| 134 | + * @param {Express.Multer.File} params.file - The file object. |
| 135 | + * @param {string} params.file_id - The file id. |
| 136 | + * @param {string} [params.basePath='images'] - The base folder within the container. |
| 137 | + * @param {string} [params.containerName] - The Azure Blob container name. |
| 138 | + * @returns {Promise<{ filepath: string, bytes: number }>} An object containing the blob URL and its byte size. |
| 139 | + */ |
| 140 | +async function uploadFileToAzure({ |
| 141 | + req, |
| 142 | + file, |
| 143 | + file_id, |
| 144 | + basePath = defaultBasePath, |
| 145 | + containerName, |
| 146 | +}) { |
| 147 | + try { |
| 148 | + const inputFilePath = file.path; |
| 149 | + const inputBuffer = await fs.promises.readFile(inputFilePath); |
| 150 | + const bytes = Buffer.byteLength(inputBuffer); |
| 151 | + const userId = req.user.id; |
| 152 | + const fileName = `${file_id}__${path.basename(inputFilePath)}`; |
| 153 | + const fileURL = await saveBufferToAzure({ |
| 154 | + userId, |
| 155 | + buffer: inputBuffer, |
| 156 | + fileName, |
| 157 | + basePath, |
| 158 | + containerName, |
| 159 | + }); |
| 160 | + await fs.promises.unlink(inputFilePath); |
| 161 | + return { filepath: fileURL, bytes }; |
| 162 | + } catch (error) { |
| 163 | + logger.error('[uploadFileToAzure] Error uploading file:', error); |
| 164 | + throw error; |
| 165 | + } |
| 166 | +} |
| 167 | + |
| 168 | +/** |
| 169 | + * Retrieves a readable stream for a blob from Azure Blob Storage. |
| 170 | + * |
| 171 | + * @param {object} _req - The Express request object. |
| 172 | + * @param {string} fileURL - The URL of the blob. |
| 173 | + * @returns {Promise<ReadableStream>} A readable stream of the blob. |
| 174 | + */ |
| 175 | +async function getAzureFileStream(_req, fileURL) { |
| 176 | + try { |
| 177 | + const response = await axios({ |
| 178 | + method: 'get', |
| 179 | + url: fileURL, |
| 180 | + responseType: 'stream', |
| 181 | + }); |
| 182 | + return response.data; |
| 183 | + } catch (error) { |
| 184 | + logger.error('[getAzureFileStream] Error getting blob stream:', error); |
| 185 | + throw error; |
| 186 | + } |
| 187 | +} |
| 188 | + |
| 189 | +module.exports = { |
| 190 | + saveBufferToAzure, |
| 191 | + saveURLToAzure, |
| 192 | + getAzureURL, |
| 193 | + deleteFileFromAzure, |
| 194 | + uploadFileToAzure, |
| 195 | + getAzureFileStream, |
| 196 | +}; |
0 commit comments