Ember Data records without IDs - auto numbering?


#1

I’ve got a JSON file that I’m using for data. It’s outside of my control and the records do not have IDs. Is there any way to get Ember Data to apply an ID on my behalf? Here’s a sample of a single record…the properties will all always be there, but many of them will be blank.

[{
    "": "",
    "First": "Andy",
    "Last": "Matthews",
    "Department": "Product",
    "Team": "",
    "Title": "Software Developer",
    "Location ": "Nashville",
    "Direct": "",
    "Extension": "n/a",
    "Cell": "",
    "IM": "someonetowritehometo",
    "Email": "amatthews@myemma.com",
    "Emmaversary": "Sept 24, 2012"
}]

#2

This might be a hack but you might try using guidFor inside a specialized adapter for your model.

You could also implement your own counter or way of creating client side ids within your adapter.

http://emberjs.com/api/#method_guidFor

The main sticky point I think is how will the API handle that Id when you go to persist the record. But if you are read only you you will probably not have too many issues.


#3

Yep. It’s an employee directory, so read only.


#4

Actually I ended up going with a custom model serializer based on this SO post:

App.PersonSerializer = DS.RESTSerializer.extend({
    normalizePayload: function(type, payload) {
        var result = [],
            obj;
        payload.forEach(function(el, index){
            el['id'] = index;
            result.push(el);
        });
        return {'person': result };
    }
});

#5

Yup makes sense for incrementing id.

If you decide for some reason you need temporary but globally “unique” ids that is what guidFor does. It is a private method so perhaps subject to change and definitely use at own risk. But from what I understand it creates ids like

ember123
ember321
ember992
etc

I think it increments by object count in memory but I am not exactly sure all the implementation details.

Also, if dealing with distributed systems where you need to be sure that the id can be created both server side and client side then you would need to implement some sort of UUID in Javascript.

Also, sometimes I create a sha1 checksum of my data record because that gives me something to pass around as an ID and I know should be consistent if the data doesn’t change.

Anyway, thanks for SO link that is cool. Good to know.


#6

@commadelimited

We took a similar approach where we are calling the model’s class/prototype for a getId function which returns an incremented id from within normalizePayload. This allows us to scope an id variable within the ES6 module for the model itself to auto increment for the lifetime of the application. This way we don’t have a global that’s incrementing IDs. But there are a few ways to tackle this, you’re on the right track with that blog post.


Custom serializer for model loads, route has no data