UNPKG

strapi-supabase-file-upload

Version:
57 lines 2.25 kB
import { createClient } from '@supabase/supabase-js'; function streamToBuffer(stream) { return new Promise((resolve, reject) => { const chunks = []; stream.on('data', chunk => chunks.push(chunk)); stream.on('end', () => resolve(Buffer.concat(chunks))); stream.on('error', reject); }); } export function init(providerOptions) { const supabase = createClient(providerOptions.apiUrl, providerOptions.apiKey); const bucket = providerOptions.bucket; const directory = providerOptions.directory || ''; return { async upload(file) { const fileName = file.name || `${file.hash}${file.ext}`; const fileNameWithoutExt = (file.name || file.hash).replace(/\.[^/.]+$/, ''); // Remove size prefixes to get the base filename const baseName = fileNameWithoutExt.replace(/^(thumbnail_|large_|medium_|small_)/, ''); const fileDirectory = `${directory}${baseName}/`; const filePath = `${fileDirectory}${fileName}`; let fileContent = file.buffer; if (!fileContent && file.stream) { fileContent = await streamToBuffer(file.stream); } if (!fileContent) { throw new Error('No file content provided'); } const { error } = await supabase.storage .from(bucket) .upload(filePath, fileContent, { contentType: file.mime, upsert: true, }); if (error) throw error; const { data: urlData } = supabase.storage .from(bucket) .getPublicUrl(filePath); file.url = urlData.publicUrl; }, async uploadStream(file) { return this.upload(file); }, async delete(file) { const filePath = file.url.split(`/${bucket}/`)[1]; if (!filePath) { throw new Error('Invalid file URL'); } const { error } = await supabase.storage.from(bucket).remove([filePath]); if (error) throw error; }, }; } export default { init }; //# sourceMappingURL=index.js.map