DS.JSONAPISerializer

DS.JSONAPISerializer Class

Extends: DS.JSONSerializer

Defined in: addon/serializers/json-api.js:14

Module: ember-data

Ember Data 2.0 Serializer:

In Ember Data a Serializer is used to serialize and deserialize records when they are transferred in and out of an external source. This process involves normalizing property names, transforming attribute values and serializing relationships.

JSONAPISerializer supports the http://jsonapi.org/ spec and is the serializer recommended by Ember Data.

This serializer normalizes a JSON API payload that looks like:

app/models/player.js
import DS from 'ember-data';

export default DS.Model.extend({
  name: DS.attr('string'),
  skill: DS.attr('string'),
  gamesPlayed: DS.attr('number'),
  club: DS.belongsTo('club')
});
app/models/club.js
import DS from 'ember-data';

export default DS.Model.extend({
  name: DS.attr('string'),
  location: DS.attr('string'),
  players: DS.hasMany('player')
});
  {
    "data": [
      {
        "attributes": {
          "name": "Benfica",
          "location": "Portugal"
        },
        "id": "1",
        "relationships": {
          "players": {
            "data": [
              {
                "id": "3",
                "type": "players"
              }
            ]
          }
        },
        "type": "clubs"
      }
    ],
    "included": [
      {
        "attributes": {
          "name": "Eusebio Silva Ferreira",
          "skill": "Rocket shot",
          "games-played": 431
        },
        "id": "3",
        "relationships": {
          "club": {
            "data": {
              "id": "1",
              "type": "clubs"
            }
          }
        },
        "type": "players"
      }
    ]
  }

to the format that the Ember Data store expects.

Customizing meta

Since a JSON API Document can have meta defined in multiple locations you can use the specific serializer hooks if you need to customize the meta.

One scenario would be to camelCase the meta keys of your payload. The example below shows how this could be done using normalizeArrayResponse and extractRelationship.

app/serializers/application.js
export default JSONAPISerializer.extend({
  normalizeArrayResponse(store, primaryModelClass, payload, id, requestType) {
    let normalizedDocument = this._super(...arguments);

    // Customize document meta
    normalizedDocument.meta = camelCaseKeys(normalizedDocument.meta);

    return normalizedDocument;
  },

  extractRelationship(relationshipHash) {
    let normalizedRelationship = this._super(...arguments);

    // Customize relationship meta
    normalizedRelationship.meta = camelCaseKeys(normalizedRelationship.meta);

    return normalizedRelationship;
  }
});

_extractType (modelClass, resourceHash) Stringprivate

Defined in addon/serializers/json-api.js:344

Parameters:

modelClass DS.Model
resourceHash Object

Returns:

String

_normalizeDocumentHelper (documentHash) Objectprivate

Defined in addon/serializers/json-api.js:132

Parameters:

documentHash Object

Returns:

Object

_normalizeRelationshipDataHelper (relationshipDataHash) Objectprivate

Defined in addon/serializers/json-api.js:167

Parameters:

relationshipDataHash Object

Returns:

Object

_normalizeResourceHelper (resourceHash) Objectprivate

Defined in addon/serializers/json-api.js:195

Parameters:

resourceHash Object

Returns:

Object

_normalizeResponse (store, primaryModelClass, payload, id, requestType, isSingle) Objectprivate

Inherited from DS.JSONSerializer but overwritten in addon/serializers/json-api.js:255

Parameters:

store DS.Store
primaryModelClass DS.Model
payload Object
id String|Number
requestType String
isSingle Boolean

Returns:

Object
JSON-API Document

keyForAttribute (key, method) String

Inherited from DS.JSONSerializer but overwritten in addon/serializers/json-api.js:423

keyForAttribute can be used to define rules for how to convert an attribute name in your model to a key in your JSON. By default JSONAPISerializer follows the format used on the examples of http://jsonapi.org/format and uses dashes as the word separator in the JSON attribute keys.

This behaviour can be easily customized by extending this method.

Example

