Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Support for resource nesting

I am wondering, is it possible to configure DataProvider/Resource/List to support REST urls like api/users/1/roles?

For RESTful API it is very common use case to get childs of certain parent entity, but I cant figure it how to setup React Admin and achieve this. I am using custom DataProvider build on OData spec backend.

I understand that I can get roles of certain user by filtered request on api/roles?filter={userId: 1} or something like that, but my issue is that my users and roles are in many-to-many relation so relation references are stored in pivot table. In other words, I dont have reference on user in roles table so I cant filter them.

Am I overseeing something or is there some approach which I simply dont see?

EDIT: REST API is built in OData spec and it supports many-to-many relations with classic pivot (or intermediate) table. This table is not exposed in API, but is utilized in urls like the one above. So I cant directly access it as a resource.

Schema for User - Role relations looks pretty standard too.

|----------|    |-----------|     |--------|
| USER     |    | User_Role |     | Role   |
|----------|    |-----------|     |--------|
| Id       |-\  | Id        |   /-| Id     |
| Login    |  \-| UserId    |  /  | Name   |
| Password |    | RoleId    |-/   | Code   |
|----------|    |-----------|     |--------|
like image 352
Allwe Avatar asked Jan 18 '19 13:01

Allwe


2 Answers

TL;DR: By default, React Admin doesn't support nested resource, you have to write a custom data provider.

This question was answered on a past issue: maremelab/react-admin#261

Detailed Answer

The default data provider in React Admin is ra-data-simple-rest.

As explained on its documentation, this library doesn't support nested resources since it only use the resource name and the resource ID to build a resource URL:

Simple REST Data Provider

In order to support nested resources, you have to write your own data provider.

Nested resources support is a recurrent feature request but, at the time, the core team don't want to handle this load of work.

I strongly suggest to gather your forces and write an external data provider and publish it like ra-data-odata provider. It would be a great addition and we will honored to help you with that external package.

like image 151
Kmaschta Avatar answered Nov 04 '22 07:11

Kmaschta


Your question was already answer here, but I would like to tell you about my workaround in order for React-Admin work with many-to-many relations.

As said in the mentioned answer you have to extend the DataProvider in order for it to fetch resources of a many-to-many relation. However you need to use the new REST verb, lets suppose GET_MANY_MANY_REFERENCE somewhere on your application. Since different REST services/API can have different routes formats to fetch related resources I didn't bother trying to build a new DataProvider, I know is not a great solution, but for short deadlines is considerable simple.

My solution was taking inspiration on <ReferenceManyField> and build a new component <ReferenceManyManyField> for many-to-many relations. This component fetches related records on componentDidMount using fetch API. On response uses the response data to build to objects one data being an object with keys being record ids, and values the respective record object, and an ids array with the ids of records. This is passes to children along with other state variables like page, sort, perPage, total, to handle pagination and ordering of data. Be aware that changing the order of the data in a Datagrid means a new request will be made to the API. This component is divided in a controller and a view, like <ReferencemanyField>, where controller fetches data, manages it and passes it to children and view that receives controller data and passes it to children render its content. That made me possible to render many-to-many relations data on a Datagrid, even if with some limitation, is a component to aggregated to my project and only work with my current API if something changes I would have to change the field to, but as for now it works and can be reused along my app.

Implementation details go as follow:

//ReferenceManyManyField
export const ReferenceManyManyField = ({children, ...prop}) => {
  if(React.Children.count(children) !== 1) {
    throw new Error( '<ReferenceManyField> only accepts a single child (like <Datagrid>)' )
  }

  return <ReferenceManyManyFieldController {...props}>
    {controllerProps => (<ReferenceManyManyFieldView 
    {...props} 
    {...{children, ...controllerProps}} /> )}
  </ReferenceManyManyFieldController>

//ReferenceManyManyFieldController
class ReferenceManyManyFieldController extends Component {

  constructor(props){
    super(props)
    //State to manage sorting and pagination, <ReferecemanyField> uses some props from react-redux 
    //I discarded react-redux for simplicity/control however in the final solution react-redux might be incorporated
    this.state = {
      sort: props.sort,
      page: 1,
      perPage: props.perPage,
      total: 0
    }
  }

  componentWillMount() {
    this.fetchRelated()
  }

  //This could be a call to your custom dataProvider with a new REST verb
  fetchRelated({ record, resource, reference, showNotification, fetchStart, fetchEnd } = this.props){
    //fetchStart and fetchEnd are methods that signal an operation is being made and make active/deactivate loading indicator, dataProvider or sagas should do this
    fetchStart()
    dataProvider(GET_LIST,`${resource}/${record.id}/${reference}`,{
      sort: this.state.sort,
      pagination: {
        page: this.state.page,
        perPage: this.state.perPage
      }
    })
    .then(response => {
      const ids = []
      const data = response.data.reduce((acc, record) => {
        ids.push(record.id)
        return {...acc, [record.id]: record}
      }, {})
      this.setState({data, ids, total:response.total})
    })
    .catch(e => {
      console.error(e)
      showNotification('ra.notification.http_error')
    })
    .finally(fetchEnd)
  }

  //Set methods are here to manage pagination and ordering,
  //again <ReferenceManyField> uses react-redux to manage this
  setSort = field => {
    const order =
        this.state.sort.field === field &&
        this.state.sort.order === 'ASC'
            ? 'DESC'
            : 'ASC';
    this.setState({ sort: { field, order } }, this.fetchRelated);
  };

  setPage = page => this.setState({ page }, this.fetchRelated);

  setPerPage = perPage => this.setState({ perPage }, this.fetchRelated);

  render(){
    const { resource, reference, children, basePath } = this.props
    const { page, perPage, total } = this.state;

    //Changed basePath to be reference name so in children can nest other resources, not sure why the use of replace, maybe to maintain plurals, don't remember 
    const referenceBasePath = basePath.replace(resource, reference);

    return children({
      currentSort: this.state.sort,
      data: this.state.data,
      ids: this.state.ids,
      isLoading: typeof this.state.ids === 'undefined',
      page,
      perPage,
      referenceBasePath,
      setPage: this.setPage,
      setPerPage: this.setPerPage,
      setSort: this.setSort,
      total
    })
  }

}

ReferenceManyManyFieldController.defaultProps = {
  perPage: 25,
  sort: {field: 'id', order: 'DESC'}
}

//ReferenceManyManyFieldView
export const ReferenceManyManyFieldView = ({
  children,
  classes = {},
  className,
  currentSort,
  data,
  ids,
  isLoading,
  page,
  pagination,
  perPage,
  reference,
  referenceBasePath,
  setPerPage,
  setPage,
  setSort,
  total
}) => (
  isLoading ? 
    <LinearProgress className={classes.progress} />
  :
      <Fragment>
        {React.cloneElement(children, {
          className,
          resource: reference,
          ids,
          data,
          basePath: referenceBasePath,
          currentSort,
          setSort,
          total
        })}
        {pagination && React.cloneElement(pagination, {
          page,
          perPage,
          setPage,
          setPerPage,
          total
        })}
      </Fragment>
);

//Assuming the question example, the presentation of many-to-many relationship would be something like
const UserShow = ({...props}) => (
  <Show {...props}>
    <TabbedShowLayout>
      <Tab label='User Roles'>
        <ReferenceManyManyField source='users' reference='roles' addLabel={false} pagination={<Pagination/>}>
          <Datagrid>
            <TextField source='name'/>
            <TextField source='code'/>
          </Datagrid>
        </ReferenceManyManyField>
      </Tab>
    </TabbedShowLayout>
  </Show>
)
//Used <TabbedShowLayout> because is what I use in my project, not sure if works under <Show> or <SimpleShowLayout>, but I think it work since I use it in other contexts

I think the implementation can be improved and be more compatible with React-Admin. In other reference fields data fetch is stored on react-redux state, in this implementation it's not. The relation is not saved anywhere besides the component making application not work on offline since can't fetch data, not even ordering is possible.

like image 31
Mário Ferreiro Avatar answered Nov 04 '22 09:11

Mário Ferreiro