add websocket endpoint /api/workout/:id/subscribe.

This commit is contained in:
2019-10-30 21:27:22 +01:00
parent 9bc39e5d60
commit e3c7730f1d
5 changed files with 75 additions and 3 deletions
+40
View File
@@ -174,5 +174,45 @@ module.exports = function workoutRouter(repo) {
}
});
router.ws("/:id/subscribe", (ws, req) => {
console.log("HELLO!")
const workout = workouts.find(w => w.id === req.params.id);
if (workout == null) {
ws.send(JSON.stringify({error: "workout not found"}));
ws.close();
}
workout.listMeasurements().then((list) => {
ws.send(JSON.stringify({workoutStatusBackfill: list}));
}).catch(err => {
ws.send(JSON.stringify({error: `could not list measurements: ${err.message || err}`}));
ws.close();
});
const handler = (workotuStatus) => {
workotuStatus = {...workotuStatus};
delete workotuStatus.id;
ws.send(JSON.stringify({workotuStatus}))
}
workout.events.on("workoutStatus", handler);
ws.onclose = () => {
workout.events.removeListener("workoutStatus", handler);
ws.removeAllListeners();
};
ws.send(JSON.stringify({
workout: {
id: workout.id,
bike: workout.bike,
program: workout.program,
date: workout.date,
},
}));
})
return router;
}