Skip to content
Merged
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
23 changes: 23 additions & 0 deletions providers/__tests__/baseDataProvider.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,18 @@ describe('baseDataProvider', () => {
})
);
});

it('sends file content instead of a temporary blob: URL', async () => {
const rawFile = new File(['hello'], 'a.txt', { type: 'text/plain' });
const previousData = { id: 1, fileData: null };
const data = { id: 1, fileData: { src: 'blob:http://app/123', title: 'a.txt', rawFile } };
httpClient.mockResolvedValueOnce({ json: data });

await provider.update('uploaded_file', { id: 1, previousData, data });

const body = JSON.parse(httpClient.mock.calls[0][1].body);
expect(body.fileData.src).toBe('data:text/plain;base64,aGVsbG8=');
});
});

describe('create', () => {
Expand All @@ -124,6 +136,17 @@ describe('baseDataProvider', () => {
);
expect(result).toEqual({ data: { id: 1, title: 'new post' } });
});

it('sends file content instead of a temporary blob: URL', async () => {
const rawFile = new File(['hello'], 'a.txt', { type: 'text/plain' });
const data = { fileData: { src: 'blob:http://app/123', title: 'a.txt', rawFile } };
httpClient.mockResolvedValueOnce({ json: { id: 1 } });

await provider.create('uploaded_file', { data });

const body = JSON.parse(httpClient.mock.calls[0][1].body);
expect(body.fileData.src).toBe('data:text/plain;base64,aGVsbG8=');
});
});

describe('delete', () => {
Expand Down
17 changes: 10 additions & 7 deletions providers/baseDataProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { DataProvider, fetchUtils, GetListParams, RaRecord } from 'react-admin';
import saveAs from 'file-saver';
import { MAX_PAGE_SIZE } from '@shared/config/settings';
import { parseSort } from '@shared/utils/sortUtil';
import { resolvePendingFiles } from '@shared/utils/pendingFiles.util';

/**
* Maps react-admin queries to a nestjsx/crud powered REST API.
Expand Down Expand Up @@ -283,9 +284,9 @@ export default (apiUrl: string, httpClient = fetchUtils.fetchJson): ExtendedData
}));
},

update: (resource, params) => {
update: async (resource, params) => {
// no need to send all fields, only updated fields are enough
const data = countDiff(params.data, params.previousData);
const data = await resolvePendingFiles(countDiff(params.data, params.previousData));
return httpClient(`${apiUrl}/${resource}/${params.id}`, {
method: 'PATCH',
body: JSON.stringify(data),
Expand All @@ -304,13 +305,15 @@ export default (apiUrl: string, httpClient = fetchUtils.fetchJson): ExtendedData
data: responses.map(({ json }) => json),
})),

create: (resource, params) =>
httpClient(`${apiUrl}/${resource}`, {
create: async (resource, params) => {
const data = await resolvePendingFiles(params.data);
return httpClient(`${apiUrl}/${resource}`, {
method: 'POST',
body: JSON.stringify(params.data),
body: JSON.stringify(data),
}).then(({ json }) => ({
data: { ...params.data, id: json.id } as any,
})),
data: { ...data, id: json.id } as any,
}));
},

createMany: (resource, bulk) =>
httpClient(`${apiUrl}/${resource}/bulk`, {
Expand Down
58 changes: 58 additions & 0 deletions utils/__tests__/pendingFiles.util.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { resolvePendingFiles } from '../pendingFiles.util';
import { readAsDataURL } from '@shared/utils/fileUtil';

jest.mock('@shared/utils/fileUtil', () => ({
readAsDataURL: jest.fn(),
}));

const mockReadAsDataURL = readAsDataURL as jest.Mock;

describe('resolvePendingFiles', () => {
beforeEach(() => {
mockReadAsDataURL.mockReset();
mockReadAsDataURL.mockResolvedValue('data:application/pdf;base64,JVBERi0=');
});

it('replaces a blob: src with the data URL of rawFile', async () => {
const rawFile = new File(['%PDF-'], 'a.pdf', { type: 'application/pdf' });
const result = await resolvePendingFiles({
title: 'x',
fileData: { src: 'blob:https://app/123', title: 'a.pdf', rawFile },
});

expect(mockReadAsDataURL).toHaveBeenCalledWith(rawFile);
expect(result.fileData.src).toBe('data:application/pdf;base64,JVBERi0=');
expect(result.fileData.title).toBe('a.pdf');
expect(result.title).toBe('x');
});

it('handles files inside arrays', async () => {
const rawFile = new File(['x'], 'a.png', { type: 'image/png' });
const result = await resolvePendingFiles({ files: [{ src: 'blob:https://app/1', rawFile }] });

expect(result.files[0].src).toBe('data:application/pdf;base64,JVBERi0=');
});

it('leaves already converted files untouched', async () => {
const value = { fileData: { src: 'data:application/pdf;base64,AAA', title: 'a.pdf' } };
const result = await resolvePendingFiles(value);

expect(mockReadAsDataURL).not.toHaveBeenCalled();
expect(result).toEqual(value);
});

it('ignores a blob: src without rawFile', async () => {
const value = { fileData: { src: 'blob:https://app/1' } };
const result = await resolvePendingFiles(value);

expect(mockReadAsDataURL).not.toHaveBeenCalled();
expect(result).toEqual(value);
});

it('passes primitives, null, and dates through', async () => {
const date = new Date('2026-01-01');
expect(await resolvePendingFiles(null)).toBeNull();
expect(await resolvePendingFiles(5)).toBe(5);
expect(await resolvePendingFiles({ d: date })).toEqual({ d: date });
});
});
35 changes: 35 additions & 0 deletions utils/pendingFiles.util.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { readAsDataURL } from '@shared/utils/fileUtil';

const isPlainObject = (value: any): value is Record<string, any> =>
value !== null && typeof value === 'object' && Object.getPrototypeOf(value) === Object.prototype;

const isPendingFile = (value: any): boolean =>
isPlainObject(value) &&
typeof value.src === 'string' &&
value.src.startsWith('blob:') &&
typeof Blob !== 'undefined' &&
value.rawFile instanceof Blob;

/**
* Replaces temporary `blob:` URLs of newly picked files with their base64 data URL.
*
* FileInput values hold a `blob:` src (valid only in the current tab) until the file is read.
* Reading happens asynchronously, so a fast save could send the `blob:` URL to the server.
* Resolving here, right before the request, guarantees the server always gets the file content.
*/
export const resolvePendingFiles = async <T>(data: T): Promise<T> => {
if (Array.isArray(data)) {
return Promise.all(data.map(item => resolvePendingFiles(item))) as any;
}
if (!isPlainObject(data)) {
return data;
}
if (isPendingFile(data)) {
const src = await readAsDataURL(data.rawFile);
return { ...data, src };
}
const entries = await Promise.all(
Object.entries(data).map(async ([key, value]) => [key, await resolvePendingFiles(value)] as const)
);
return Object.fromEntries(entries) as T;
};
Loading