2

I have an Employee model in my emberjs app, and I am trying to load the Employees content using a RESTful web service which come in the following format:

{
    "Result": [
        {
            "EmployeeId": "1",
            "EmployeeName": "Mark Smith",
            "Active": 0,
            "Dept": "Sales"
        },
        {
            "EmployeeId": "2",
            "EmployeeName": "John Smith",
            "Active": 1,
            "Dept": "Sales"
        },
        {
            "EmployeeId": "3",
            "EmployeeName": "Michael Smith",
            "Active": 1,
            "Dept": "Administration"
        }
    ],
    "ResultCount": 3
}

Here I am facing 3 problems:

  1. Is it possible to read this JSON format and add it to the Employee model, I understand that "Result" should have been "Employees" but I have no control over the return JSON format so if it is possible to use "Result" that will be great. Any example on doing so is highly appreciated.

  2. How can I handle "ResultCount"? Is there a way I can read it as part of Employee model?

  3. How I can read "Active" in the app View as "Active" / "Not Active" instead of 0 or 1?

Thanks for your time

MChan
  • 6,842
  • 27
  • 83
  • 132
  • 2
    You'd need to build a custom serializer, I think if it doesn't follow the standard format. There's a good answer about it here: http://stackoverflow.com/questions/14300679/how-to-create-a-custom-serializer-for-ember-data – jasonpgignac Feb 20 '14 at 20:06

1 Answers1

0

As pointed out by jasonpgignac, you'll need to write a custom serailizer/deserializer to get the data into ember-data.

Once you have your data loaded ResultCount isn't required. You should use the 'length' property on the returned collection.

As part of your serializer you'll want to convert 0/1 to false/true in your model. You can them add a property like:

activeLabel: ( ->
  if @get('active')
    'Active'
  else
    'Not Active'
).property('active')

and use this property in your templates.

As requested, here's a sample class from a project of mine:

App.StudentSerializer = DS.ActiveModelSerializer.extend

  serializeBelongsTo: (record, json, relationship) ->
    key = relationship.key
    if key is 'attendance'
      @serializeAttendance(record, json)
    else
      json["#{key}_id"] = record.get("#{key}.id")

  serializeAttendance: (record, json) ->
    attendance = record.get('attendance')
    json['attendance'] = {}
    ['monday', 'tuesday', 'wednesday', 'thursday', 'friday'].forEach( (day) =>
      json['attendance'][day] = attendance.get(day)
    )

  serializeHasMany: (record, json, relationship) ->
    key = relationship.key

    jsonKey = Ember.String.singularize(key) + '_ids'
    json[jsonKey] = []
    record.get(key).forEach( (item) ->
      json[jsonKey].push(item.get('id'))
    )

My store.coffee looks like:

App.Store = DS.Store.extend
  # Override the default adapter with the `DS.ActiveModelAdapter` which
  # is built to work nicely with the ActiveModel::Serializers gem.
  adapter: '_ams'

App.ApplicationSerializer = DS.ActiveModelSerializer.extend()

You'll probably want to use the JsonAdapter and extend it if you don't have any control over the backend. As I said below, I haven't done deserialising but there should be the necessary hooks for you to convert into the format required by ember-data.

Martin Stannard
  • 811
  • 8
  • 22
  • @Matrin Thanks a lot for your reply. Any chance you know where can I find a sample for a serializer/ deserializer? Based on my humbled experience with Emberjs it is really difficult to locate examples / tutorials that explains how some of its features works! – MChan Feb 25 '14 at 08:52
  • You should start at http://emberjs.com/api/data/classes/DS.JSONSerializer.html#method_serialize and associated methods. Using the examples there should give you some ideas for what you'll need to change to get your JSON to comform to that required by ember-data. Also, what version of ember-data are you using? You want to be on the latest 1.0.0 release candidate for those docs to apply at all. – Martin Stannard Feb 25 '14 at 11:23
  • I've literary spent days digging inside Ember classes, open source projects, tutorials on the web. Ironically all of this effort didn't result in one working example on how to serialize/ deserialize or how to create a custom RESTAdapter for a specific model that require sending authentication token with each API request...I've even posted the question here with a bounty and no reply yet...this is just a small hint on level of frustration I am having from Ember :) I am using Ember 1.3 and just for the record 90% of web tutorials are on ver 1.0...looks like many have abandoned supporting ember! – MChan Feb 25 '14 at 11:34
  • I'm using ember-simple-auth for token authentication, it works well and you can customise it to fit your needs. You need to separate out the auth from the serialization. I'll post an example class from a project of mine above. I've only had to do serialization because I'm using active_model_serializers on a Rails backend, and it deserializes fine. – Martin Stannard Feb 25 '14 at 12:55
  • thanks a lot I will follow your advice and look at ember-simple-auth, I will also work on the example above. Having said that, since you are familiar with Ember, will you mind answer this question http://stackoverflow.com/questions/21947548/implementing-custom-ajax-calls-when-loading-data-in-model I am already offering +50 bounty on answering it. Thanks in advance – MChan Feb 25 '14 at 13:11