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
180 changes: 180 additions & 0 deletions packages/ra-data-json-server/src/index.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
import jsonServerClient from '.';

describe('Data JSON Server Client', () => {
const id = '../users/1?_embed=posts#';
const escapedUrl =
'http://localhost:3000/posts/..%2Fusers%2F1%3F_embed%3Dposts%23';

describe('getOne', () => {
it('should escape id in path', async () => {
const httpClient = jest.fn().mockResolvedValue({ json: { id } });
const client = jsonServerClient(
'http://localhost:3000',
httpClient
);

await client.getOne('posts', { id });

expect(httpClient).toHaveBeenCalledWith(
escapedUrl,
expect.any(Object)
);
});
});
describe('update', () => {
it('should escape id in path', async () => {
const httpClient = jest.fn().mockResolvedValue({ json: { id } });
const client = jsonServerClient(
'http://localhost:3000',
httpClient
);

await client.update('posts', {
previousData: undefined,
id,
data: { body: '' },
});

expect(httpClient).toHaveBeenCalledWith(
escapedUrl,
expect.any(Object)
);
});
});
describe('updateMany', () => {
it('should escape id in path', async () => {
const httpClient = jest.fn().mockResolvedValue({ json: { id } });
const client = jsonServerClient(
'http://localhost:3000',
httpClient
);

await client.updateMany('posts', {
data: { body: '' },
ids: [id],
});

expect(httpClient).toHaveBeenCalledWith(
escapedUrl,
expect.any(Object)
);
});
});
describe('delete', () => {
it('should escape id in path', async () => {
const httpClient = jest.fn().mockResolvedValue({ json: { id } });
const client = jsonServerClient(
'http://localhost:3000',
httpClient
);

await client.delete('posts', {
previousData: undefined,
id,
});

expect(httpClient).toHaveBeenCalledWith(
escapedUrl,
expect.any(Object)
);
});
});
describe('deleteMany', () => {
it('should escape id in path', async () => {
const httpClient = jest.fn().mockResolvedValue({ json: { id } });
const client = jsonServerClient(
'http://localhost:3000',
httpClient
);

await client.deleteMany('posts', {
ids: [id],
});

expect(httpClient).toHaveBeenCalledWith(
escapedUrl,
expect.any(Object)
);
});
});
describe('invalid identifiers', () => {
it.each(['.', '..', ''])(
'should not send a request for the id "%s"',
async id => {
const httpClient = jest.fn().mockResolvedValue({ json: {} });
const client = jsonServerClient(
'http://localhost:3000',
httpClient
);
const data = { body: '' };

const error = 'cannot build a URL';

await expect(client.getOne('posts', { id })).rejects.toThrow(
error
);
await expect(
client.update('posts', { id, data, previousData: { id } })
).rejects.toThrow(error);
await expect(
client.updateMany('posts', { ids: [1, id], data })
).rejects.toThrow(error);
await expect(client.delete('posts', { id })).rejects.toThrow(
error
);
await expect(
client.deleteMany('posts', { ids: [1, id] })
).rejects.toThrow(error);
expect(httpClient).not.toHaveBeenCalled();
}
);
});
describe('getManyReference', () => {
const params = {
target: 'post_id',
filter: {},
pagination: { page: 1, perPage: 10 },
sort: { field: 'id', order: 'ASC' as const },
};
const httpClient = jest.fn().mockResolvedValue({
headers: new Headers({ 'x-total-count': '1' }),
json: [{ id: 1 }],
});
beforeEach(() => {
httpClient.mockClear();
});

it('should filter by target', async () => {
const client = jsonServerClient(
'http://localhost:3000',
httpClient
);

const result = await client.getManyReference('comments', {
...params,
id: 12,
});

expect(httpClient).toHaveBeenCalledWith(
'http://localhost:3000/comments?_end=10&_order=ASC&_sort=id&_start=0&post_id=12',
expect.any(Object)
);
expect(result).toEqual({ data: [{ id: 1 }], total: 1 });
});

it('should return no record when the id is an empty array', async () => {
const client = jsonServerClient(
'http://localhost:3000',
httpClient
);

const result = await client.getManyReference('comments', {
...params,
id: [] as any,
});

expect(httpClient).not.toHaveBeenCalled();
expect(result).toEqual({ data: [], total: 0 });
});
});
});
40 changes: 32 additions & 8 deletions packages/ra-data-json-server/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,19 @@
import { stringify } from '@marmelab/query-string';
import { fetchUtils, DataProvider } from 'ra-core';
import { fetchUtils, DataProvider, Identifier } from 'ra-core';

