Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion src/compat/realtime-mock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,15 @@ function createSocket(_url: string, handlers: SocketHandlers): RealtimeSocket {
}
switch (request.cmd) {
case 'bind': {
if (!state.values.has(request.name)) addVariable(state, request.name, null);
// A function can add a variable after `registerSystem`, as a plain property. The
// first binding keeps its value.
if (!state.values.has(request.name)) {
addVariable(
state,
request.name,
Reflect.get(state.module, request.name) ?? null,
);
}
const notify: Listener = (value) =>
reply({ id: request.id, type: 'notify', value: value ?? null, meta });
bound.get(key)?.();
Expand Down
28 changes: 28 additions & 0 deletions test/compat.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,34 @@ test('a 7.x binding and call use a 6.x mock system', async () => {
realtime.stop();
});

test('a binding keeps the value of a variable that a function added', async () => {
registerSystem('sys-2', {
Debug: [
{
$post(this: Record<string, unknown>, id: string, value: string) {
this[`logs:${id}`] = value;
},
},
],
});
const realtime = createRealtime({
base_url: 'http://mock.invalid',
auth: { kind: 'none' },
environment: mockRealtimeEnvironment(),
});
const logs = { sys: 'sys-2', mod: 'Debug', index: 1, name: 'post' };
expect(await realtime.exec(logs, ['a', 'first'])).toEqual({ ok: true, value: null });
const states: BindingState[] = [];
const release = realtime.bind({ ...logs, name: 'logs:a' }, (state) => states.push(state));
await waitFor(() => lastValue(states) === 'first');

// After the binding, a change notifies it.
expect((await realtime.exec(logs, ['a', 'second'])).ok).toBe(true);
await waitFor(() => lastValue(states) === 'second');
release();
realtime.stop();
});

function lastValue(states: readonly BindingState[]): unknown {
const last = states.at(-1);
return last?.kind === 'value' ? last.value : undefined;
Expand Down
Loading