2018-02-12 23:25:21 +00:00
|
|
|
import { copy } from '@ember/object/internals';
|
|
|
|
import { get } from '@ember/object';
|
2017-12-15 21:39:18 +00:00
|
|
|
import { makeArray } from '@ember/array';
|
2017-09-19 14:47:10 +00:00
|
|
|
import JSONSerializer from 'ember-data/serializers/json';
|
2018-04-07 01:07:57 +00:00
|
|
|
import removeRecord from '../utils/remove-record';
|
2017-09-19 14:47:10 +00:00
|
|
|
|
|
|
|
export default JSONSerializer.extend({
|
|
|
|
primaryKey: 'ID',
|
|
|
|
|
|
|
|
keyForAttribute(attr) {
|
|
|
|
return attr.camelize().capitalize();
|
|
|
|
},
|
|
|
|
|
|
|
|
keyForRelationship(attr, relationshipType) {
|
2017-10-13 22:17:51 +00:00
|
|
|
const key = `${attr
|
|
|
|
.singularize()
|
|
|
|
.camelize()
|
|
|
|
.capitalize()}ID`;
|
2017-09-19 14:47:10 +00:00
|
|
|
return relationshipType === 'hasMany' ? key.pluralize() : key;
|
|
|
|
},
|
|
|
|
|
|
|
|
// Modeled after the pushPayload for ember-data/serializers/rest
|
|
|
|
pushPayload(store, payload) {
|
|
|
|
const documentHash = {
|
|
|
|
data: [],
|
|
|
|
included: [],
|
|
|
|
};
|
|
|
|
|
|
|
|
Object.keys(payload).forEach(key => {
|
|
|
|
const modelName = this.modelNameFromPayloadKey(key);
|
|
|
|
const serializer = store.serializerFor(modelName);
|
|
|
|
const type = store.modelFor(modelName);
|
|
|
|
|
|
|
|
makeArray(payload[key]).forEach(hash => {
|
|
|
|
const { data, included } = serializer.normalize(type, hash, key);
|
|
|
|
documentHash.data.push(data);
|
|
|
|
if (included) {
|
|
|
|
documentHash.included.push(...included);
|
|
|
|
}
|
|
|
|
});
|
2018-02-12 23:25:21 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
store.push(documentHash);
|
|
|
|
},
|
|
|
|
|
2018-02-14 23:42:34 +00:00
|
|
|
normalizeFindAllResponse(store, modelClass) {
|
2018-02-12 23:25:21 +00:00
|
|
|
const result = this._super(...arguments);
|
|
|
|
this.cullStore(store, modelClass.modelName, result.data);
|
|
|
|
return result;
|
|
|
|
},
|
2017-09-19 14:47:10 +00:00
|
|
|
|
2018-02-12 23:25:21 +00:00
|
|
|
// When records are removed server-side, and therefore don't show up in requests,
|
|
|
|
// the local copies of those records need to be unloaded from the store.
|
2018-02-14 23:42:34 +00:00
|
|
|
cullStore(store, type, records, storeFilter = () => true) {
|
2018-02-12 23:25:21 +00:00
|
|
|
const newRecords = copy(records).filter(record => get(record, 'id'));
|
|
|
|
const oldRecords = store.peekAll(type);
|
2018-02-14 23:42:34 +00:00
|
|
|
oldRecords
|
|
|
|
.filter(record => get(record, 'id'))
|
|
|
|
.filter(storeFilter)
|
|
|
|
.forEach(old => {
|
|
|
|
const newRecord = newRecords.find(record => get(record, 'id') === get(old, 'id'));
|
|
|
|
if (!newRecord) {
|
2018-04-07 01:07:57 +00:00
|
|
|
removeRecord(store, old);
|
2018-02-14 23:42:34 +00:00
|
|
|
} else {
|
|
|
|
newRecords.removeObject(newRecord);
|
|
|
|
}
|
|
|
|
});
|
2017-09-19 14:47:10 +00:00
|
|
|
},
|
|
|
|
|
|
|
|
modelNameFromPayloadKey(key) {
|
|
|
|
return key.dasherize().singularize();
|
|
|
|
},
|
|
|
|
});
|