Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Send range header in simple REST client getList request
  • Loading branch information
jpetitcolas committed Aug 17, 2020
1 parent 7223b23 commit 4a60ffa
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 2 deletions.
39 changes: 39 additions & 0 deletions packages/ra-data-simple-rest/src/index.spec.ts
@@ -0,0 +1,39 @@
import simpleClient from '.';

describe('Data Simple REST Client', () => {
describe('getList', () => {
it('should include the `Range` header in request (for Chrome compatibility purpose)', async () => {
const httpClient = jest.fn(() =>
Promise.resolve({
headers: new Headers({
'content-range': '0/4-8',
}),
})
);
const client = simpleClient('http://localhost:3000', httpClient);

await client.getList('posts', {
filter: {},
pagination: {
page: 1,
perPage: 10,
},
sort: {
field: 'title',
order: 'desc',
},
});

expect(httpClient).toHaveBeenCalledWith(
'http://localhost:3000/posts?filter=%7B%7D&range=%5B0%2C9%5D&sort=%5B%22title%22%2C%22desc%22%5D',
{
headers: {
map: {
range: 'posts=0-9',
},
},
}
);
});
});
});
13 changes: 11 additions & 2 deletions packages/ra-data-simple-rest/src/index.ts
Expand Up @@ -37,14 +37,23 @@ export default (apiUrl, httpClient = fetchUtils.fetchJson): DataProvider => ({
getList: (resource, params) => {
const { page, perPage } = params.pagination;
const { field, order } = params.sort;

const rangeStart = (page - 1) * perPage;
const rangeEnd = page * perPage - 1;

const query = {
sort: JSON.stringify([field, order]),
range: JSON.stringify([(page - 1) * perPage, page * perPage - 1]),
range: JSON.stringify([rangeStart, rangeEnd]),
filter: JSON.stringify(params.filter),
};
const url = `${apiUrl}/${resource}?${stringify(query)}`;

return httpClient(url).then(({ headers, json }) => {
return httpClient(url, {
// Chrome doesn't return `Content-Range` header if no `Range` is provided in the request.
headers: new Headers({
Range: `${resource}=${rangeStart}-${rangeEnd}`,
}),
}).then(({ headers, json }) => {
if (!headers.has('content-range')) {
throw new Error(
'The Content-Range header is missing in the HTTP Response. The simple REST data provider expects responses for lists of resources to contain this header with the total number of results to build the pagination. If you are using CORS, did you declare Content-Range in the Access-Control-Expose-Headers header?'
Expand Down

0 comments on commit 4a60ffa

Please sign in to comment.