If I have multiple distinct REST API back-ends (separate apps doing separate things), and I want a single UI (react-admin-based) app that is capable of doing CRUD to entities managed by these various back-ends, I'm curious if it's possible to wire up react-admin to do that.
I'm imagining that instead of this (single/global dataProvider):
const App = () => (
<Admin dataProvider={simpleRestProvider('http://path.to.foo.api')}>
<Resource name="foos" list={FooList} />
</Admin>
);
we could do something like this (resource-specific dataProviders):
const App = () => (
<Admin >
<Resource name="foos" list={FooList}
dataProvider={simpleRestProvider('http://path.to.foo.api')} />
<Resource name="bars" list={BarList}
dataProvider={simpleRestProvider('http://path.to.bar.api')} />
</Admin>
);
At any rate, if you have advice on how I can do REST to multiple back-ends in react-admin, I'd appreciate it very much.
React-admin runs in the browser, and relies on data it fetches from APIs. JSONPlaceholder provides endpoints for users, posts, and comments. The admin we'll build should allow to Create, Retrieve, Update, and Delete (CRUD) these resources.
No, but you can have a super dataProvivder which would select the appropriate one depending on the resource. Something like:
const dataProviders = [
{ dataProvider: simpleRestProvider('http://path.to.foo.api'), resources: ['foos'] },
{ dataProvider: simpleRestProvider('http://path.to.bar.api'), resources: ['bars'] },
];
export default (type, resource, params) => {
const dataProviderMapping = dataProviders.find(dp => dp.resources.includes(resource));
return dataProviderMapping.dataProvider(type, resource, params);
}
I got the idea from @Gildas Garcia's answer. Thank @Gildas Garcia very much. But your code only work on React admin version 2, in version 3 and above, I need have some customs to make it work. Here is my solutions
// ... others import
import {
fetchUtils,
GET_LIST,
GET_ONE,
CREATE,
UPDATE,
UPDATE_MANY,
DELETE,
GET_MANY,
GET_MANY_REFERENCE,
} from 'react-admin';
const dataProviders = [
{
dataProvider: simpleRestProvider('http://localhost:3000'),
resources: ['users'],
},
{
dataProvider: simpleRestProvider('http://localhost:3002'),
resources: ['roles'],
},
{
dataProvider: customJSONDataProvider('http://localhost:3003'),
resources: ['permissions'],
},
];
export default (type, resource, params) => {
const dataProviderMapping = dataProviders.find((dp) =>
dp.resources.includes(resource));
const mappingType = {
[GET_LIST]: 'getList',
[GET_ONE]: 'getOne',
[GET_MANY]: 'getMany',
[GET_MANY_REFERENCE]: 'getManyReference',
[CREATE]: 'create',
[UPDATE]: 'update',
[UPDATE_MANY]: 'updateMany',
[DELETE]: 'delete',
};
return dataProviderMapping.dataProvider[mappingType[type]](resource, params);
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With