Skip to content

The open alternative to Salesforce, designed for AI.

feat(client-sdk): upload files straight to storage from uploadFile (#26305)

martmull826a4aaeebc0
diff --git a/packages/twenty-client-sdk/src/generate/__tests__/client-wrapper-auth.test.ts b/packages/twenty-client-sdk/src/generate/__tests__/client-wrapper-auth.test.ts
index 10c651d8331..ca66236ca78 100644
--- a/packages/twenty-client-sdk/src/generate/__tests__/client-wrapper-auth.test.ts
+++ b/packages/twenty-client-sdk/src/generate/__tests__/client-wrapper-auth.test.ts
@@ -1,10 +1,3 @@
-import { readFileSync } from 'node:fs';
-import { mkdtemp, rm, writeFile } from 'node:fs/promises';
-import { tmpdir } from 'node:os';
-import { join } from 'node:path';
-import { pathToFileURL } from 'node:url';
-
-import { transform } from 'esbuild';
import {
afterAll,
beforeAll,
@@ -15,128 +8,20 @@ import {
vi,
} from 'vitest';
-import { buildClientWrapperSource } from '../client-wrapper';
-
-const twentyClientTemplateSource = readFileSync(
- join(__dirname, '..', 'twenty-client-template.ts'),
- 'utf-8',
-);
-
-type TwentyClassType = new (options?: {
- url?: string;
- fetch?: typeof globalThis.fetch;
-}) => {
- query: (request: Record<string, unknown>) => Promise<unknown>;
- uploadFile: (
- fileBuffer: Buffer,
- filename: string,
- contentType: string,
- fieldMetadataUniversalIdentifier: string,
- ) => Promise<{
- id: string;
- path: string;
- size: number;
- createdAt: string;
- url: string;
- }>;
-};
-
-const stubGeneratedIndexSource = `
-export type QueryGenqlSelection = Record<string, unknown>
-export type MutationGenqlSelection = Record<string, unknown>
-export type GraphqlOperation = Record<string, unknown>
-
-export type ClientOptions = {
- url?: string
- headers?: HeadersInit | (() => HeadersInit | Promise<HeadersInit>)
- fetcher?: (operation: GraphqlOperation | GraphqlOperation[]) => Promise<unknown>
- fetch?: typeof globalThis.fetch
- batch?: unknown
-}
-
-export type Client = {
- query: (request: QueryGenqlSelection & { __name?: string }) => Promise<unknown>
- mutation: (
- request: MutationGenqlSelection & { __name?: string },
- ) => Promise<unknown>
-}
-
-export class GenqlError extends Error {
- constructor(
- public readonly errors: unknown,
- public readonly data: unknown,
- ) {
- super('GenqlError')
- }
-}
-
-export const createClient = (options: ClientOptions): Client => {
- return {
- query: (request) => {
- return options.fetcher?.({
- query: 'query',
- variables: request,
- })
- },
- mutation: (request) => {
- return options.fetcher?.({
- query: 'mutation',
- variables: request,
- })
- },
- }
-}
-`;
-
-const createJsonResponse = ({
- body,
- status = 200,
- statusText = 'OK',
-}: {
- body: unknown;
- status?: number;
- statusText?: string;
-}) =>
- new Response(JSON.stringify(body), {
- status,
- statusText,
- headers: { 'Content-Type': 'application/json' },
- });
-
-const getAuthorizationHeaderValue = (requestInit: RequestInit | undefined) => {
- return new Headers(requestInit?.headers).get('Authorization');
-};
+import {
+ createJsonResponse,
+ type GeneratedClientClass,
+ getAuthorizationHeaderValue,
+ loadGeneratedClientClass,
+} from './generated-client-test-helpers';
describe('Generated client wrapper auth behavior', () => {
- let temporaryDir: string;
- let TwentyClass: TwentyClassType;
+ let TwentyClass: GeneratedClientClass;
+ let cleanup: () => Promise<void>;
beforeAll(async () => {
- temporaryDir = await mkdtemp(join(tmpdir(), 'twenty-generated-client-'));
-
- const wrapperSource = buildClientWrapperSource(twentyClientTemplateSource, {
- apiClientName: 'MetadataApiClient',
- defaultUrl: '`${process.env.TWENTY_API_URL}/metadata`',
- includeUploadFile: true,
- });
-
- const fullSource = stubGeneratedIndexSource + wrapperSource;
-
- const transpiledModule = await transform(fullSource, {
- loader: 'ts',
- format: 'esm',
- target: 'es2022',
- });
-
- const outputPath = join(temporaryDir, 'index.mjs');
-
- await writeFile(outputPath, transpiledModule.code);
-
- const generatedModule = await import(
- `${pathToFileURL(outputPath).href}?t=${Date.now()}`
- );
-
- TwentyClass = generatedModule.MetadataApiClient as TwentyClassType;
+ ({ GeneratedClientClass: TwentyClass, cleanup } =
+ await loadGeneratedClientClass());
});
beforeEach(() => {
@@ -148,9 +33,7 @@ describe('Generated client wrapper auth behavior', () => {
});
afterAll(async () => {
- if (temporaryDir) {
- await rm(temporaryDir, { recursive: true, force: true });
- }
+ await cleanup();
});
const runQueryCapturingAuthorization = async (
@@ -406,6 +289,10 @@ describe('Generated client wrapper auth behavior', () => {
const fetchMock = vi.fn(
async (_url: string | URL | Request, requestInit?: RequestInit) => {
+ if (requestInit?.method === 'PUT') {
+ return new Response(null, { status: 200 });
+ }
+
const authorizationHeaderValue =
getAuthorizationHeaderValue(requestInit);
@@ -417,10 +304,25 @@ describe('Generated client wrapper auth behavior', () => {
});
}
+ if (String(requestInit?.body).includes('createFileUpload')) {
+ return createJsonResponse({
+ body: {
+ data: {
+ createFileUpload: {
+ fileId: 'uploaded-file-id',
+ uploadUrl:
+ 'https://storage.example.com/pending/uploaded-file-id',
+ contentType: 'application/octet-stream',
+ },
+ },
+ },
+ });
+ }
+
return createJsonResponse({
body: {
data: {
- uploadFilesFieldFileByUniversalIdentifier: {
+ completeFileUpload: {
id: 'uploaded-file-id',
path: 'test/path.txt',
size: 10,
@@ -438,16 +340,17 @@ describe('Generated client wrapper auth behavior', () => {
fetch: fetchMock as unknown as typeof globalThis.fetch,
});
- const uploadResult = await twentyClient.uploadFile(
- Buffer.from('content'),
- 'test.txt',
- 'text/plain',
- 'field-uuid',
- );
+ const uploadResult = await twentyClient.uploadFile({
+ fileBuffer: Buffer.from('content'),
+ filename: 'test.txt',
+ fieldMetadataUniversalIdentifier: 'field-uuid',
+ });
expect(uploadResult.id).toBe('uploaded-file-id');
expect(requestAccessTokenRefresh).toHaveBeenCalledTimes(1);
- expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(
+ fetchMock.mock.calls.map(([, requestInit]) => requestInit?.method),
+ ).toEqual(['POST', 'POST', 'PUT', 'POST']);
});
it('bubbles auth error when refresh callback throws', async () => {
diff --git a/packages/twenty-client-sdk/src/generate/__tests__/client-wrapper-upload-file.test.ts b/packages/twenty-client-sdk/src/generate/__tests__/client-wrapper-upload-file.test.ts
new file mode 100644
index 00000000000..cdd53a95e6e
--- /dev/null
+++ b/packages/twenty-client-sdk/src/generate/__tests__/client-wrapper-upload-file.test.ts
@@ -0,0 +1,222 @@
+import {
+ afterAll,
+ beforeAll,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi,
+} from 'vitest';
+
+import {
+ createJsonResponse,
+ type GeneratedClientClass,
+ getAuthorizationHeaderValue,
+ loadGeneratedClientClass,
+} from './generated-client-test-helpers';
+
+const CLIENT_URL = 'https://example.com/metadata';
+const FIELD_METADATA_UNIVERSAL_IDENTIFIER = 'field-universal-identifier';
+
+const uploadTarget = {
+ fileId: 'file-id',
+ uploadUrl: 'https://storage.example.com/pending/file-id?signature=abc',
+ contentType: 'application/octet-stream',
+};
+
+const uploadedFile = {
+ id: 'file-id',
+ path: 'files-field/field-universal-identifier/file-id.pdf',
+ size: 7,
+ createdAt: '2026-02-24T00:00:00.000Z',
+ url: 'https://example.com/file/files-field/file-id?token=xyz',
+};
+
+type CapturedRequest = {
+ url: string;
+ requestInit: RequestInit | undefined;
+};
+
+const parseGraphqlBody = (requestInit: RequestInit | undefined) =>
+ JSON.parse(String(requestInit?.body)) as {
+ query: string;
+ variables: Record<string, unknown>;
+ };
+
+const createFetchMock = ({
+ putResponse = () => new Response(null, { status: 200 }),
+ createFileUploadResponse = () =>
+ createJsonResponse({ body: { data: { createFileUpload: uploadTarget } } }),
+ completeFileUploadResponse = () =>
+ createJsonResponse({
+ body: { data: { completeFileUpload: uploadedFile } },
+ }),
+}: {
+ putResponse?: () => Response;
+ createFileUploadResponse?: () => Response;
+ completeFileUploadResponse?: () => Response;
+} = {}) => {
+ const capturedRequests: CapturedRequest[] = [];
+
+ const fetchMock = vi.fn(
+ async (url: string | URL | Request, requestInit?: RequestInit) => {
+ capturedRequests.push({ url: String(url), requestInit });
+
+ if (requestInit?.method === 'PUT') {
+ return putResponse();
+ }
+
+ if (requestInit?.body instanceof FormData) {
+ throw new Error('Unexpected multipart request');
+ }
+
+ const { query } = parseGraphqlBody(requestInit);
+
+ if (query.includes('createFileUpload')) {
+ return createFileUploadResponse();
+ }
+
+ if (query.includes('completeFileUpload')) {
+ return completeFileUploadResponse();
+ }
+
+ throw new Error(`Unexpected GraphQL operation: ${query}`);
+ },
+ );
+
+ return { fetchMock, capturedRequests };
+};
+
+const refusedMutationResponse = (message: string) => () =>
+ createJsonResponse({
+ body: {
+ errors: [{ message }],
+ data: null,
+ },
+ });
+
+describe('Generated client wrapper uploadFile', () => {
+ let TwentyClass: GeneratedClientClass;
+ let cleanup: () => Promise<void>;
+
+ const createClient = (fetchMock: ReturnType<typeof vi.fn>) =>
+ new TwentyClass({
+ url: CLIENT_URL,
+ fetch: fetchMock as unknown as typeof globalThis.fetch,
+ });
+
+ const uploadInvoice = (
+ twentyClient: InstanceType<GeneratedClientClass>,
+ fileBuffer = Buffer.from('content'),
+ ) =>
+ twentyClient.uploadFile({
+ fileBuffer,
+ filename: 'invoice.pdf',
+ fieldMetadataUniversalIdentifier: FIELD_METADATA_UNIVERSAL_IDENTIFIER,
+ });
+
+ beforeAll(async () => {
+ ({ GeneratedClientClass: TwentyClass, cleanup } =
+ await loadGeneratedClientClass());
+ });
+
+ beforeEach(() => {
+ process.env.TWENTY_APP_ACCESS_TOKEN = 'application-token';
+ delete process.env.TWENTY_APP_APPLICATION_ACCESS_TOKEN;
+ delete process.env.TWENTY_API_KEY;
+ delete (globalThis as Record<string, unknown>)
+ .frontComponentHostCommunicationApi;
+ });
+
+ afterAll(async () => {
+ await cleanup();
+ });
+
+ it('creates an upload target, sends the bytes to it, then completes the upload', async () => {
+ const { fetchMock, capturedRequests } = createFetchMock();
+ const fileBuffer = Buffer.from('content');
+
+ const result = await uploadInvoice(createClient(fetchMock), fileBuffer);
+
+ expect(result).toEqual(uploadedFile);
+ expect(capturedRequests).toHaveLength(3);
+
+ const [createRequest, putRequest, completeRequest] = capturedRequests;
+
+ expect(createRequest.url).toBe(CLIENT_URL);
+ expect(getAuthorizationHeaderValue(createRequest.requestInit)).toBe(
+ 'Bearer application-token',
+ );
+ const createBody = parseGraphqlBody(createRequest.requestInit);
+ expect(createBody.query).toContain('fileFolder: FilesField');
+ expect(createBody.variables).toEqual({
+ filename: 'invoice.pdf',
+ size: fileBuffer.byteLength,
+ fieldMetadataUniversalIdentifier: FIELD_METADATA_UNIVERSAL_IDENTIFIER,
+ });
+
+ expect(putRequest.url).toBe(uploadTarget.uploadUrl);
+ expect(putRequest.requestInit?.method).toBe('PUT');
+ expect(putRequest.requestInit?.body).toBe(fileBuffer);
+ expect(
+ new Headers(putRequest.requestInit?.headers).get('Content-Type'),
+ ).toBe(uploadTarget.contentType);
+ expect(getAuthorizationHeaderValue(putRequest.requestInit)).toBeNull();
+
+ expect(completeRequest.url).toBe(CLIENT_URL);
+ expect(getAuthorizationHeaderValue(completeRequest.requestInit)).toBe(
+ 'Bearer application-token',
+ );
+ expect(parseGraphqlBody(completeRequest.requestInit).variables).toEqual({
+ fileId: uploadTarget.fileId,
+ });
+ });
+
+ it('sends nothing to storage when the upload target is refused', async () => {
+ const { fetchMock, capturedRequests } = createFetchMock({
+ createFileUploadResponse: refusedMutationResponse(
+ 'The file is empty or exceeds the maximum allowed size.',
+ ),
+ });
+
+ await expect(uploadInvoice(createClient(fetchMock))).rejects.toThrow(
+ 'GenqlError',
+ );
+
+ expect(capturedRequests).toHaveLength(1);
+ });
+
+ it('does not complete the upload when storage refuses the bytes', async () => {
+ const { fetchMock, capturedRequests } = createFetchMock({
+ putResponse: () =>
+ new Response('<Error>SignatureDoesNotMatch</Error>', {
+ status: 403,
+ statusText: 'Forbidden',
+ }),
+ });
+
+ await expect(uploadInvoice(createClient(fetchMock))).rejects.toThrow(
+ 'File upload failed (403 Forbidden): <Error>SignatureDoesNotMatch</Error>',
+ );
+
+ expect(
+ capturedRequests.map(({ requestInit }) => requestInit?.method),
+ ).toEqual(['POST', 'PUT']);
+ });
+
+ it('surfaces the completion error', async () => {
+ const { fetchMock, capturedRequests } = createFetchMock({
+ completeFileUploadResponse: refusedMutationResponse(
+ 'MIME type text/plain is not allowed in file folder FilesField',
+ ),
+ });
+
+ await expect(uploadInvoice(createClient(fetchMock))).rejects.toThrow(
+ 'GenqlError',
+ );
+
+ expect(
+ capturedRequests.map(({ requestInit }) => requestInit?.method),
+ ).toEqual(['POST', 'PUT', 'POST']);
+ });
+});
diff --git a/packages/twenty-client-sdk/src/generate/__tests__/generated-client-test-helpers.ts b/packages/twenty-client-sdk/src/generate/__tests__/generated-client-test-helpers.ts
new file mode 100644
index 00000000000..05f13972de9
--- /dev/null
+++ b/packages/twenty-client-sdk/src/generate/__tests__/generated-client-test-helpers.ts
@@ -0,0 +1,139 @@
+import { readFileSync } from 'node:fs';
+import { mkdtemp, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { pathToFileURL } from 'node:url';
+
+import { transform } from 'esbuild';
+
+import { buildClientWrapperSource } from '../client-wrapper';
+
+const twentyClientTemplateSource = readFileSync(
+ join(__dirname, '..', 'twenty-client-template.ts'),
+ 'utf-8',
+);
+
+export type GeneratedUploadedFile = {
+ id: string;
+ path: string;
+ size: number;
+ createdAt: string;
+ url: string;
+};
+
+export type GeneratedClientClass = new (options?: {
+ url?: string;
+ fetch?: typeof globalThis.fetch;
+}) => {
+ query: (request: Record<string, unknown>) => Promise<unknown>;
+ uploadFile: (input: {
+ fileBuffer: Buffer;
+ filename: string;
+ fieldMetadataUniversalIdentifier: string;
+ }) => Promise<GeneratedUploadedFile>;
+};
+
+const stubGeneratedIndexSource = `
+export type QueryGenqlSelection = Record<string, unknown>
+export type MutationGenqlSelection = Record<string, unknown>
+export type GraphqlOperation = Record<string, unknown>
+
+export type ClientOptions = {
+ url?: string
+ headers?: HeadersInit | (() => HeadersInit | Promise<HeadersInit>)
+ fetcher?: (operation: GraphqlOperation | GraphqlOperation[]) => Promise<unknown>
+ fetch?: typeof globalThis.fetch
+ batch?: unknown
+}
+
+export type Client = {
+ query: (request: QueryGenqlSelection & { __name?: string }) => Promise<unknown>
+ mutation: (
+ request: MutationGenqlSelection & { __name?: string },
+ ) => Promise<unknown>
+}
+
+export class GenqlError extends Error {
+ constructor(
+ public readonly errors: unknown,
+ public readonly data: unknown,
+ ) {
+ super('GenqlError')
+ }
+}
+
+export const createClient = (options: ClientOptions): Client => {
+ return {
+ query: (request) => {
+ return options.fetcher?.({
+ query: 'query',
+ variables: request,
+ })
+ },
+ mutation: (request) => {
+ return options.fetcher?.({
+ query: 'mutation',
+ variables: request,
+ })
+ },
+ }
+}
+`;
+
+export const loadGeneratedClientClass = async (): Promise<{
+ GeneratedClientClass: GeneratedClientClass;
+ cleanup: () => Promise<void>;
+}> => {
+ const temporaryDir = await mkdtemp(
+ join(tmpdir(), 'twenty-generated-client-'),
+ );
+
+ const wrapperSource = buildClientWrapperSource(twentyClientTemplateSource, {
+ apiClientName: 'MetadataApiClient',
+ defaultUrl: '`${process.env.TWENTY_API_URL}/metadata`',
+ includeUploadFile: true,
+ });
+
+ const transpiledModule = await transform(
+ stubGeneratedIndexSource + wrapperSource,
+ {
+ loader: 'ts',
+ format: 'esm',
+ target: 'es2022',
+ },
+ );
+
+ const outputPath = join(temporaryDir, 'index.mjs');
+
+ await writeFile(outputPath, transpiledModule.code);
+
+ const generatedModule = await import(
+ `${pathToFileURL(outputPath).href}?t=${Date.now()}`
+ );
+
+ return {
+ GeneratedClientClass: generatedModule.MetadataApiClient,
+ cleanup: () => rm(temporaryDir, { recursive: true, force: true }),
+ };
+};
+
+export const createJsonResponse = ({
+ body,
+ status = 200,
+ statusText = 'OK',
+}: {
+ body: unknown;
+ status?: number;
+ statusText?: string;
+}) =>
+ new Response(JSON.stringify(body), {
+ status,
+ statusText,
+ headers: { 'Content-Type': 'application/json' },
+ });
+
+export const getAuthorizationHeaderValue = (
+ requestInit: RequestInit | undefined,
+) => {
+ return new Headers(requestInit?.headers).get('Authorization');
+};
diff --git a/packages/twenty-client-sdk/src/generate/twenty-client-template.ts b/packages/twenty-client-sdk/src/generate/twenty-client-template.ts
index a3f33f0ec63..58e07a0c246 100644
--- a/packages/twenty-client-sdk/src/generate/twenty-client-template.ts
+++ b/packages/twenty-client-sdk/src/generate/twenty-client-template.ts
@@ -61,6 +61,20 @@ type GraphqlResponse = {
rawBody: string;
};
+type FilesFieldUploadTarget = {
+ fileId: string;
+ uploadUrl: string;
+ contentType: string;
+};
+
+type FilesFieldUploadedFile = {
+ id: string;
+ path: string;
+ size: number;
+ createdAt: string;
+ url: string;
+};
+
const getProcessEnvironment = (): ProcessEnvironment => {
const processObject = (
globalThis as { process?: { env?: ProcessEnvironment } }
@@ -210,60 +224,91 @@ export class TwentyGeneratedClient {
}
// __UPLOAD_FILE_START__
- async uploadFile(
- fileBuffer: Buffer,
- filename: string,
- contentType: string = 'application/octet-stream',
- fieldMetadataUniversalIdentifier: string,
- ): Promise<{
- id: string;
- path: string;
- size: number;
- createdAt: string;
- url: string;
- }> {
- const form = new FormData();
-
- form.append(
- 'operations',
- JSON.stringify({
- query: `mutation UploadFilesFieldFileByUniversalIdentifier($file: Upload!, $fieldMetadataUniversalIdentifier: String!) {
- uploadFilesFieldFileByUniversalIdentifier(file: $file, fieldMetadataUniversalIdentifier: $fieldMetadataUniversalIdentifier) { id path size createdAt url }
+ async uploadFile({
+ fileBuffer,
+ filename,
+ fieldMetadataUniversalIdentifier,
+ }: {
+ fileBuffer: Buffer;
+ filename: string;
+ fieldMetadataUniversalIdentifier: string;
+ }): Promise<FilesFieldUploadedFile> {
+ const { createFileUpload: uploadTarget } =
+ await this.executeMutationOrThrow<{
+ createFileUpload: FilesFieldUploadTarget;
+ }>({
+ query: `mutation CreateFilesFieldFileUpload($filename: String!, $size: Float!, $fieldMetadataUniversalIdentifier: String!) {
+ createFileUpload(filename: $filename, size: $size, fileFolder: FilesField, fieldMetadataUniversalIdentifier: $fieldMetadataUniversalIdentifier) { fileId uploadUrl contentType }
}`,
variables: {
- file: null,
+ filename,
+ size: fileBuffer.byteLength,
fieldMetadataUniversalIdentifier,
},
- }),
- );
- form.append('map', JSON.stringify({ '0': ['variables.file'] }));
- form.append(
- '0',
- new Blob([fileBuffer as BlobPart], { type: contentType }),
- filename,
+ });
+
+ await this.putFileToUploadTargetOrThrow({ fileBuffer, uploadTarget });
+
+ const { completeFileUpload: uploadedFile } =
+ await this.executeMutationOrThrow<{
+ completeFileUpload: FilesFieldUploadedFile;
+ }>({
+ query: `mutation CompleteFilesFieldFileUpload($fileId: String!) {
+ completeFileUpload(fileId: $fileId) { id path size createdAt url }
+ }`,
+ variables: { fileId: uploadTarget.fileId },
+ });
+
+ return uploadedFile;
+ }
+
+ private async putFileToUploadTargetOrThrow({
+ fileBuffer,
+ uploadTarget,
+ }: {
+ fileBuffer: Buffer;
+ uploadTarget: FilesFieldUploadTarget;
+ }): Promise<void> {
+ const fetchImplementation = this.getFetchImplementationOrThrow();
+
+ const response = await fetchImplementation.call(
+ globalThis,
+ uploadTarget.uploadUrl,
+ {
+ method: 'PUT',
+ headers: { 'Content-Type': uploadTarget.contentType },
+ body: fileBuffer as BodyInit,
+ credentials: 'omit',
+ },
);
+ if (!response.ok) {
+ throw new Error(
+ `File upload failed (${response.status} ${response.statusText}): ${await response.text()}`,
+ );
+ }
+ }
+
+ private async executeMutationOrThrow<TData>({
+ query,
+ variables,
+ }: {
+ query: string;
+ variables: Record<string, unknown>;
+ }): Promise<TData> {
const result = await this.executeGraphqlRequestWithOptionalRefresh({
- operation: form,
- headers: {},
- requestInit: {
- method: 'POST',
- },
+ operation: { query, variables },
});
if (result.errors) {
throw new GenqlError(result.errors, result.data);
}
- const data = result.data as Record<string, unknown>;
+ if (!result.data) {
+ throw new Error('Empty GraphQL response');
+ }
- return data.uploadFilesFieldFileByUniversalIdentifier as {
- id: string;
- path: string;
- size: number;
- createdAt: string;
- url: string;
- };
+ return result.data as TData;
}
// __UPLOAD_FILE_END__
@@ -312,12 +357,7 @@ export class TwentyGeneratedClient {
requestInit?: RequestInit;
token: string | null;
}): Promise<GraphqlResponse> {
- if (!this.fetchImplementation) {
- throw new Error(
- 'Global `fetch` function is not available, ' +
- 'pass a fetch implementation to the Twenty client',
- );
- }
+ const fetchImplementation = this.getFetchImplementationOrThrow();
const resolvedHeaders = await this.resolveHeaders();
const requestHeaders = new Headers(resolvedHeaders);
@@ -340,7 +380,7 @@ export class TwentyGeneratedClient {
requestHeaders.delete('Authorization');
}
- const response = await this.fetchImplementation.call(globalThis, this.url, {
+ const response = await fetchImplementation.call(globalThis, this.url, {
...this.requestOptions,
...requestInit,
method: requestInit?.method ?? 'POST',
@@ -368,6 +408,17 @@ export class TwentyGeneratedClient {
};
}
+ private getFetchImplementationOrThrow(): typeof globalThis.fetch {
+ if (!this.fetchImplementation) {
+ throw new Error(
+ 'Global `fetch` function is not available, ' +
+ 'pass a fetch implementation to the Twenty client',
+ );
+ }
+
+ return this.fetchImplementation;
+ }
+
private async resolveHeaders(): Promise<HeadersInit> {
if (typeof this.headers === 'function') {
return (await this.headers()) ?? {};
diff --git a/packages/twenty-client-sdk/src/metadata/generated/index.ts b/packages/twenty-client-sdk/src/metadata/generated/index.ts
index b25a37468ad..f313a5e9efd 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/index.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/index.ts
@@ -100,6 +100,20 @@ type GraphqlResponse = {
rawBody: string;
};
+type FilesFieldUploadTarget = {
+ fileId: string;
+ uploadUrl: string;
+ contentType: string;
+};
+
+type FilesFieldUploadedFile = {
+ id: string;
+ path: string;
+ size: number;
+ createdAt: string;
+ url: string;
+};
+
const getProcessEnvironment = (): ProcessEnvironment => {
const processObject = (
globalThis as { process?: { env?: ProcessEnvironment } }
@@ -247,60 +261,91 @@ export class MetadataApiClient {
mutation<R extends MutationGenqlSelection>(request: R & { __name?: string }) {
return this.client.mutation(request);
}
- async uploadFile(
- fileBuffer: Buffer,
- filename: string,
- contentType: string = 'application/octet-stream',
- fieldMetadataUniversalIdentifier: string,
- ): Promise<{
- id: string;
- path: string;
- size: number;
- createdAt: string;
- url: string;
- }> {
- const form = new FormData();
-
- form.append(
- 'operations',
- JSON.stringify({
- query: `mutation UploadFilesFieldFileByUniversalIdentifier($file: Upload!, $fieldMetadataUniversalIdentifier: String!) {
- uploadFilesFieldFileByUniversalIdentifier(file: $file, fieldMetadataUniversalIdentifier: $fieldMetadataUniversalIdentifier) { id path size createdAt url }
+ async uploadFile({
+ fileBuffer,
+ filename,
+ fieldMetadataUniversalIdentifier,
+ }: {
+ fileBuffer: Buffer;
+ filename: string;
+ fieldMetadataUniversalIdentifier: string;
+ }): Promise<FilesFieldUploadedFile> {
+ const { createFileUpload: uploadTarget } =
+ await this.executeMutationOrThrow<{
+ createFileUpload: FilesFieldUploadTarget;
+ }>({
+ query: `mutation CreateFilesFieldFileUpload($filename: String!, $size: Float!, $fieldMetadataUniversalIdentifier: String!) {
+ createFileUpload(filename: $filename, size: $size, fileFolder: FilesField, fieldMetadataUniversalIdentifier: $fieldMetadataUniversalIdentifier) { fileId uploadUrl contentType }
}`,
variables: {
- file: null,
+ filename,
+ size: fileBuffer.byteLength,
fieldMetadataUniversalIdentifier,
},
- }),
- );
- form.append('map', JSON.stringify({ '0': ['variables.file'] }));
- form.append(
- '0',
- new Blob([fileBuffer as BlobPart], { type: contentType }),
- filename,
+ });
+
+ await this.putFileToUploadTargetOrThrow({ fileBuffer, uploadTarget });
+
+ const { completeFileUpload: uploadedFile } =
+ await this.executeMutationOrThrow<{
+ completeFileUpload: FilesFieldUploadedFile;
+ }>({
+ query: `mutation CompleteFilesFieldFileUpload($fileId: String!) {
+ completeFileUpload(fileId: $fileId) { id path size createdAt url }
+ }`,
+ variables: { fileId: uploadTarget.fileId },
+ });
+
+ return uploadedFile;
+ }
+
+ private async putFileToUploadTargetOrThrow({
+ fileBuffer,
+ uploadTarget,
+ }: {
+ fileBuffer: Buffer;
+ uploadTarget: FilesFieldUploadTarget;
+ }): Promise<void> {
+ const fetchImplementation = this.getFetchImplementationOrThrow();
+
+ const response = await fetchImplementation.call(
+ globalThis,
+ uploadTarget.uploadUrl,
+ {
+ method: 'PUT',
+ headers: { 'Content-Type': uploadTarget.contentType },
+ body: fileBuffer as BodyInit,
+ credentials: 'omit',
+ },
);
+ if (!response.ok) {
+ throw new Error(
+ `File upload failed (${response.status} ${response.statusText}): ${await response.text()}`,
+ );
+ }
+ }
+
+ private async executeMutationOrThrow<TData>({
+ query,
+ variables,
+ }: {
+ query: string;
+ variables: Record<string, unknown>;
+ }): Promise<TData> {
const result = await this.executeGraphqlRequestWithOptionalRefresh({
- operation: form,
- headers: {},
- requestInit: {
- method: 'POST',
- },
+ operation: { query, variables },
});
if (result.errors) {
throw new GenqlError(result.errors, result.data);
}
- const data = result.data as Record<string, unknown>;
+ if (!result.data) {
+ throw new Error('Empty GraphQL response');
+ }
- return data.uploadFilesFieldFileByUniversalIdentifier as {
- id: string;
- path: string;
- size: number;
- createdAt: string;
- url: string;
- };
+ return result.data as TData;
}
private async executeGraphqlRequestWithOptionalRefresh({
@@ -348,12 +393,7 @@ export class MetadataApiClient {
requestInit?: RequestInit;
token: string | null;
}): Promise<GraphqlResponse> {
- if (!this.fetchImplementation) {
- throw new Error(
- 'Global `fetch` function is not available, ' +
- 'pass a fetch implementation to the Twenty client',
- );
- }
+ const fetchImplementation = this.getFetchImplementationOrThrow();
const resolvedHeaders = await this.resolveHeaders();
const requestHeaders = new Headers(resolvedHeaders);
@@ -376,7 +416,7 @@ export class MetadataApiClient {
requestHeaders.delete('Authorization');
}
- const response = await this.fetchImplementation.call(globalThis, this.url, {
+ const response = await fetchImplementation.call(globalThis, this.url, {
...this.requestOptions,
...requestInit,
method: requestInit?.method ?? 'POST',
@@ -404,6 +444,17 @@ export class MetadataApiClient {
};
}
+ private getFetchImplementationOrThrow(): typeof globalThis.fetch {
+ if (!this.fetchImplementation) {
+ throw new Error(
+ 'Global `fetch` function is not available, ' +
+ 'pass a fetch implementation to the Twenty client',
+ );
+ }
+
+ return this.fetchImplementation;
+ }
+
private async resolveHeaders(): Promise<HeadersInit> {
if (typeof this.headers === 'function') {
return (await this.headers()) ?? {};
diff --git a/packages/twenty-docs/developers/extend/apps/logic/logic-functions.mdx b/packages/twenty-docs/developers/extend/apps/logic/logic-functions.mdx
index 7f5ebf07299..a754a9cbbec 100644
--- a/packages/twenty-docs/developers/extend/apps/logic/logic-functions.mdx
+++ b/packages/twenty-docs/developers/extend/apps/logic/logic-functions.mdx
@@ -1045,7 +1045,7 @@ const { objects } = await metadataClient.query({
#### Uploading files
-`MetadataApiClient` includes an `uploadFile` method for attaching files to file-type fields:
+`MetadataApiClient` includes an `uploadFile` method for attaching files to file-type fields. The file goes straight to Twenty's file storage: the API issues an upload target, the client sends the bytes there, then the API confirms the upload.
```ts
import { MetadataApiClient } from 'twenty-client-sdk/metadata';
@@ -1053,14 +1053,11 @@ import * as fs from 'fs';
const metadataClient = new MetadataApiClient();
-const fileBuffer = fs.readFileSync('./invoice.pdf');
-
-const uploadedFile = await metadataClient.uploadFile(
- fileBuffer, // file contents as a Buffer
- 'invoice.pdf', // filename
- 'application/pdf', // MIME type
- '58a0a314-d7ea-4865-9850-7fb84e72f30b', // field universalIdentifier
-);
+const uploadedFile = await metadataClient.uploadFile({
+ fileBuffer: fs.readFileSync('./invoice.pdf'),
+ filename: 'invoice.pdf',
+ fieldMetadataUniversalIdentifier: '58a0a314-d7ea-4865-9850-7fb84e72f30b',
+});
console.log(uploadedFile);
// { id: '...', path: '...', size: 12345, createdAt: '...', url: 'https://...' }
@@ -1070,11 +1067,11 @@ console.log(uploadedFile);
|-----------|------|-------------|
| `fileBuffer` | `Buffer` | The raw file contents |
| `filename` | `string` | The name of the file (used for storage and display) |
-| `contentType` | `string` | MIME type (defaults to `application/octet-stream` if omitted) |
| `fieldMetadataUniversalIdentifier` | `string` | The `universalIdentifier` of the file-type field on your object |
Key points:
- Uses the field's `universalIdentifier` (not its workspace-specific ID), so your upload code works across any workspace where your app is installed.
+- The MIME type is detected from the file contents once uploaded, so there is nothing to declare.
- The returned `url` is a signed URL you can use to access the uploaded file.
</Accordion>
diff --git a/packages/twenty-docs/developers/extend/apps/tutorials/document-generator/generating-documents.mdx b/packages/twenty-docs/developers/extend/apps/tutorials/document-generator/generating-documents.mdx
index 8d441392a96..fae676d2989 100644
--- a/packages/twenty-docs/developers/extend/apps/tutorials/document-generator/generating-documents.mdx
+++ b/packages/twenty-docs/developers/extend/apps/tutorials/document-generator/generating-documents.mdx
@@ -188,8 +188,9 @@ can't encode. Rendering non-Latin scripts (Chinese, Arabic, Cyrillic) would mean
embedding a Unicode font.
</Note>
-Then upload it and store the reference on the record. `uploadFile` routes bytes
-to your app-owned files field; the returned `id` is what you save:
+Then upload it and store the reference on the record. `uploadFile` sends the
+bytes straight to file storage and attaches them to your app-owned files field;
+the returned `id` is what you save:
```ts filename="src/logic-functions/handlers/generate-document-handler.ts"
import { MetadataApiClient } from 'twenty-client-sdk/metadata';
@@ -199,12 +200,11 @@ const documentName = `${documentTemplate.name} — ${record.displayName}`;
const bytes = await generateDocumentPdf(documentName, content);
const fileName = 'proposal.pdf';
-const uploaded = await new MetadataApiClient().uploadFile(
- Buffer.from(bytes),
- fileName,
- 'application/pdf',
- DOCUMENT_FILE_FIELD_UNIVERSAL_IDENTIFIER,
-);
+const uploaded = await new MetadataApiClient().uploadFile({
+ fileBuffer: Buffer.from(bytes),
+ filename: fileName,
+ fieldMetadataUniversalIdentifier: DOCUMENT_FILE_FIELD_UNIVERSAL_IDENTIFIER,
+});
await client.mutation({
updateDocument: {
diff --git a/packages/twenty-sdk/CHANGELOG.md b/packages/twenty-sdk/CHANGELOG.md
index 0ae7b89ecd3..3bca8d3a1d2 100644
--- a/packages/twenty-sdk/CHANGELOG.md
+++ b/packages/twenty-sdk/CHANGELOG.md
@@ -6,6 +6,26 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and
## [Unreleased]
+### Breaking Changes
+
+- **`MetadataApiClient.uploadFile` in `twenty-client-sdk` takes one object and no longer accepts a content type.** The file now goes straight to Twenty's file storage (the API issues an upload target, the client sends the bytes there, then the API confirms the upload) instead of being streamed through the GraphQL API, and the MIME type is detected from the bytes on completion. Update every call:
+
+ ```diff
+ - const uploaded = await metadataClient.uploadFile(
+ - fileBuffer,
+ - 'invoice.pdf',
+ - 'application/pdf',
+ - FIELD_UNIVERSAL_IDENTIFIER,
+ - );
+ + const uploaded = await metadataClient.uploadFile({
+ + fileBuffer,
+ + filename: 'invoice.pdf',
+ + fieldMetadataUniversalIdentifier: FIELD_UNIVERSAL_IDENTIFIER,
+ + });
+ ```
+
+ The returned `{ id, path, size, createdAt, url }` is unchanged. `uploadFile` now requires a Twenty server that exposes the `createFileUpload` and `completeFileUpload` mutations.
+
### Added
- **`enqueueJobs` in `twenty-sdk/logic-function`.** Enqueues one run per payload of a single logic function in one call (up to 200 payloads per batch). `retryLimit` and `delayMs` apply to every run in the batch.