Commit abf6fd23 authored by jpellizzari's avatar jpellizzari
Browse files

Added shape check PoC

No related merge requests found
Showing with 94 additions and 0 deletions
+94 -0
import expect from 'expect';
import { isCompatibleShape } from '../storage-utils';
describe('storage-utils', () => {
let state;
beforeEach(() => {
state = {
controlPipe: null,
nodeDetails: [],
topologyViewMode: 'topo',
pinnedMetricType: 'CPU',
pinnedSearches: [],
searchQuery: '',
selectedNodeId: null,
gridSortedBy: null,
gridSortedDesc: null,
topologyId: 'containers',
topologyOptions: {
processes: {
unconnected: 'hide'
},
containers: {
system: [
'all'
],
stopped: [
'running'
],
pseudo: [
'hide'
]
}
},
contrastMode: false
};
});
it('is ok when state has not changed', () => {
// Same state should be ok
expect(isCompatibleShape(state, state)).toBe(true);
});
it('catches state shape changes', () => {
// State shape changed, should not be compatible;
const changed = {
...state,
topologyOptions: {
...state.topologyOptions,
processes: {
// Changes from a string to an array; simulates the actual real-world case
unconnected: ['hide']
}
}
};
expect(isCompatibleShape(state, changed)).toBe(false);
});
it('ignores trivial shape differences', () => {
const trivial = {
...state,
nodeDetails: [{ a: 1, b: 2 }],
controlPipe: { id: 123 }
};
expect(isCompatibleShape(state, trivial)).toBe(true);
});
});
import debug from 'debug';
import reduce from 'lodash/reduce';
const log = debug('scope:storage-utils');
......@@ -44,3 +45,29 @@ export function storageSetObject(key, obj) {
}
return false;
}
function typeOf(obj) {
return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();
}
// Checks the shape of an object. Ignores the signature of elements in arrays.
function shapeOf(obj) {
return reduce(obj, (result, val, key) => {
const type = typeOf(val);
if (type === 'null' || type === 'undefined') {
// Do nothing
return result;
} else if (type === 'object') {
result[key] = shapeOf(val);
} else {
result[key] = type;
}
return result;
}, {});
}
export function isCompatibleShape(object, target) {
const shape = JSON.stringify(shapeOf(object));
const targetString = JSON.stringify(shapeOf(target));
return shape === targetString;
}
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment