Skip to content

Commit c8bd4b4

Browse files
committed
Added itemForKey
1 parent 7b59014 commit c8bd4b4

4 files changed

Lines changed: 35 additions & 3 deletions

File tree

docs/hds-lib.js

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

docs/hds-lib.js.map

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/HDSModel.js

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,8 +28,37 @@ class HDSModel {
2828
const response = await fetch(this.#modelUrl);
2929
const resultText = await response.text();
3030
const result = JSON.parse(resultText);
31-
this.#modelData = result;
31+
this.#modelData = deepFreeze(result);
32+
}
33+
34+
/**
35+
* get item for a key
36+
* @param {string} key
37+
*/
38+
itemForKey (key) {
39+
return this.#modelData.items[key];
3240
}
3341
}
3442

3543
module.exports = HDSModel;
44+
45+
/**
46+
* Recursively make immutable an object
47+
* @param {*} object
48+
* @returns {*}
49+
*/
50+
function deepFreeze (object) {
51+
// Retrieve the property names defined on object
52+
const propNames = Reflect.ownKeys(object);
53+
54+
// Freeze properties before freezing self
55+
for (const name of propNames) {
56+
const value = object[name];
57+
58+
if ((value && typeof value === 'object') || typeof value === 'function') {
59+
deepFreeze(value);
60+
}
61+
}
62+
63+
return Object.freeze(object);
64+
}

tests/hdsModel.test.js

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
/* eslint-env mocha */
2+
const assert = require('node:assert/strict');
23

34
const modelURL = 'https://model.datasafe.dev/pack.json';
45

@@ -8,5 +9,7 @@ describe('[MODX] Model', () => {
89
it('[MODL] Load model', async () => {
910
const model = new HDSModel(modelURL);
1011
await model.load();
12+
const item = model.itemForKey('body-weight');
13+
assert.equal(item.streamId, 'body-weight');
1114
});
1215
});

0 commit comments

Comments
 (0)