Skip to content

Commit

Permalink
refactor(client): allow receiving metadata
Browse files Browse the repository at this point in the history
see #7
  • Loading branch information
TimoBechtel committed Jan 27, 2021
1 parent 3a80482 commit 6cebf47
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 5 deletions.
10 changes: 6 additions & 4 deletions src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,14 @@ import { Node, nodeify, traverseNode, unwrap } from './node';

type Unsubscriber = () => void;

type Meta = { [namespace: string]: any };

export type ChainReference = {
get: (path: string) => ChainReference;
each: (callback: (ref: ChainReference, key: string) => void) => Unsubscriber;
set: (value: any) => ChainReference;
on: (callback: (data: any) => void) => Unsubscriber;
once: (callback: (data: any) => void) => void;
on: (callback: (data: any, meta: Meta) => void) => Unsubscriber;
once: (callback: (data: any, meta: Meta) => void) => void;
};

type UpdateListener = {
Expand Down Expand Up @@ -189,7 +191,7 @@ export function SocketDBClient({
},
on(callback) {
const listener = (data: Node) => {
callback(unwrap(data));
callback(unwrap(data), data.meta);
};
subscribe(path, listener);
return () => {
Expand All @@ -201,7 +203,7 @@ export function SocketDBClient({
// maybe should use subscribe {once: true} ?
// and not send "unsubscribe" back
unsubscribe(path, listener);
callback(unwrap(data));
callback(unwrap(data), data.meta);
});
},
};
Expand Down
30 changes: 29 additions & 1 deletion test/client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,33 @@ test('received data should not be passed as reference', (done) => {
client.get('data').set(testData);
});

test('also receives metadata', (done) => {
const metaExample = { owner: 'Thomas' };
const { addListener, removeListener, notify } = createEventBroker();
const socketClient: SocketClient = {
onConnect() {},
onDisconnect() {},
off: removeListener,
on: addListener,
send(event) {
if (event === 'subscribe') {
notify('players/1', {
data: { meta: metaExample, value: 'Thomas' },
});
}
},
};
const client = SocketDBClient({ socketClient });

client
.get('players')
.get('1')
.on((_, meta) => {
expect(meta).toEqual(metaExample);
done();
});
});

test('on/once always receives data on first call', (done) => {
const { addListener, removeListener, notify } = createEventBroker();
const socketClient: SocketClient = {
Expand All @@ -286,14 +313,15 @@ test('on/once always receives data on first call', (done) => {
.get('1')
.on(() => {
updateCount++;
expect(updateCount).toBe(2);
done();
});
}
},
};
const client = SocketDBClient({ socketClient });

let updateCount = 1;
let updateCount = 0;
client
.get('players')
.get('1')
Expand Down

0 comments on commit 6cebf47

Please sign in to comment.