artistsWorker.js 991 B

123456789101112131415161718192021222324252627282930313233343536
  1. /*
  2. Musicify - Artists Worker
  3. Offloads listArtists fetch + JSON parsing from the main UI thread.
  4. */
  5. self.onmessage = function(evt) {
  6. var msg = evt && evt.data ? evt.data : {};
  7. if (msg.type !== 'fetchArtists') return;
  8. var reqId = msg.reqId;
  9. var endpoint = msg.endpoint;
  10. fetch(endpoint, {
  11. method: 'POST',
  12. cache: 'no-cache',
  13. headers: { 'Content-Type': 'application/json' },
  14. body: JSON.stringify({})
  15. }).then(function(resp) {
  16. if (!resp.ok) {
  17. throw new Error('HTTP ' + resp.status);
  18. }
  19. return resp.json();
  20. }).then(function(data) {
  21. self.postMessage({
  22. type: 'artistsResult',
  23. reqId: reqId,
  24. items: Array.isArray(data) ? data : []
  25. });
  26. }).catch(function(err) {
  27. self.postMessage({
  28. type: 'artistsError',
  29. reqId: reqId,
  30. error: (err && err.message) ? err.message : 'Fetch failed'
  31. });
  32. });
  33. };