Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: use cdn v3 for uploading files #96

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion libs/client/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@fal-ai/client",
"description": "The fal.ai client for JavaScript and TypeScript",
"version": "1.1.1",
"version": "1.2.0-alpha.2",
"license": "MIT",
"repository": {
"type": "git",
Expand Down
97 changes: 46 additions & 51 deletions libs/client/src/storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,51 +28,59 @@
transformInput: (input: Record<string, any>) => Promise<Record<string, any>>;
}

type InitiateUploadResult = {
file_url: string;
upload_url: string;
type CdnAuthToken = {
base_url: string;
expires_at: string;
token: string;
token_type: string;
};

type InitiateUploadData = {
file_name: string;
content_type: string | null;
};
function isExpired(token: CdnAuthToken): boolean {
return new Date().getTime() >= new Date(token.expires_at).getTime();
}

/**
* Get the file extension from the content type. This is used to generate
* a file name if the file name is not provided.
*
* @param contentType the content type of the file.
* @returns the file extension or `bin` if the content type is not recognized.
*/
function getExtensionFromContentType(contentType: string): string {
const [_, fileType] = contentType.split("/");
return fileType.split(/[-;]/)[0] ?? "bin";
interface TokenManager {
token: CdnAuthToken | null;

fetchToken(config: RequiredConfig): Promise<CdnAuthToken>;

getToken(config: RequiredConfig): Promise<CdnAuthToken>;
}

/**
* Initiate the upload of a file to the server. This returns the URL to upload
* the file to and the URL of the file once it is uploaded.
*
* @param file the file to upload
* @returns the URL to upload the file to and the URL of the file once it is uploaded.
*/
async function initiateUpload(
file: Blob,
config: RequiredConfig,
): Promise<InitiateUploadResult> {
const contentType = file.type || "application/octet-stream";
const filename =
file.name || `${Date.now()}.${getExtensionFromContentType(contentType)}`;
return await dispatchRequest<InitiateUploadData, InitiateUploadResult>({
type UploadCdnResponse = {
access_url: string;
};

const tokenManager: TokenManager = {
token: null,
async getToken(config: RequiredConfig) {
if (!tokenManager.token || isExpired(tokenManager.token)) {
tokenManager.token = await tokenManager.fetchToken(config);
}
return tokenManager.token;
},
async fetchToken(config: RequiredConfig): Promise<CdnAuthToken> {
return dispatchRequest<object, CdnAuthToken>({
method: "POST",
targetUrl: `${getRestApiUrl()}/storage/auth/token?storage_type=fal-cdn-v3`,
config: config,
input: {},
});
},
};

async function uploadFile(file: Blob, config: RequiredConfig) {
const token = await tokenManager.getToken(config);
const response = await fetch(`${token.base_url}/files/upload`, {
method: "POST",
targetUrl: `${getRestApiUrl()}/storage/upload/initiate`,
input: {
content_type: contentType,
file_name: filename,
headers: {
Authorization: `${token.token_type} ${token.token}`,
"Content-Type": file.type || "application/octet-stream",
},
config,
body: file,
});
const result: UploadCdnResponse = await response.json();
return result.access_url;
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
Expand All @@ -87,20 +95,7 @@
}: StorageClientDependencies): StorageClient {
const ref: StorageClient = {
upload: async (file: Blob) => {
const { fetch, responseHandler } = config;
const { upload_url: uploadUrl, file_url: url } = await initiateUpload(
file,
config,
);
const response = await fetch(uploadUrl, {
method: "PUT",
body: file,
headers: {
"Content-Type": file.type || "application/octet-stream",
},
});
await responseHandler(response);
return url;
return await uploadFile(file, config);
},

// eslint-disable-next-line @typescript-eslint/no-explicit-any
Expand All @@ -110,7 +105,7 @@
} else if (input instanceof Blob) {
return await ref.upload(input);
} else if (isPlainObject(input)) {
const inputObject = input as Record<string, any>;

Check warning on line 108 in libs/client/src/storage.ts

View workflow job for this annotation

GitHub Actions / build

Unexpected any. Specify a different type
const promises = Object.entries(inputObject).map(
async ([key, value]): Promise<KeyValuePair> => {
return [key, await ref.transformInput(value)];
Expand Down
Loading