dimanche 25 août 2019

Change an Ember model's value before saving to server

I've got an Ember Model, with a field which I want to display and work with, but before I save or retrieve it from the server, I want to multiply/divide it by 1000.

This means the UI should always work with a smaller value, but save a larger value to the server. Likewise, it should retrieve a larger value from the server, but make it smaller before allowing it to be used by the controllers, routes, etc.

import DS from 'ember-data';

export default DS.Model.extend({
    name: DS.attr('string'),
    value: DS.attr('number')
});

Essentially, I want my application to show these fields as:

/* my webpage */
Please enter name: "foo"
Please enter value: 5

But when I send the request, it should send them as:

{
    "myModel": {
        "name": "foo",
        "value": 5000
    }
}

It should also receive them in this format, but then deserialise the value by dividing by 1000.

Please note that multiplying/dividing by 1000 is an example - I may want to append, prepend, add, subtract, etc.


I tried doing this in a less elegant way:

// Controller.js
actions: {
    save: function() {
        this.set('model.value', this.get('model.value') * 1000);
        this.get('model').save().then(
            /* stuff */
        );
        this.set('model.value', this.get('model.value') / 1000);
    }
}

But I'm not happy with this, and it results in duplicated code that is hard to maintain, and error-prone.

I have a RESTSerializer, but I don't know how to use it to manipulate fields, and couldn't find anything in the documentation. Maybe I need to use a different serializer? Mine is basically empty so far.

import DS from 'ember-data';

export default DS.RESTSerializer.extend({
    primaryKey: 'name',
});




Aucun commentaire:

Enregistrer un commentaire