Skip to content

Commit

Permalink
feat: separate json transformation from websocket store
Browse files Browse the repository at this point in the history
fixes #539

BREAKING CHANGE: websocketStore transparently passes values (strings). JSON encoding/decoding must be handeled separatly
  • Loading branch information
arlac77 committed Mar 24, 2022
1 parent b61c621 commit 67237c0
Showing 1 changed file with 26 additions and 4 deletions.
30 changes: 26 additions & 4 deletions src/index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ const reopenTimeouts = [2000, 5000, 10000, 30000, 60000];

/**
* Create a writable store based on a web-socket.
* Data is transferred as JSON.
* Keeps socket open (reopens if closed) as long as there are subscriptions.
* @param {string} url the WebSocket url
* @param {any} initialValue store value used before 1st. response from server is present
Expand Down Expand Up @@ -54,7 +53,7 @@ export function websocketStore(url, initialValue, socketOptions) {
socket = new WebSocket(url, socketOptions);

socket.onmessage = event => {
initialValue = JSON.parse(event.data);
initialValue = event.data;
subscriptions.forEach(subscription => subscription(initialValue));
};

Expand All @@ -76,7 +75,7 @@ export function websocketStore(url, initialValue, socketOptions) {

return {
set(value) {
const send = () => socket.send(JSON.stringify(value));
const send = () => socket.send(value);
if (socket.readyState !== WebSocket.OPEN) open().then(send);
else send();
},
Expand All @@ -94,4 +93,27 @@ export function websocketStore(url, initialValue, socketOptions) {
};
}

export default websocketStore;
export default websocketStore;


export function jsonTransformerStore(store) {

let subscription = store.subscribe(this);

//JSON.parse();

return {
set(value) {
store.set(JSON.stringify(value));
},
subscribe(subscription) {
subscriptions.add(subscription);

subscriptions.forEach(subscription => subscription(initialValue));

return () => {
subscriptions.delete(subscription);
};
}
};
}

0 comments on commit 67237c0

Please sign in to comment.