refactor: represent scopes as fragments and special-case serialization of parent IDs on scopes themselves

This commit is contained in:
Randall Morey committed 2020-07-22 11:47:33 -04:00
1 parent d9795daf1b
commit 3d432950d6
12 files changed
+148 -108

No files matched your search

+19 -5
View File
@@ -1,19 +1,33 @@
import Model from '@ember-data/model';
import { belongsTo } from '@ember-data/model';
import { fragment } from 'ember-data-model-fragments/attributes';
import { computed } from '@ember/object';
import { get } from '@ember/object';
export default class BaseModel extends Model {
// =relationships
/**
* Scope of this resource, if any.
* @type {ScopeModel}
* Scope of this resource, if any, represented as a JSON fragment.
* @type {FragmentParentScope}
*/
@belongsTo('scope', {async: false, inverse: false}) scope;
@fragment('fragment-parent-scope') scope;
// =attributes
/**
* Convenience for getting and setting the parent scope ID.
* @type {string
*/
@computed('scope.scope_id')
get scopeID() {
return get(this, 'scope.scope_id');
}
set scopeID(id) {
if (!this.scope) this.scope = {};
this.scope.scope_id = id;
}
/**
* Names are optional on models in our API. Thus we need to fallback on ID
* for display purposes.
@@ -61,7 +75,7 @@ export default class BaseModel extends Model {
* @return {Promise}
*/
save(options={adapterOptions: {}}) {
const scopeID = this.belongsTo('scope').id();
const scopeID = this.scopeID;
if (scopeID && !options.adapterOptions.scopeID) {
options.adapterOptions.scopeID = scopeID;
}
@@ -0,0 +1,36 @@
import Fragment from 'ember-data-model-fragments/fragment';
import { computed } from '@ember/object';
import { attr } from '@ember-data/model';
import { scopeTypes } from './scope';
export default class FragmentParentScope extends Fragment {
// =attributes
@attr('string', {
description: 'ID of the related scope'
}) scope_id;
@attr('string', {
description: 'The type of the resource'
}) type;
/**
* @type {boolean}
*/
@computed('type')
get isGlobal() { return this.type === scopeTypes.global; }
/**
* @type {boolean}
*/
@computed('type')
get isOrg() { return this.type === scopeTypes.org; }
/**
* @type {boolean}
*/
@computed('type')
get isProject() { return this.type === scopeTypes.project; }
}
-15
View File
@@ -1,5 +1,4 @@
import GeneratedScopeModel from '../generated/models/scope';
import { belongsTo, hasMany } from '@ember-data/model';
import { computed } from '@ember/object';
export const scopeTypes = {
@@ -10,20 +9,6 @@ export const scopeTypes = {
export default class ScopeModel extends GeneratedScopeModel {
// =relationships
/**
* The parent scope, if any.
* @type {ScopeModel}
*/
@belongsTo('scope', {inverse: 'children'}) scope;
/**
* The inverse of parent scope, children.
* @type {ScopeModelp[]}
*/
@hasMany('scope', {inverse: 'scope'}) children;
// =attributes
/**
@@ -24,15 +24,6 @@ export default class ApplicationSerializer extends RESTSerializer {
return underscore(attr);
}
/**
* Generates an underscored key for the relationship ending in `_id`.
* @param {string} rel
* @return {string}
*/
keyForRelationship(rel) {
return underscore(rel);
}
/**
* If an attribute is annotated as readOnly in the model, don't serialize it.
* Otherwise delegate to default attribute serializer.
@@ -137,19 +128,4 @@ export default class ApplicationSerializer extends RESTSerializer {
);
}
/**
* Returns the default extraction with one difference. If the extracted
* relationship does not include a `type` field as required by JSON API
* (the Ember internal record representation), one is added.
* @override
* @param {Object} relationshipModelName
* @param {Object} relationshipHash
* @return {Object}
*/
extractRelationship(relationshipModelName/*, relationshipHash*/) {
const relationship = super.extractRelationship(...arguments);
if (!relationship.type) relationship.type = relationshipModelName;
return relationship;
}
}
+35
View File
@@ -0,0 +1,35 @@
import ApplicationSerializer from './application';
export default class ScopeSerializer extends ApplicationSerializer {
// =attributes
attrs = {
scope: { serialize: true }
};
// =methods
/**
* While most resources do not serialize scope into a request body (scope
* is expressed in the URL), scopes themselves _do serialize scope_ as a
* string field `parent_scope_id`.
* Otherwise delegate to default attribute serializer.
*
* @override
* @method serializeAttribute
* @param {Snapshot} snapshot
* @param {Object} json
* @param {String} key
* @param {Object} attribute
*/
serializeAttribute(snapshot, json, key) {
let value = super.serializeAttribute(...arguments);
if (key === 'scope' && this._canSerialize(key)) {
json.parent_scope_id = snapshot.attr('scope').attr('scope_id');
delete json[key];
}
return value;
}
}
@@ -0,0 +1 @@
export { default } from 'api/models/fragment-parent-scope';
+1
View File
@@ -0,0 +1 @@
export { default } from 'api/serializers/scope';
+1
View File
@@ -41,6 +41,7 @@
"ember-cli-uglify": "^3.0.0",
"ember-copy": "^1.0.0",
"ember-data": "^3.16.0",
"ember-data-model-fragments": "5.0.0-beta.0",
"ember-disable-prototype-extensions": "^1.1.3",
"ember-export-application-global": "^2.0.1",
"ember-get-config": "^0.2.4",
+7 -11
View File
@@ -26,20 +26,17 @@ module('Unit | Model | base', function (hooks) {
data: {
id: '123abc',
type: 'user',
attributes: {},
relationships: {
attributes: {
scope: {
data: {
id: 'o_1',
type: 'scope'
}
scope_id: 'o_1',
type: 'scope'
}
}
}
});
const scope = store.peekRecord('scope', 'o_1');
const model = store.peekRecord('user', '123abc');
assert.equal(model.scope, scope);
assert.equal(model.scope.scope_id, scope.id);
});
test('it has a displayName attribute', function (assert) {
@@ -88,8 +85,7 @@ module('Unit | Model | base', function (hooks) {
test('it saves records to a scoped URL', async function (assert) {
assert.expect(3);
const store = this.owner.lookup('service:store');
const scope = store.createRecord('scope', {id: 'o_123'});
const model = store.createRecord('user', { scope });
const model = store.createRecord('user', { scopeID: 'o_123' });
this.server.post('/v1/o_123/users', () => {
assert.ok(true, 'Correctly scoped create record URL was requested.')
return {};
@@ -111,7 +107,7 @@ module('Unit | Model | base', function (hooks) {
assert.expect(3);
const store = this.owner.lookup('service:store');
const customScopeID = 'global';
const scope = store.createRecord('scope', {id: 'o_123'});
const scope = {scope_id: 'o_123'};
const model = store.createRecord('user', { scope });
this.server.post('/v1/global/users', () => {
assert.ok(true, 'Correctly scoped create record URL was requested.')
@@ -134,7 +130,7 @@ module('Unit | Model | base', function (hooks) {
assert.expect(1);
const store = this.owner.lookup('service:store');
const method = 'my-custom-method';
const scope = store.createRecord('scope', {id: 'o_123'});
const scope = {scope_id: 'o_123'};
const model = store.createRecord('user', { scope });
this.server.post(`/v1/o_123/users:${method}`, () => {
assert.ok(true, 'Correctly scoped create record URL was requested.')
+12 -50
View File
@@ -6,65 +6,27 @@ module('Unit | Model | scope', function(hooks) {
setupTest(hooks);
setupMirage(hooks);
test('it exists', function(assert) {
assert.expect(1);
const store = this.owner.lookup('service:store');
const model = store.createRecord('scope', {});
assert.ok(model);
});
test('it has self-referential parent and child relationships', async function(assert) {
assert.expect(9);
test('it may have a scope fragment', async function(assert) {
assert.expect(6);
const store = this.owner.lookup('service:store');
this.server.get('/v1/scopes', () => ({
items: [
{id: 'global', type: 'global'},
{id: 'o_1', type: 'org', scope: {id: 'global'}},
{id: 'o_2', type: 'org', scope: {id: 'global'}},
{id: 'p_1', type: 'project', scope: {id: 'o_1'}},
{id: 'p_2', type: 'project', scope: {id: 'o_1'}},
{id: 'p_3', type: 'project', scope: {id: 'o_2'}},
{id: 'o_1', type: 'org', scope: {scope_id: 'global'}},
{id: 'o_2', type: 'org', scope: {scope_id: 'global'}},
{id: 'p_1', type: 'project', scope: {scope_id: 'o_1'}},
{id: 'p_2', type: 'project', scope: {scope_id: 'o_1'}},
{id: 'p_3', type: 'project', scope: {scope_id: 'o_2'}},
]
}));
const scopes = await store.findAll('scope');
// check integrity of scope relationships
assert.notOk(await scopes.firstObject.get('scope'), 'Global scope has no parent');
assert.equal(await scopes.firstObject.get('children.length'), 2, 'Global scope has two children scopes');
assert.equal(await scopes.objectAt(1).get('scope.id'), 'global', 'Org 1 parent scope is global');
assert.equal(await scopes.objectAt(2).get('scope.id'), 'global', 'Org 2 parent scope is global');
assert.equal(await scopes.objectAt(1).get('children.length'), 2, 'Org 1 has two children scopes');
assert.equal(await scopes.objectAt(2).get('children.length'), 1, 'Org 2 has one child scope');
assert.equal(await scopes.objectAt(3).get('scope.id'), 'o_1', 'Project 1 parent scope is org 1');
assert.equal(await scopes.objectAt(4).get('scope.id'), 'o_1', 'Project 2 parent scope is org 1');
assert.equal(await scopes.objectAt(5).get('scope.id'), 'o_2', 'Project 3 parent scope is org 2');
});
test('it can load the parent scope if it is not already loaded', async function(assert) {
assert.expect(3);
const store = this.owner.lookup('service:store');
store.push({
data: {
id: 'p_1',
type: 'scope',
attributes: {},
relationships: {
scope: {
data: {
id: 'o_1',
type: 'scope'
}
}
}
}
});
this.server.get('/v1/scopes/o_1', () => {
assert.ok(true, 'Correct parent scope was requested.');
return { id: 'o_1' };
});
const project = store.peekRecord('scope', 'p_1');
assert.equal(project.belongsTo('scope').id(), 'o_1');
const org = await project.get('scope');
assert.equal(org.id, 'o_1');
assert.equal(await scopes.objectAt(1).get('scope.scope_id'), 'global', 'Org 1 parent scope is global');
assert.equal(await scopes.objectAt(2).get('scope.scope_id'), 'global', 'Org 2 parent scope is global');
assert.equal(await scopes.objectAt(3).get('scope.scope_id'), 'o_1', 'Project 1 parent scope is org 1');
assert.equal(await scopes.objectAt(4).get('scope.scope_id'), 'o_1', 'Project 2 parent scope is org 1');
assert.equal(await scopes.objectAt(5).get('scope.scope_id'), 'o_2', 'Project 3 parent scope is org 2');
});
test('it has isType boolean getters and setters', async function(assert) {
@@ -14,17 +14,18 @@ module('Unit | Serializer | application', function (hooks) {
test('it serializes records', function (assert) {
assert.expect(1);
const store = this.owner.lookup('service:store');
const scope = store.createRecord('scope', {id: 'global'});
const record = store.createRecord('user', {
name: 'User',
description: 'Description',
scope
scope: {
scope_id: 'global',
type: 'global'
}
});
const serializedRecord = record.serialize();
assert.deepEqual(serializedRecord, {
name: 'User',
description: 'Description'
//disabled: false, // TODO: disabled is temporarily disabled
});
});
@@ -0,0 +1,32 @@
import { module, test } from 'qunit';
import { setupTest } from 'ember-qunit';
module('Unit | Serializer | scope', function(hooks) {
setupTest(hooks);
// Replace this with your real tests.
test('it exists', function(assert) {
let store = this.owner.lookup('service:store');
let serializer = store.serializerFor('scope');
assert.ok(serializer);
});
test('it serializes records', function (assert) {
assert.expect(1);
const store = this.owner.lookup('service:store');
const record = store.createRecord('scope', {
type: 'org',
name: 'User',
description: 'Description',
scopeID: 'global'
});
const serializedRecord = record.serialize();
assert.deepEqual(serializedRecord, {
type: 'org',
name: 'User',
description: 'Description',
parent_scope_id: 'global'
});
});
});