Skip to content

Instantly share code, notes, and snippets.

@greyhwndz
Forked from richmolj/nested_relationship_post.md
Last active September 15, 2015 20:07
Show Gist options
  • Save greyhwndz/c4d9da45171aa3d34fa0 to your computer and use it in GitHub Desktop.
Save greyhwndz/c4d9da45171aa3d34fa0 to your computer and use it in GitHub Desktop.
# Usage:
# 
# post.serialize(include: ['comments'], comments: {include: ['author']})
#
# gives:
# {
#   data: {
#     attributes: {id: 1, name: 'post name'},
#     relationships: {
#       comments: {
#         data: {
#           attributes: {id: 1, name: 'comment'},
#           relationships: {
#             author: {
#               data: {
#                 attributes: {id: 1, name: 'Stephen King'}
#               }
#             }
#           }
#         }
#       }
#     }
#   }
# }

`import DS from 'ember-data'`

ApplicationSerializer = DS.JSONAPISerializer.extend

  serialize: (snapshot, options) ->
    @_withOptions options, =>
      @_super(snapshot, options)

  serializeBelongsTo: (snapshot, json, relationship) ->
    key = relationship.key

    json.relationships = {} unless json.relationships
    if @_shouldInclude(key)
      subOpts = @_options[key]
      json.relationships[key] = snapshot.belongsTo(key).serialize(subOpts)
    json

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

    json.relationships = {} unless json.relationships
    if @_shouldInclude(key)
      mapped = snapshot.hasMany(key).map (associationSnapshot) =>
        subOpts = @_options[key]
        associationSnapshot.serialize(subOpts)
      json.relationships[key] = mapped
    json
    
  _withOptions: (options, fn) ->
    @_options = options || {}
    result = fn()
    @_options = null
    result

  _shouldInclude: (associationName) ->
    if includes = @_options['include']
      includes.contains(associationName)
    else
      false

`export default ApplicationSerializer`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment