How to serialize all keys of object before send request when using ember-ajax


#1

Hi!

I’m using ember-ajax to send data to endpoint that are not rest, like /users/confirm-email, /users/reset-password, etc, example:

const attributes = changeset.getProperties('company', 'email', 'country', 'firstName', 'lastName', 'password');
this.get('ajax').request('/users', {
  method: 'POST',
  data: {
    data: {
      attributes,
      type: 'users'
    }
  }
}).then(() => {
  this.transitionToRoute('users.confirm-email', {
    queryParams: {
      email: changeset.get('email')
    }
  });
}).catch((response) => {
  this.errorHandler(response);
});

My API was made in Rails, therefore i’m using underscore_case, but in this case i’m sending data with camelCase pattern, and i would like to change it to underscore, something like the serializer that ember-data uses, is it possible? How to do it?


#2
const payload = {};
Object.keys(attributes).forEach(function(key) {
  payload[key.underscore()] = attributes[key];
});

Something like that should do the trick. Checkout https://www.emberjs.com/api/classes/Ember.String.html#method_underscore


#3

Hei nerdyworm, thank you for your reply. Where could i add this? I need this function in several models. Is there a pattern to add this helpers?


#4

You could just use ember-data with the ActiveModel serializer for those models and you wouldn’t need to use ember-ajax directly.

Otherwise, I would just make a little helper function and use it when you need to. I typically use an app/utils and then import it into your thingy via import magic from '<appname>/utils/magic