Skip to content

Commit

Permalink
[Live] Throwing an error when setting an invalid model name
Browse files Browse the repository at this point in the history
  • Loading branch information
weaverryan committed Oct 21, 2023
1 parent 5979432 commit ed68c9c
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 1 deletion.
3 changes: 3 additions & 0 deletions src/LiveComponent/assets/dist/live_controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -1799,6 +1799,9 @@ class Component {
set(model, value, reRender = false, debounce = false) {
const promise = this.nextRequestPromise;
const modelName = normalizeModelName(model);
if (!this.valueStore.has(modelName)) {
throw new Error(`Invalid model name "${model}".`);
}
const isChanged = this.valueStore.set(modelName, value);
this.hooks.triggerHook('model:set', model, value, this);
this.unsyncedInputsTracker.markModelAsSynced(modelName);
Expand Down
4 changes: 4 additions & 0 deletions src/LiveComponent/assets/src/Component/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,10 @@ export default class Component {
set(model: string, value: any, reRender = false, debounce: number|boolean = false): Promise<BackendResponse> {
const promise = this.nextRequestPromise;
const modelName = normalizeModelName(model);

if (!this.valueStore.has(modelName)) {
throw new Error(`Invalid model name "${model}".`);
}
const isChanged = this.valueStore.set(modelName, value);

this.hooks.triggerHook('model:set', model, value, this);
Expand Down
10 changes: 9 additions & 1 deletion src/LiveComponent/assets/test/Component/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ const makeTestComponent = (): { component: Component, backend: MockBackend } =>
const component = new Component(
document.createElement('div'),
'test-component',
{ firstName: '' },
{ firstName: '', product: { name: '' } },
[],
() => [],
null,
Expand Down Expand Up @@ -65,6 +65,14 @@ describe('Component class', () => {
// @ts-ignore
expect(await backendResponse?.getBody()).toEqual('<div data-live-props-value="{}"></div>');
});

it('errors when an invalid model is passed', async () => {
const { component } = makeTestComponent();

// setting nested - totally ok
component.set('product.name', 'Ryan', false);
expect(() => { component.set('notARealModel', 'Ryan', false) }).toThrow('Invalid model name "notARealModel"');
});
});

describe('Proxy wrapper', () => {
Expand Down

0 comments on commit ed68c9c

Please sign in to comment.