feat: integrate S3 storage adapter and update file upload functionality
This commit is contained in:
41
src/lib/storage/storage.utils.ts
Normal file
41
src/lib/storage/storage.utils.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
'use client';
|
||||
|
||||
import * as storage from '@/lib/storage/storage.external';
|
||||
import { StorageProvider } from '@/lib/storage/storage.interface';
|
||||
import { wrap } from '@/utils/types/results';
|
||||
import { z } from 'zod';
|
||||
|
||||
export const FileUploadResp = z.object({
|
||||
signedUrl: z.string(),
|
||||
key: z.string(),
|
||||
});
|
||||
export type FileUploadResp = z.infer<StorageProvider>;
|
||||
|
||||
export const uploadFile = wrap(async (file: File) => {
|
||||
const uniqueFileKey = crypto.randomUUID();
|
||||
const result = await storage.getPutUrl(uniqueFileKey, file.type);
|
||||
if (!result.ok) {
|
||||
throw new Error('File upload failed');
|
||||
}
|
||||
|
||||
const response = await fetch(result.value, {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'Content-Type': file.type,
|
||||
},
|
||||
body: file,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to upload file');
|
||||
}
|
||||
|
||||
const presignedUrl = await storage.getSignedUrl(uniqueFileKey);
|
||||
if (!presignedUrl.ok) {
|
||||
throw new Error('Failed to retrieve file URL');
|
||||
}
|
||||
return {
|
||||
signedUrl: presignedUrl.value,
|
||||
key: uniqueFileKey,
|
||||
};
|
||||
});
|
||||
Reference in New Issue
Block a user