Skip to content

Instantly share code, notes, and snippets.

@richmolj
Created September 2, 2015 15:26
Show Gist options
  • Save richmolj/edf25850a06759895caf to your computer and use it in GitHub Desktop.
Save richmolj/edf25850a06759895caf to your computer and use it in GitHub Desktop.
`import Ember from 'ember'`
class JSONAPISerialization
constructor: (@records) ->
@includes = []
toJSON: (opts = {}) =>
json = {}
if opts.single
json.data = @serializeRecord(@records)
else
json.data = @records.map (r) => @serializeRecord(r)
json.meta = opts.meta if opts.meta
json.included = @includes
json
dataTypeFor: (record, association_name) =>
record._relationship_types[association_name].dataType
serializeRecord: (record, opts = {}) =>
attributes = @attributes(record)
json =
id: record.id
type: record.jsonApiType
attributes: attributes
if relationships = @relationships(record)
json.relationships = relationships
json
relationships: (record) =>
relationships = {}
for association_name, associated_records of record.relationships
if record._relationship_types[association_name].type == 'hasMany'
array = []
for associated_record in associated_records
@includes.push(@serializeRecord(associated_record))
array.push(@relationshipAttributes(associated_record))
relationships[association_name] = {data: array}
else
@includes.push(@serializeRecord(associated_records))
relationships[association_name] = {data: @relationshipAttributes(associated_records)}
relationships
relationshipAttributes: (record) ->
json =
id: record.id,
type: record.jsonApiType
json
attributes: (record) =>
attributes = Ember.$.extend({}, record)
delete attributes.relationships
delete attributes.jsonApiType
delete attributes._relationship_types
delete attributes._deferred
attributes
`export var JSONAPISerialization`
# example usage
@get '/api/users', (db, request) ->
users = db.users
users.forEach (u) -> u.relationships.organization = db.organizations.find(u.organization_id)
serializer = new JSONAPISerialization(users)
serializer.toJSON(meta: total: users.length)
@get '/api/users/:id', (db, request) ->
user = db.users.find(request.params.id)
serializer = new JSONAPISerialization(user)
serializer.toJSON(single: true)
`import Mirage/*, {faker} */ from 'ember-cli-mirage';`
# I put the API type and relationship metadata on the factory. These will be referenced in the serializer,
# but not output
UserFactory = PullRequestFactory.extend
jsonApiType: 'users'
relationships: {}
_relationship_types:
organization:
type: 'belongsTo'
`export default UserFactory`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment