Christian Fazzini
Christian Fazzini

Reputation: 19713

Is this a good use case for a util class?

I have the same Ember.$ajax call being used in several locations in my Ember app. I chose to use a util class:

export default function updateImage(model, token, imageUrl) {
  return Ember.$.ajax({
    url: `api/v1/${Ember.Inflector.inflector.pluralize(model.get('constructor.modelName'))}/${model.get('id')}/update-image`,
    type: 'PUT',
    headers: {
      // Used in staging and production
      // In Development, this will send with an empty value. API ignores this header in development anyways
      'X-CSRF-TOKEN': Ember.$('meta[name="csrf-token"]').attr('content'),
      Authorization:  `Token ${token }`
    },
    data: {
      data: {
        attributes: {
          'image-url': imageUrl
        }
      }
    }
  })
}

Then in a controller/route, I can do:

  updateImage(user, this.currentSession.get('token'), imageUrl)
  .success(response => {
    user.set('imageUrl', response['users']['image-url']);
    this.flashService.generic('Saved image!');
  })
  .error(response => {
    console.log(response);
  });

Is this good use of a util class? Can I refactor this further? Or should I consider some other pattern? Will a mixin be more appropriate for this kind of logic?

Upvotes: 1

Views: 39

Answers (1)

Daniel
Daniel

Reputation: 18682

It's perfectly fine use case. It is single, universal method that can be used across your application. If you would need to use more similar, related methods in many places, or you would want to split updateImage function for better abstraction then you should switch to Mixin, but now, it's fine.

Upvotes: 1

Related Questions