Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Request: please pass the model class to dataTransformer #155

Open
seankndy opened this issue Jan 3, 2022 · 2 comments
Open

Request: please pass the model class to dataTransformer #155

seankndy opened this issue Jan 3, 2022 · 2 comments

Comments

@seankndy
Copy link

seankndy commented Jan 3, 2022

It would be nice if this plugin would pass the model class as the second argument to the dataTransformer callback so that the dataTransformer function could mutate extra state in the model. Example:

In my model:

export default class FooBar extends Model {
  // ....

  static state() {
    return {
      abilities: null,
    }
  }
}

Now in the transformer:

  dataTransformer: (response, model) => {
    if ('abilities' in response.data) {
      model.commit((state) => {
        state.abilities = response.data.abilities
      })
    }
    return 'data' in response.data ? response.data.data : response.data
  }

I can accomplish this same sort of thing by passing a 'model' into the axios config during the request:

API call:

    const response = FooBar.api()
      .get('/foobars', {
        model: FooBar,
      })

Then in dataTransformer, use it in response.config:

  dataTransformer: (response) => {
    if ('model' in response.config && 'abilities' in response.data) {
      response.config.model.commit((state) => state.abilities = response.data.abilities)
    }

    return 'data' in response.data ? response.data.data : response.data
  }

However it seems reasonable to me that the plugin would pass in the model and make this cleaner.

@seankndy seankndy changed the title Pleas pass the model class to dataTransformer Request: please pass the model class to dataTransformer Jan 3, 2022
@cuebit
Copy link
Member

cuebit commented Jan 5, 2022

Curious to understand why you'd need a reference to the constructor?

If you're calling FooBar.api(), the transformer belongs to FooBar, therefore FooBar can be referenced statically.

If your transformer is anonymously generic then that's a user-land resolution.

In the case of the latter, maybe you could use a factory to pass the model reference?

@seankndy
Copy link
Author

seankndy commented Jan 5, 2022

The data transformer in this case is global and applies to every model. So in the calling code I am using the static FooBar, but in the transformer itself I don't know which model was called as it's generic to every model.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants