chore: 🤖 add support for grants on role model

This commit is contained in:
Randall Morey committed 2020-08-07 15:42:40 -04:00
1 parent 13f76659e4
commit ee6999251d
4 files changed
+102 -1

No files matched your search

+28 -1
View File
@@ -1,3 +1,30 @@
import GeneratedRoleModel from '../generated/models/role';
import { array } from 'ember-data-model-fragments/attributes';
export default class RoleModel extends GeneratedRoleModel {}
export default class RoleModel extends GeneratedRoleModel {
// =attributes
/**
* Grants is read-only _most_ under normal circumstances. But grants can
* be persisted via a dedicated call to `saveGrants()`.
*/
@array({readOnly: true}) grants;
// =methods
/**
* Saves the `grants` array on the role via the `set-grants` method.
* See serializer and adapter for more information.
* @return {Promise}
*/
saveGrants() {
return this.save({
adapterOptions: {
method: 'set-grants',
serializeGrants: true
}
});
}
}
+29
View File
@@ -0,0 +1,29 @@
import ApplicationSerializer from './application';
import { get } from '@ember/object';
export default class RoleSerializer extends ApplicationSerializer {
// =methods
/**
* If `adapterOptions.serializeGrants` is true, the serialization should
* include **only grants** and nothing else. Normally, grants are not
* serialized.
* @override
* @param {Snapshot} snapshot
* @return {object}
*/
serialize(snapshot) {
const serializeGrants = get(snapshot, 'adapterOptions.serializeGrants');
let serialized = super.serialize(...arguments);
if (serializeGrants) serialized = this.serializeWithGrants(snapshot);
return serialized;
}
serializeWithGrants(snapshot) {
return {
grants: snapshot.attr('grants')
};
}
}
+1
View File
@@ -0,0 +1 @@
export { default } from 'api/serializers/role';
@@ -0,0 +1,44 @@
import { module, test } from 'qunit';
import { setupTest } from 'ember-qunit';
module('Unit | Serializer | role', function(hooks) {
setupTest(hooks);
test('it serializes roles normally, without grants', function (assert) {
assert.expect(1);
const store = this.owner.lookup('service:store');
const serializer = store.serializerFor('role');
const record = store.createRecord('role', {
name: 'User',
description: 'Description',
grants: ['foo', 'bar']
});
const snapshot = record._createSnapshot();
snapshot.adapterOptions = {};
const serializedRecord = serializer.serialize(snapshot);
assert.deepEqual(serializedRecord, {
name: 'User',
description: 'Description'
});
});
test('it serializes only grants when `adapterOptions.serializeGrants` is true', function (assert) {
assert.expect(1);
const store = this.owner.lookup('service:store');
const serializer = store.serializerFor('role');
const record = store.createRecord('role', {
name: 'User',
description: 'Description',
grants: ['foo', 'bar']
});
const snapshot = record._createSnapshot();
snapshot.adapterOptions = {
serializeGrants: true
};
const serializedRecord = serializer.serialize(snapshot);
assert.deepEqual(serializedRecord, {
grants: ['foo', 'bar']
});
});
});