-
Notifications
You must be signed in to change notification settings - Fork 140
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
8ddf759
commit 8ce490c
Showing
9 changed files
with
131 additions
and
163 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,82 @@ | ||
import { useMutation, useQuery } from '@tanstack/react-query'; | ||
|
||
import { trpc } from '@/lib/trpc/client'; | ||
|
||
/** | ||
* Fetches a file from the specified URL and returns file information. | ||
* Designed to be used as a `queryFn` in a `useQuery`. | ||
* | ||
* @param url The URL from which the file should be fetched. | ||
* @param [metadata] The metadata of the file you want to retrieve. | ||
* @returns A Promise that resolves to an object containing information about the file. | ||
* | ||
* @example | ||
* // Usage with Tanstack Query's useQuery: | ||
* const fileQuery = useQuery({ | ||
queryKey: ['fileKey', url], | ||
queryFn: () => fetchFile(url, ['name']), | ||
enabled: !!url, | ||
}); | ||
*/ | ||
export const fetchFile = async (url: string, metadata?: string[]) => { | ||
const fileResponse = await fetch(url, { | ||
cache: 'no-cache', | ||
}); | ||
if (!fileResponse.ok) { | ||
throw new Error('Could not fetch the file'); | ||
} | ||
|
||
const lastModifiedDateHeader = fileResponse.headers.get('Last-Modified'); | ||
const defaultFileData = { | ||
fileUrl: url, | ||
size: fileResponse.headers.get('Content-Length') ?? undefined, | ||
type: fileResponse.headers.get('Content-Type') ?? undefined, | ||
lastModifiedDate: lastModifiedDateHeader | ||
? new Date(lastModifiedDateHeader) | ||
: new Date(), | ||
}; | ||
|
||
if (!metadata) { | ||
return defaultFileData; | ||
} | ||
|
||
return metadata.reduce((file, metadataKey) => { | ||
return { | ||
...file, | ||
[metadataKey]: fileResponse.headers.get(`x-amz-meta-${metadataKey}`), | ||
}; | ||
}, defaultFileData); | ||
}; | ||
|
||
export const useUploadFileMutation = ( | ||
params: { | ||
getMetadata?: (file: File) => Record<string, string>; | ||
} = {} | ||
) => { | ||
const uploadPresignedUrl = trpc.files.uploadPresignedUrl.useMutation(); | ||
return useMutation({ | ||
mutationFn: async (file: File) => { | ||
const presignedUrlOutput = await uploadPresignedUrl.mutateAsync({ | ||
metadata: { | ||
name: file.name, | ||
...params.getMetadata?.(file), | ||
}, | ||
}); | ||
await fetch(presignedUrlOutput.signedUrl, { | ||
method: 'PUT', | ||
headers: { 'Content-Type': file.type }, | ||
body: file, | ||
}); | ||
// TODO ERRORS | ||
return presignedUrlOutput.futureFileUrl; | ||
}, | ||
}); | ||
}; | ||
|
||
export const useFetchFile = (url?: string | null) => { | ||
return useQuery({ | ||
queryKey: ['file', url], | ||
queryFn: () => (url ? fetchFile(url, ['name']) : undefined), | ||
enabled: !!url, | ||
}); | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,102 +1,5 @@ | ||
import { UseMutateAsyncFunction } from '@tanstack/react-query'; | ||
import { stringify } from 'superjson'; | ||
|
||
import { env } from '@/env.mjs'; | ||
|
||
import { UploadSignedUrlInput } from './schemas'; | ||
|
||
/** | ||
* Fetches a file from the specified URL and returns file information. | ||
* Designed to be used as a `queryFn` in a `useQuery`. | ||
* | ||
* @param url The URL from which the file should be fetched. | ||
* @param [metadata] The metadata of the file you want to retrieve. | ||
* @returns A Promise that resolves to an object containing information about the file. | ||
* | ||
* @example | ||
* // Usage with Tanstack Query's useQuery: | ||
* const fileQuery = useQuery({ | ||
queryKey: ['fileKey', url], | ||
queryFn: () => fetchFile(url, ['name']), | ||
enabled: !!url, | ||
}); | ||
*/ | ||
export const fetchFile = async (url: string, metadata?: string[]) => { | ||
const fileResponse = await fetch(url, { | ||
cache: 'no-cache', | ||
}); | ||
if (!fileResponse.ok) { | ||
throw new Error('Could not fetch the file'); | ||
} | ||
|
||
const lastModifiedDateHeader = fileResponse.headers.get('Last-Modified'); | ||
const defaultFileData = { | ||
fileUrl: url, | ||
size: fileResponse.headers.get('Content-Length') ?? undefined, | ||
type: fileResponse.headers.get('Content-Type') ?? undefined, | ||
lastModifiedDate: lastModifiedDateHeader | ||
? new Date(lastModifiedDateHeader) | ||
: new Date(), | ||
}; | ||
|
||
if (!metadata) { | ||
return defaultFileData; | ||
} | ||
|
||
return metadata.reduce((file, metadataKey) => { | ||
return { | ||
...file, | ||
[metadataKey]: fileResponse.headers.get(`x-amz-meta-${metadataKey}`), | ||
}; | ||
}, defaultFileData); | ||
}; | ||
|
||
/** | ||
* Asynchronously uploads a file to a server using a presigned URL. | ||
* Designed to be used as a `mutationFn` in a `useMutation`. | ||
* | ||
* @param getPresignedUrl | ||
* - An asyncMutation that is used to obtain the presigned URL and the future URL where the file will be accessible. | ||
* | ||
* @param file - The file object to upload. | ||
* @param metadata - Optional metadata for the file, which will be sent to the server when generating the presigned URL. | ||
* | ||
* @returns A promise that resolves to an object containing the URL of the uploaded file, | ||
* | ||
* @example | ||
* // Usage with Tanstack Query's useMutation: | ||
* const getPresignedUrl = trpc.routeToGetPresignedUrl.useMutation(); | ||
const fileUpload = useMutation({ | ||
mutationFn: (file: File) => uploadFile(getPresignedUrl.mutateAsync, file), | ||
}); | ||
*/ | ||
export const uploadFile = async ( | ||
getPresignedUrl: UseMutateAsyncFunction< | ||
{ signedUrl: string; futureFileUrl: string }, | ||
unknown, | ||
UploadSignedUrlInput | ||
>, | ||
file: File, | ||
metadata: Record<string, string> = {} | ||
) => { | ||
const { signedUrl, futureFileUrl } = await getPresignedUrl({ | ||
metadata: stringify({ | ||
name: file.name, | ||
...metadata, | ||
}), | ||
}); | ||
|
||
await fetch(signedUrl, { | ||
method: 'PUT', | ||
headers: { 'Content-Type': file.type }, | ||
body: file, | ||
}); | ||
|
||
return { | ||
fileUrl: futureFileUrl, | ||
} as const; | ||
}; | ||
|
||
export const isFileUrlValidBucket = async (url: string) => { | ||
return url.startsWith(env.S3_BUCKET_PUBLIC_URL); | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
import { z } from 'zod'; | ||
|
||
import { env } from '@/env.mjs'; | ||
import { zUploadSignedUrlOutput } from '@/files/schemas'; | ||
import { getS3UploadSignedUrl } from '@/server/config/s3'; | ||
import { createTRPCRouter, protectedProcedure } from '@/server/config/trpc'; | ||
|
||
export const filesRouter = createTRPCRouter({ | ||
uploadPresignedUrl: protectedProcedure() | ||
.meta({ | ||
openapi: { | ||
method: 'GET', | ||
path: '/files/upload-presigned-url', | ||
tags: ['files'], | ||
protect: true, | ||
}, | ||
}) | ||
.input( | ||
z | ||
.object({ | ||
metadata: z.record(z.string(), z.string()), | ||
}) | ||
.optional() | ||
) | ||
.output(zUploadSignedUrlOutput()) | ||
.mutation(async ({ input, ctx }) => { | ||
return await getS3UploadSignedUrl({ | ||
key: ctx.user.id, // FIX ME | ||
host: env.S3_BUCKET_PUBLIC_URL, | ||
metadata: input?.metadata, | ||
}); | ||
}), | ||
}); |