-
Notifications
You must be signed in to change notification settings - Fork 19
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* feat: client file upload * feat: signed upload * fix: add multipart header * fix: remove unused file * chore(wip): own signature impl * feat: use gcs presigned upload * fix: invalid export * fix: rest api host url * feat: final upload logic and sample
- Loading branch information
Showing
6 changed files
with
209 additions
and
63 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 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,47 @@ | ||
import { getConfig } from './config'; | ||
import { getUserAgent, isBrowser } from './runtime'; | ||
|
||
export async function dispatchRequest<Input, Output>( | ||
method: string, | ||
targetUrl: string, | ||
input: Input | ||
): Promise<Output> { | ||
const { | ||
credentials: credentialsValue, | ||
requestMiddleware, | ||
responseHandler, | ||
} = getConfig(); | ||
const userAgent = isBrowser() ? {} : { 'User-Agent': getUserAgent() }; | ||
const credentials = | ||
typeof credentialsValue === 'function' | ||
? credentialsValue() | ||
: credentialsValue; | ||
|
||
const { url, headers } = await requestMiddleware({ | ||
url: targetUrl, | ||
}); | ||
const authHeader = credentials ? { Authorization: `Key ${credentials}` } : {}; | ||
if (typeof window !== 'undefined' && credentials) { | ||
console.warn( | ||
"The fal credentials are exposed in the browser's environment. " + | ||
"That's not recommended for production use cases." | ||
); | ||
} | ||
const requestHeaders = { | ||
...authHeader, | ||
Accept: 'application/json', | ||
'Content-Type': 'application/json', | ||
...userAgent, | ||
...(headers ?? {}), | ||
} as HeadersInit; | ||
const response = await fetch(url, { | ||
method, | ||
headers: requestHeaders, | ||
mode: 'cors', | ||
body: | ||
method.toLowerCase() !== 'get' && input | ||
? JSON.stringify(input) | ||
: undefined, | ||
}); | ||
return await responseHandler(response); | ||
} |
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,108 @@ | ||
import { getConfig } from './config'; | ||
import { dispatchRequest } from './request'; | ||
|
||
/** | ||
* File support for the client. This interface establishes the contract for | ||
* uploading files to the server and transforming the input to replace file | ||
* objects with URLs. | ||
*/ | ||
export interface StorageSupport { | ||
/** | ||
* Upload a file to the server. Returns the URL of the uploaded file. | ||
* @param file the file to upload | ||
* @param options optional parameters, such as custom file name | ||
* @returns the URL of the uploaded file | ||
*/ | ||
upload: (file: Blob) => Promise<string>; | ||
|
||
/** | ||
* Transform the input to replace file objects with URLs. This is used | ||
* to transform the input before sending it to the server and ensures | ||
* that the server receives URLs instead of file objects. | ||
* | ||
* @param input the input to transform. | ||
* @returns the transformed input. | ||
*/ | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
transformInput: (input: Record<string, any>) => Promise<Record<string, any>>; | ||
} | ||
|
||
function isDataUri(uri: string): boolean { | ||
// avoid uri parsing if it doesn't start with data: | ||
if (!uri.startsWith('data:')) { | ||
return false; | ||
} | ||
try { | ||
const url = new URL(uri); | ||
return url.protocol === 'data:'; | ||
} catch (_) { | ||
return false; | ||
} | ||
} | ||
|
||
type InitiateUploadResult = { | ||
file_url: string; | ||
upload_url: string; | ||
}; | ||
|
||
type InitiateUploadData = { | ||
file_name: string; | ||
content_type: string | null; | ||
}; | ||
|
||
function getRestApiUrl(): string { | ||
const { host } = getConfig(); | ||
return host.replace('gateway', 'rest'); | ||
} | ||
|
||
async function initiateUpload(file: Blob): Promise<InitiateUploadResult> { | ||
return await dispatchRequest<InitiateUploadData, InitiateUploadResult>( | ||
'POST', | ||
`https://${getRestApiUrl()}/storage/upload/initiate`, | ||
{ | ||
file_name: file.name, | ||
content_type: file.type || 'application/octet-stream', | ||
} | ||
); | ||
} | ||
|
||
// eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
type KeyValuePair = [string, any]; | ||
|
||
export const storageImpl: StorageSupport = { | ||
upload: async (file: Blob) => { | ||
const { upload_url: uploadUrl, file_url: url } = await initiateUpload(file); | ||
const response = await fetch(uploadUrl, { | ||
method: 'PUT', | ||
body: file, | ||
headers: { | ||
'Content-Type': file.type || 'application/octet-stream', | ||
}, | ||
}); | ||
const { responseHandler } = getConfig(); | ||
await responseHandler(response); | ||
return url; | ||
}, | ||
|
||
// eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
transformInput: async (input: Record<string, any>) => { | ||
const promises = Object.entries(input).map(async ([key, value]) => { | ||
if ( | ||
value instanceof Blob || | ||
(typeof value === 'string' && isDataUri(value)) | ||
) { | ||
let blob = value; | ||
// if string is a data uri, convert to blob | ||
if (typeof value === 'string' && isDataUri(value)) { | ||
const response = await fetch(value); | ||
blob = await response.blob(); | ||
} | ||
const url = await storageImpl.upload(blob as Blob); | ||
return [key, url]; | ||
} | ||
return [key, value] as KeyValuePair; | ||
}); | ||
const results = await Promise.all(promises); | ||
return Object.fromEntries(results); | ||
}, | ||
}; |