app/serializers/application.js
import DS from 'ember-data';

export default DS.JSONAPISerializer.extend({
  keyForAttribute(attr, method) {
    return Ember.String.dasherize(attr).toUpperCase();
  }
});

Parameters:

key String
method String

Returns:

String
normalized key

keyForRelationship (key, typeClass, method) String

Inherited from DS.JSONSerializer but overwritten in addon/serializers/json-api.js:453

keyForRelationship can be used to define a custom key when serializing and deserializing relationship properties. By default JSONAPISerializer follows the format used on the examples of http://jsonapi.org/format and uses dashes as word separators in relationship properties.

This behaviour can be easily customized by extending this method.

Example

app/serializers/post.js
 import DS from 'ember-data';

 export default DS.JSONAPISerializer.extend({
   keyForRelationship(key, relationship, method) {
     return Ember.String.underscore(key);
   }
 });

Parameters:

key String
typeClass String
method String

Returns:

String
normalized key

modelNameFromPayloadKey (key) String

Inherited from DS.JSONSerializer but overwritten in addon/serializers/json-api.js:371

Dasherizes and singularizes the model name in the payload to match the format Ember Data uses internally for the model name.

For example the key posts would be converted to post and the key studentAssesments would be converted to student-assesment.

Parameters:

key String

Returns:

String
the model's modelName

modelNameFromPayloadType (payloadType) Stringpublic

Inherited from DS.JSONSerializer but overwritten in addon/serializers/json-api.js:631

modelNameFromPayloadType can be used to change the mapping for a DS model name, taken from the value in the payload.

Say your API namespaces the type of a model and returns the following payload for the post model:

// GET /api/posts/1
{
  "data": {
    "id": 1,
    "type: "api::v1::post"
  }
}

By overwriting modelNameFromPayloadType you can specify that the post model should be used:

app/serializers/application.js
import DS from 'ember-data';

export default DS.JSONAPISerializer.extend({
  modelNameFromPayloadType(payloadType) {
    return payloadType.replace('api::v1::', '');
  }
});

By default the modelName for a model is its singularized name in dasherized form. Usually, Ember Data can use the correct inflection to do this for you. Most of the time, you won't need to override modelNameFromPayloadType for this purpose.

Also take a look at payloadTypeFromModelName to customize how the type of a record should be serialized.

Parameters:

payloadType String
type from payload

Returns:

String
modelName

payloadKeyFromModelName (modelName) String

Defined in addon/serializers/json-api.js:387

Converts the model name to a pluralized version of the model name.

For example post would be converted to posts and student-assesment would be converted to student-assesments.

Parameters:

modelName String

Returns:

String

payloadTypeFromModelName (modelname) Stringpublic

Defined in addon/serializers/json-api.js:679

payloadTypeFromModelName can be used to change the mapping for the type in the payload, taken from the model name.

Say your API namespaces the type of a model and expects the following payload when you update the post model:

// POST /api/posts/1
{
  "data": {
    "id": 1,
    "type": "api::v1::post"
  }
}

By overwriting payloadTypeFromModelName you can specify that the namespaces model name for the post should be used:

app/serializers/application.js
import DS from 'ember-data';

export default JSONAPISerializer.extend({
  payloadTypeFromModelName(modelName) {
    return 'api::v1::' + modelName;
  }
});

By default the payload type is the pluralized model name. Usually, Ember Data can use the correct inflection to do this for you. Most of the time, you won't need to override payloadTypeFromModelName for this purpose.

Also take a look at modelNameFromPayloadType to customize how the model name from should be mapped from the payload.

Parameters:

modelname String
modelName from the record

Returns:

String
payloadType

pushPayload (store, payload)

Defined in addon/serializers/json-api.js:241

Parameters:

store DS.Store
payload Object

© 2017 Yehuda Katz, Tom Dale and Ember.js contributors
Licensed under the MIT License.
https://emberjs.com/api/data/classes/DS.JSONAPISerializer.html

在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号

意见反馈
返回顶部