Api.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import {
  2. topicUrlJsonPoll,
  3. fetchLinesIterator,
  4. topicUrl,
  5. topicUrlAuth,
  6. maybeWithBasicAuth,
  7. topicShortUrl,
  8. topicUrlJsonPollWithSince
  9. } from "./utils";
  10. class Api {
  11. async poll(baseUrl, topic, since, user) {
  12. const shortUrl = topicShortUrl(baseUrl, topic);
  13. const url = (since > 1) // FIXME Ahh, this is >1, because we do +1 when we call this .....
  14. ? topicUrlJsonPollWithSince(baseUrl, topic, since)
  15. : topicUrlJsonPoll(baseUrl, topic);
  16. const messages = [];
  17. const headers = maybeWithBasicAuth({}, user);
  18. console.log(`[Api] Polling ${url}`);
  19. for await (let line of fetchLinesIterator(url, headers)) {
  20. console.log(`[Api, ${shortUrl}] Received message ${line}`);
  21. messages.push(JSON.parse(line));
  22. }
  23. return messages;
  24. }
  25. async publish(baseUrl, topic, user, message) {
  26. const url = topicUrl(baseUrl, topic);
  27. console.log(`[Api] Publishing message to ${url}`);
  28. await fetch(url, {
  29. method: 'PUT',
  30. body: message,
  31. headers: maybeWithBasicAuth({}, user)
  32. });
  33. }
  34. async auth(baseUrl, topic, user) {
  35. const url = topicUrlAuth(baseUrl, topic);
  36. console.log(`[Api] Checking auth for ${url}`);
  37. const response = await fetch(url, {
  38. headers: maybeWithBasicAuth({}, user)
  39. });
  40. if (response.status >= 200 && response.status <= 299) {
  41. return true;
  42. } else if (!user && response.status === 404) {
  43. return true; // Special case: Anonymous login to old servers return 404 since /<topic>/auth doesn't exist
  44. } else if (response.status === 401 || response.status === 403) { // See server/server.go
  45. return false;
  46. }
  47. throw new Error(`Unexpected server response ${response.status}`);
  48. }
  49. }
  50. const api = new Api();
  51. export default api;