I have a project with Elm on both client and server. The server is set up with ports to get a HTTP request from Node’s HTTP module with one port, and return a String response using another port:
The Elm part:
port module Server.Main exposing (main)
port httpRequests : (String -> msg) -> Sub msg
port httpResponse : String -> Cmd msg
The JS part:
http.createServer(function (req, res) {
new Promise(function(resolve, reject) {
const handler = response => {
resolve({response, handler});
};
app.ports.httpResponse.subscribe(handler);
})
.then(obj => {
res.writeHead(200, {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
});
res.write(obj.response);
res.end();
app.ports.httpResponse.unsubscribe(obj.handler);
})
app.ports.httpRequests.send(`http://localhost:${port}${req.url}`);
}).listen(port);
This works fine when I’m testing it (there is a lot of time between the requests), but it is, I think, not ideal, as when multiple requests happen “at the same time”, the responses can get switched. Ie. there is probably a race condition.
What to do here? Thread an ID through the ports with the request and response, and implement some kind of “unmatched responses queue” on the JS side, for when the errorneous switch happens? Any ideas?