Skip to content

Instantly share code, notes, and snippets.

@zacck-zz
Last active October 28, 2018 10:01
Show Gist options
  • Save zacck-zz/1f73eae6499b3f48e4f80b684f450983 to your computer and use it in GitHub Desktop.
Save zacck-zz/1f73eae6499b3f48e4f80b684f450983 to your computer and use it in GitHub Desktop.
subscribe : SelectionSet response RootSubscription -> Session -> Cmd msg
subscribe query session =
let
headers : List ( String, String )
headers =
[ ( "authorization", JWT.authorizationHeader session.jwt )
]
queryString : String
queryString =
Document.serializeSubscription query
in
Ports.subscribeTo
{ endpoint = Env.graphqlEndpoint
, headers = headers
, query = queryString
}
app.ports.subscribeTo.subscribe(function(subscriptionRequest) {
var xhr = new XMLHttpRequest();
var linesSeen = 0;
xhr.open("POST", subscriptionRequest.endpoint, true);
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
subscriptionRequest.headers.forEach(function([header, value]) {
xhr.setRequestHeader(header, value);
});
xhr.onreadystatechange = function(event) {
};
xhr.onprogress = function(event) {
if (xhr.responseText !== "" && xhr.responseText !== undefined) {
try {
var oldLinesSeen = linesSeen;
var lines = xhr.responseText.split("\n");
var linesSeen = lines.length;
lines.forEach(function(line, index) {
if (index <= oldLinesSeen) { return };
if (line == "") { return };
app.ports.notifySubscription.send(line);
});
} catch (error) {
console.log('Error processing json', error);
}
}
};
xhr.send(JSON.stringify({ query: subscriptionRequest.query }));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment