Files
threshold-ui/addons/api/mirage/serializers/application.js
T

82 lines
1.8 KiB
JavaScript
Raw Normal View History

2020-05-19 18:10:39 -04:00
import { RestSerializer } from 'ember-cli-mirage';
import { underscore } from '@ember/string';
2020-06-17 13:20:57 -04:00
import { isArray } from '@ember/array';
2020-05-19 18:10:39 -04:00
/**
* Manages serialization/normalization of data into and out of the mock API.
*/
export default RestSerializer.extend({
// =attributes
/**
* False to disable automatically rooting payloads under a key.
* This is handled by the `serialize()` method, see below.
* @type {boolean}
*/
root: false,
/**
* @type {boolean}
*/
embed: true,
// =methods
/**
* Generates an underscored key for the attribute.
* @param {string} attr
* @return {string}
*/
keyForAttribute(attr) {
return underscore(attr);
},
keyForRelationshipId(relationshipName) {
return `${this._container.inflector.singularize(
underscore(relationshipName)
)}_id`;
},
2020-05-19 18:10:39 -04:00
/**
* Serialize items into a root key `items`.
* @return {object}
*/
serialize() {
let json = RestSerializer.prototype.serialize.apply(this, arguments);
// If array, root it under a standard `items` key
2021-03-04 15:47:38 -05:00
if (isArray(json)) json = { items: json };
2020-05-19 18:10:39 -04:00
return json;
2020-05-21 10:59:42 -04:00
},
/**
* Serialize scope into the payload, if set.
* @param {object} model
* @return {object}
*/
_hashForModel(model) {
const json = RestSerializer.prototype._hashForModel.apply(this, arguments);
if (model.scope) {
json.scope = {
id: model.scope.id,
2021-03-04 15:47:38 -05:00
type: model.scope.type,
};
}
return json;
},
2020-05-21 10:59:42 -04:00
/**
* Adds a root to the payload, since `root: false` doesn't appear to affect
* the normalize method.
* @param {object} json
* @return {object}
*/
normalize(json) {
let newJSON = json;
if (this.modelName) {
newJSON = {};
newJSON[this.modelName] = json;
}
const value = RestSerializer.prototype.normalize.apply(this, [newJSON]);
return value;
2021-03-04 15:47:38 -05:00
},
2020-05-19 18:10:39 -04:00
});