Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define a complex model

I have the following user object (json):

{
    "_id": "my-id",
    "org": 666,
    "type": "user",
    "properties": {
        "first_name": "Firstname",
        "surname1": "Surname1",
        "surname2": "Surname2",
        "allowed_apps": [ "one-app", "another-app" ],
        "default_app": "one-app",
        "email": "[email protected]"
    },
    "outputs": {
        "extension": "extension-id"
    }
}

This is a single model, with a complex structure. It is not a "multi-model structure". Therefore, I want to define this using DS.Model.extend, but I do not want to use belongsTo relationships for neither properties nor outputs, since they do not refer to other models: these fields are just complex data, direct part of my user object. That is, we do not have any properties model, nor any outputs model. These are just parts of the user model, and as such are stored in the database (couchdb in our case).

Can this be done in ember?

like image 842
blueFast Avatar asked Jun 01 '26 07:06

blueFast


1 Answers

Lamentably this kind of structure is not possible using ember-data models. Every value of a model that is not a primitive one such as string, number, boolean & date can't be defined as a model property without designing it with belongsTo or hasMany. Furthermore this site jsonapi.org which is still a WIP describes the direction ember-data is going with it's implementation.

So the point is here if you want/need to use ember-data models (DS.Model) your server should obey the JSON format ember-data expects, otherwise you have always the possibility (since ember-data is backend agnostic) to not use ember-data models definition at all, this way your models can be structured the way you want, but then you are out of being helped from the conventional work ember-data adapter and serializer does for you and you have to write your own adapter/s which then deals with all the peculiarities your JSON's have and load them finally into your store.

If you absolutely need a custom data structure to be exchanged with your backend, you can register a custom transform like for example:

App.Adapter.registerTransform('mega', {
  deserialize: function(serialized) {
    //do your custom deserialization
  },
  serialize: function(deserialized) {
    //do your custom serialization
  }
});

and then use it like:

App.MyModel = DS.Model.extend({
  megaValue: DS.attr('mega');
});

Hope it helps.

like image 163
intuitivepixel Avatar answered Jun 04 '26 13:06

intuitivepixel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!