Browse Source

feat: support key value for set with transformers

feature/data-sources
danstarns 2 years ago
parent
commit
7f22ab897f
  1. 29
      src/data_sources/model/DataRecord.ts
  2. 38
      test/specs/data_sources/model/ComponentDataVariable.ts
  3. 3
      test/specs/data_sources/transformers.ts

29
src/data_sources/model/DataRecord.ts

@ -139,16 +139,27 @@ export default class DataRecord<T extends DataRecordProps = DataRecordProps> ext
set(attributeName: unknown, value?: unknown, options?: SetOptions): DataRecord {
const onRecordSet = this.dataSource?.transformers?.onRecordSet;
const newValue =
options?.avoidTransformers || !onRecordSet
? value
: onRecordSet({
id: this.id,
key: attributeName as string,
value,
});
const applySet = (key: string, val: unknown) => {
const newValue =
options?.avoidTransformers || !onRecordSet
? val
: onRecordSet({
id: this.id,
key,
value: val,
});
super.set(attributeName as string, newValue, options);
super.set(key, newValue, options);
};
if (typeof attributeName === 'object' && attributeName !== null) {
const attributes = attributeName as Partial<T>;
for (const [key, val] of Object.entries(attributes)) {
applySet(key, val);
}
} else {
applySet(attributeName as string, value);
}
return this;
}

38
test/specs/data_sources/model/ComponentDataVariable.ts

@ -257,4 +257,42 @@ describe('ComponentDataVariable', () => {
expect(cmp.getEl()?.innerHTML).toContain('NestedItemName1-UP');
});
test('component initalizes and updates data on datarecord set object', () => {
const dataSource: DataSourceProps = {
id: 'setObject',
records: [{ id: 'id1', content: 'Hello World', color: 'red' }],
};
dsm.add(dataSource);
const cmp = cmpRoot.append({
tagName: 'h1',
type: 'text',
components: [
{
type: DataVariableType,
defaultValue: 'default',
path: `${dataSource.id}.id1.content`,
},
],
style: {
color: {
type: DataVariableType,
defaultValue: 'black',
path: `${dataSource.id}.id1.color`,
},
},
})[0];
const style = cmp.getStyle();
expect(style).toHaveProperty('color', 'red');
expect(cmp.getEl()?.innerHTML).toContain('Hello World');
const ds = dsm.get('setObject');
ds.getRecord('id1')?.set({ content: 'Hello World UP', color: 'blue' });
const updatedStyle = cmp.getStyle();
expect(updatedStyle).toHaveProperty('color', 'blue');
expect(cmp.getEl()?.innerHTML).toContain('Hello World UP');
});
});

3
test/specs/data_sources/transformers.ts

@ -105,8 +105,9 @@ describe('DataSource Transformers', () => {
const dr = ds.addRecord({ id: 'id1', content: 'i love grapes' });
expect(() => dr.set('content', 123)).toThrowError('Value must be a string');
expect(() => dr.set({ content: 123 })).toThrowError('Value must be a string');
dr.set('content', 'I LOVE GRAPES');
dr.set({ content: 'I LOVE GRAPES' });
const el = cmp.getEl();
expect(el?.innerHTML).toContain('I LOVE GRAPES');

Loading…
Cancel
Save