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
50 changes: 49 additions & 1 deletion providers/__tests__/baseDataProvider.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import baseDataProvider from '../baseDataProvider';
import baseDataProvider, { FILE_DOWNLOAD_INCOMPLETE_KEY } from '../baseDataProvider';
import saveAs from 'file-saver';
import { GetListParams, SortPayload } from 'react-admin';

Expand Down Expand Up @@ -184,6 +184,54 @@ describe('baseDataProvider', () => {

expect(mockSaveAs).toHaveBeenCalledWith(mockBlob, 'test.json');
});

describe('incomplete file responses', () => {
const params: GetListParams = {
pagination: { page: 1, perPage: 10 },
sort: { field: 'id', order: 'ASC' } as SortPayload,
filter: {},
};
let consoleError: jest.SpyInstance;

beforeEach(() => {
consoleError = jest.spyOn(console, 'error').mockImplementation(() => {});
});

afterEach(() => {
consoleError.mockRestore();
});

it('throws the translatable incomplete-download error on content length mismatch', async () => {
httpClient.mockResolvedValueOnce({
json: { type: 'application/pdf', data: 'abc', disposition: '', contentLength: 10 },
});

const error = await provider.export('posts', params, 'pdf', 'Posts').catch(e => e);

expect(error.message).toBe(FILE_DOWNLOAD_INCOMPLETE_KEY);
expect(error.details).toBe('content length mismatch: expected 10, got 3');
expect(consoleError).toHaveBeenCalled();
expect(mockSaveAs).not.toHaveBeenCalled();
});

it('throws the same error when response keys are missing', async () => {
httpClient.mockResolvedValueOnce({ json: { type: 'application/pdf' } });

const error = await provider.export('posts', params, 'pdf', 'Posts').catch(e => e);

expect(error.message).toBe(FILE_DOWNLOAD_INCOMPLETE_KEY);
expect(error.details).toBe('missing keys: data, disposition, contentLength');
});

it('throws the same error on an empty response', async () => {
httpClient.mockResolvedValueOnce({ json: null });

const error = await provider.export('posts', params, 'pdf', 'Posts').catch(e => e);

expect(error.message).toBe(FILE_DOWNLOAD_INCOMPLETE_KEY);
expect(error.details).toBe('empty response');
});
});
});

describe('getCount', () => {
Expand Down
10 changes: 10 additions & 0 deletions providers/__tests__/i18nProvider.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,11 @@ describe('i18nProvider', () => {
expect(i18nProvider.translate('ra.auth.organization_name')).toBe('שם המוסד');
});

it('translates download and PDF busy errors in Hebrew', () => {
expect(i18nProvider.translate('ra.notification.file_download_incomplete')).toContain('סינון האינטרנט');
expect(i18nProvider.translate('ra.notification.pdf_render_busy')).toBe('המערכת מפיקה כרגע דוחות אחרים. נא לנסות שוב בעוד מספר דקות.');
});

it('handles missing translations by returning the key', () => {
expect(i18nProvider.translate('ra.action.nonexistent')).toBe('ra.action.nonexistent');
});
Expand All @@ -141,6 +146,11 @@ describe('i18nProvider', () => {
expect(i18nProvider.translate('ra.action.save')).toBe('Save');
expect(i18nProvider.translate('ra.auth.organization_name')).toBe('Organization Name');
});

it('translates download and PDF busy errors in English', () => {
expect(i18nProvider.translate('ra.notification.file_download_incomplete')).toContain('content filter');
expect(i18nProvider.translate('ra.notification.pdf_render_busy')).toBe('The system is currently generating other reports. Please try again in a few minutes.');
});
});
});

Expand Down
21 changes: 17 additions & 4 deletions providers/baseDataProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -166,19 +166,32 @@ const saveResponseFile = async (res, filename) => {
return saveAs(blob, calcFileName(res.json.disposition, filename));
}

// Translation key shown to the user when a file response arrives incomplete or
// malformed. The usual cause is a content filter on the user's network that
// blocks or truncates the download, so the message explains that instead of
// exposing the technical details.
export const FILE_DOWNLOAD_INCOMPLETE_KEY = 'ra.notification.file_download_incomplete';

const fileResponseError = (details: string) => {
console.error(`Invalid file response: ${details}`);
const error = new Error(FILE_DOWNLOAD_INCOMPLETE_KEY);
(error as any).details = details;
return error;
}

const validateFileResponse = (response: any) => {
if (!response) {
throw new Error('Invalid file response');
throw fileResponseError('empty response');
}
const expectedKeys = ['data', 'type', 'disposition', 'contentLength'];
const missingKeys = expectedKeys.filter(key => !(key in response));
if (missingKeys.length > 0) {
throw new Error(`Invalid file response, missing keys: ${missingKeys.join(', ')}`);
throw fileResponseError(`missing keys: ${missingKeys.join(', ')}`);
}
const { data, contentLength } = response;
const actualLength = data.length;
const actualLength = data?.length;
if (actualLength !== contentLength) {
throw new Error(`Invalid file response, content length mismatch: expected ${contentLength}, got ${actualLength}`);
throw fileResponseError(`content length mismatch: expected ${contentLength}, got ${actualLength}`);
}
}

Expand Down
14 changes: 13 additions & 1 deletion providers/i18nProvider.js
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,8 @@ const extendedTranslation = {
notification: {
not_authorized: "אין לך הרשאה לצפות בנתונים אלו.",
application_update_available: 'גרסה חדשה זמינה.',
file_download_incomplete: 'הקובץ לא התקבל במלואו. ככל הנראה סינון האינטרנט (למשל נטפרי) חסם או קטע את ההורדה. נא לפנות לספק הסינון ולבקש לאשר את האתר, או לנסות להוריד מרשת אחרת.',
pdf_render_busy: 'המערכת מפיקה כרגע דוחות אחרים. נא לנסות שוב בעוד מספר דקות.',
},
validation: {
valueConfirm: 'ערך לא תואם',
Expand Down Expand Up @@ -165,6 +167,16 @@ const extendedTranslation = {
}
}

// English texts for keys this package adds on top of ra-language-english.
const extendedEnglishTranslation = {
ra: {
notification: {
file_download_incomplete: 'The file was not fully received. An internet content filter (such as NetFree) most likely blocked or cut off the download. Please ask your filter provider to approve this site, or try downloading from another network.',
pdf_render_busy: 'The system is currently generating other reports. Please try again in a few minutes.',
},
},
}

export const getI18nProvider = (domainTranslations, isDummy = false) => {
if (isDummy) {
return {
Expand All @@ -174,7 +186,7 @@ export const getI18nProvider = (domainTranslations, isDummy = false) => {
};
}

const translations = { en, he: deepMerge(he, deepMerge(extendedTranslation, domainTranslations)) };
const translations = { en: deepMerge(en, extendedEnglishTranslation), he: deepMerge(he, deepMerge(extendedTranslation, domainTranslations)) };

const i18nProvider = polyglotI18nProvider(
locale => translations[locale],
Expand Down
41 changes: 41 additions & 0 deletions utils/__tests__/httpUtil.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { fetchUtils } from 'react-admin';
import { fetchJson, translateErrorCode } from '../httpUtil';

jest.mock('react-admin', () => ({
fetchUtils: { fetchJson: jest.fn() },
}));

const buildHttpError = (body) => {
const error = new Error(body?.message ?? 'error');
error.status = body?.statusCode;
error.body = body;
return error;
};

describe('translateErrorCode', () => {
it('replaces the message of a known error code with its translation key', () => {
const error = buildHttpError({ statusCode: 503, code: 'PDF_RENDER_BUSY', message: 'busy' });
expect(translateErrorCode(error).message).toBe('ra.notification.pdf_render_busy');
});

it('leaves errors without a known code untouched', () => {
const error = buildHttpError({ statusCode: 500, message: 'Internal server error' });
expect(translateErrorCode(error).message).toBe('Internal server error');
});

it('handles errors without a body', () => {
const error = new Error('Network error');
expect(translateErrorCode(error).message).toBe('Network error');
});
});

describe('fetchJson', () => {
it('sends credentials and translates known error codes on failure', async () => {
const error = buildHttpError({ statusCode: 503, code: 'PDF_RENDER_BUSY', message: 'busy' });
fetchUtils.fetchJson.mockRejectedValueOnce(error);

await expect(fetchJson('/report', {})).rejects.toBe(error);
expect(error.message).toBe('ra.notification.pdf_render_busy');
expect(fetchUtils.fetchJson).toHaveBeenCalledWith('/report', { credentials: 'include' });
});
});
18 changes: 17 additions & 1 deletion utils/httpUtil.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,22 @@
import { fetchUtils } from 'react-admin';

// Server error codes that have a localized message. The server sends a stable
// `code` with an English fallback `message`; the message is replaced with a
// translation key, which react-admin's notify() translates to the user's locale.
export const ERROR_CODE_TRANSLATION_KEYS = {
PDF_RENDER_BUSY: 'ra.notification.pdf_render_busy',
};

export const translateErrorCode = (error) => {
const key = ERROR_CODE_TRANSLATION_KEYS[error?.body?.code];
if (key) {
error.message = key;
}
return error;
};

export const fetchJson = (url, options = {}) => {
options.credentials = 'include';
return fetchUtils.fetchJson(url, options);
return fetchUtils.fetchJson(url, options)
.catch((error) => { throw translateErrorCode(error); });
}
Loading