acquia / waterwheel.js

A generic JavaScript helper library to query and manipulate Drupal 8 via core REST and JSON API
https://github.com/acquia/waterwheel.js
233 stars 26 forks source link

Add JSON API deserializaton. #67

Closed Decipher closed 6 years ago

Decipher commented 6 years ago

The jsonapi-serializer package (https://www.npmjs.com/package/jsonapi-serializer) provides the ability to deserialize JSON API responses, simplifying the data for usage.

As an example, with deserialization you can turn this:

{
  "data": [{
    "type": "users",
    "id": "1",
    "attributes": {
      "first-name": "Sandro",
      "last-name": "Munda"
    }
  }, {
    "type": "users",
    "id": "2",
    "attributes": {
      "first-name": "John",
      "last-name": "Doe"
    }
  }]
}

into this:

[
  { id: 1, firstName: 'Sandro', lastName: 'Munda' },
  { id: 2, firstName: 'John', lastName: 'Doe' }
]

Or for more of a practical example, this: response.data.relationships.field_image.data[0].meta.width

to this: entity.image.meta.width

(Although that last example is done with a relationship and transform callback).

Decipher commented 6 years ago

An example of Waterwheel and JSON API serializer in a current NuxtJS project:

      return app.$waterwheel.jsonapi.get('node/photo', {
        // Consumer ID required to consumer image styles.
        _consumer_id: process.env.API_CONSUMER_CLIENT_ID,
        fields: {
          'file--file': 'url',
          'node--photo': 'title,field_image'
        },
        include: 'field_image'
      })

        // Deserialize / Normalize the data.
        .then(res => new Deserializer({
          keyForAttribute: 'camelCase',

          // Transforms.
          transform: function (record) {
            record['image'] = record['fieldImage']
            delete record['fieldImage']
            return record
          },

          // Relationships.
          'file--file': {
            valueForRelationship: function (relationship, included) {
              return {
                id: relationship.id,
                url: {
                  _original: included.url,
                  thumbnail: included.meta.derivatives.thumbnail
                },
                meta: relationship.meta
              }
            }
          }
        })

          // Deserialize.
          .deserialize(res, (err, data) => {
            if (!err) {
              return data
            }
          }))
mattgrill commented 6 years ago

@Decipher I'd rather not add another dependency. Waterwheel is mostly intended to be a middleware-type library. If you want to deserialize the incoming JSON API data there's nothing in Waterwheel stopping you from doing this.

I'll close this for now but feel free to reopen if you think there is value. Thanks.