Software zum Installieren eines Smart-Mirror Frameworks , zum Nutzen von hochschulrelevanten Informationen, auf einem Raspberry-Pi.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.js 2.0KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. 'use strict';
  2. const retry = require('retry');
  3. const networkErrorMsgs = [
  4. 'Failed to fetch', // Chrome
  5. 'NetworkError when attempting to fetch resource.', // Firefox
  6. 'The Internet connection appears to be offline.', // Safari
  7. 'Network request failed' // `cross-fetch`
  8. ];
  9. class AbortError extends Error {
  10. constructor(message) {
  11. super();
  12. if (message instanceof Error) {
  13. this.originalError = message;
  14. ({message} = message);
  15. } else {
  16. this.originalError = new Error(message);
  17. this.originalError.stack = this.stack;
  18. }
  19. this.name = 'AbortError';
  20. this.message = message;
  21. }
  22. }
  23. const decorateErrorWithCounts = (error, attemptNumber, options) => {
  24. // Minus 1 from attemptNumber because the first attempt does not count as a retry
  25. const retriesLeft = options.retries - (attemptNumber - 1);
  26. error.attemptNumber = attemptNumber;
  27. error.retriesLeft = retriesLeft;
  28. return error;
  29. };
  30. const isNetworkError = errorMessage => networkErrorMsgs.includes(errorMessage);
  31. const pRetry = (input, options) => new Promise((resolve, reject) => {
  32. options = {
  33. onFailedAttempt: () => {},
  34. retries: 10,
  35. ...options
  36. };
  37. const operation = retry.operation(options);
  38. operation.attempt(async attemptNumber => {
  39. try {
  40. resolve(await input(attemptNumber));
  41. } catch (error) {
  42. if (!(error instanceof Error)) {
  43. reject(new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`));
  44. return;
  45. }
  46. if (error instanceof AbortError) {
  47. operation.stop();
  48. reject(error.originalError);
  49. } else if (error instanceof TypeError && !isNetworkError(error.message)) {
  50. operation.stop();
  51. reject(error);
  52. } else {
  53. decorateErrorWithCounts(error, attemptNumber, options);
  54. try {
  55. await options.onFailedAttempt(error);
  56. } catch (error) {
  57. reject(error);
  58. return;
  59. }
  60. if (!operation.retry(error)) {
  61. reject(operation.mainError());
  62. }
  63. }
  64. }
  65. });
  66. });
  67. module.exports = pRetry;
  68. // TODO: remove this in the next major version
  69. module.exports.default = pRetry;
  70. module.exports.AbortError = AbortError;