/**
* Encode a record identifier as one segment of the request path.
* Throws if the identifier is not a valid path segment.
*/
const encodeId = (id: Identifier) => {
const encodedId = encodeURIComponent(id);
if (encodedId === '' || encodedId === '.' || encodedId === '..') {
throw new Error(
`The json-server data provider cannot build a URL for the identifier "${id}"`
);
}
return encodedId;
};

/**
* Maps react-admin queries to a json-server powered REST API
Expand Down Expand Up @@ -69,7 +83,7 @@ export default (apiUrl, httpClient = fetchUtils.fetchJson): DataProvider => ({
},

getOne: async (resource, params) => {
let url = `${apiUrl}/${resource}/${params.id}`;
let url = `${apiUrl}/${resource}/${encodeId(params.id)}`;
if (params?.meta?.embed) {
url += `?_embed=${params.meta.embed}`;
}
Expand All @@ -88,6 +102,10 @@ export default (apiUrl, httpClient = fetchUtils.fetchJson): DataProvider => ({
},

getManyReference: async (resource, params) => {
// stringify() omits a key whose value is an empty array, which would drop the target filter
if (Array.isArray(params.id) && params.id.length === 0) {
return { data: [], total: 0 };
}
const { page, perPage } = params.pagination;
const { field, order } = params.sort;
const query = {
Expand Down Expand Up @@ -121,7 +139,7 @@ export default (apiUrl, httpClient = fetchUtils.fetchJson): DataProvider => ({

update: async (resource, params) => {
const { json } = await httpClient(
`${apiUrl}/${resource}/${params.id}`,
`${apiUrl}/${resource}/${encodeId(params.id)}`,
{
method: 'PUT',
body: JSON.stringify(params.data),
Expand All @@ -132,9 +150,12 @@ export default (apiUrl, httpClient = fetchUtils.fetchJson): DataProvider => ({

// json-server doesn't handle filters on UPDATE route, so we fallback to calling UPDATE n times instead
updateMany: async (resource, params) => {
const urls = params.ids.map(
id => `${apiUrl}/${resource}/${encodeId(id)}`
);
const responses = await Promise.all(
params.ids.map(id =>
httpClient(`${apiUrl}/${resource}/${id}`, {
urls.map(url =>
httpClient(url, {
method: 'PUT',
body: JSON.stringify(params.data),
})
Expand All @@ -153,17 +174,20 @@ export default (apiUrl, httpClient = fetchUtils.fetchJson): DataProvider => ({

delete: async (resource, params) => {
const { json } = await httpClient(
`${apiUrl}/${resource}/${params.id}`,
`${apiUrl}/${resource}/${encodeId(params.id)}`,
{ method: 'DELETE' }
);
return { data: json };
},

// json-server doesn't handle filters on DELETE route, so we fallback to calling DELETE n times instead
deleteMany: async (resource, params) => {
const urls = params.ids.map(
id => `${apiUrl}/${resource}/${encodeId(id)}`
);
const responses = await Promise.all(
params.ids.map(id =>
httpClient(`${apiUrl}/${resource}/${id}`, {
urls.map(url =>
httpClient(url, {
method: 'DELETE',
})
)
Expand Down
32 changes: 32 additions & 0 deletions packages/ra-data-simple-rest/src/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -245,4 +245,36 @@ describe('Data Simple REST Client', () => {
);
});
});
describe('invalid identifiers', () => {
it.each(['.', '..', ''])(
'should not send a request for the id "%s"',
async id => {
const httpClient = jest.fn().mockResolvedValue({ json: {} });
const client = simpleClient(
'http://localhost:3000',
httpClient
);
const data = { body: '' };

const error = 'cannot build a URL';

await expect(client.getOne('posts', { id })).rejects.toThrow(
error
);
await expect(
client.update('posts', { id, data, previousData: { id } })
).rejects.toThrow(error);
await expect(
client.updateMany('posts', { ids: [1, id], data })
).rejects.toThrow(error);
await expect(client.delete('posts', { id })).rejects.toThrow(
error
);
await expect(
client.deleteMany('posts', { ids: [1, id] })
).rejects.toThrow(error);
expect(httpClient).not.toHaveBeenCalled();
}
);
});
});
Loading
Loading