mardi 9 mai 2017

How to properly save and validate model objects with other nested objects in Ember.js?

Let's say the user creates a new Person with a few PhoneNumbers. Everything is done through a single form, where you can dynamically add as many PhoneNumbers to the Person as you want. The user clicks the save button and whole form gets submitted to the server, after which a save response comes back from the server.

The important thing is, that i don't want to save the PhoneNumbers separately from the Person. I want the operation to be atomic - everything gets sent together in one request and either everything validates on the server side and gets saved together in one transaction, or nothing gets saved and error data returns.

Right now, to achieve it I have a savePerson action in my controller, where I do awful things like this:

person.get('phoneNumbers').setObjects([]);
phones.forEach((phone) => {
    if (!!phone.phone) {
        var p = null;
        if (!phone.id) {
            p = that.store.createRecord('phoneNumber', {
                'person': person,
                'number': phone.phone
            });
            person.get('phoneNumbers').pushObject(p);
        } else {
            p = that.store.peekRecord('phoneNumber', phone.id);
            p.person  = person;
            p.number = phone.phone;
            person.get('phoneNumbers').pushObject(p);
        }
    }
});
{...}
person.save().then(function() {
    {...}
    that.store.unloadAll('phoneNumber'); //needs to be done to remove records created by createRecord - their saved duplicates will come back after model reload
    {...}
})

I also have no idea how to properly handle server-side validation of the embedded objects. To validate the top level object (Person) I return error data compatible with JSON API specification like this:

{
    "errors": [
        {
            "detail": "This value is invalid",
            "source": {
                "pointer": "data/attributes/firstName"
            }
        }
        {...}
    ]
}

This works with Ember and eventually I have my errors in model and can retrieve them in the template with . But how to return errors referring to the nested objects? I have no idea unfortunately.

I tried to seek various solutions to my conundrums but to no avail. I couldn't find any examples regarding such situations unfortunatelly. But it seems pretty basic. Am I missing something fundamental?

I will be really grateful for any suggestions. Thanks.




Aucun commentaire:

Enregistrer un commentaire