update dependencies, devDependencies, copyright
[websub-hub] / src / common.js
index 0cacc3bf086f2b57f0b10db1ef289c6be7961e15..f7c54ef85a9ba1f96306e4dfb938897f14868348 100644 (file)
@@ -26,6 +26,22 @@ const validHash = (algorithm) => getHashes()
   .filter((h) => h.match(/^sha[0-9]+$/))
   .includes(algorithm);
 
+
+/**
+ * Return an array containing x if x is not an array.
+ * @param {*} x
+ */
+const ensureArray = (x) => {
+  if (x === undefined) {
+    return [];
+  }
+  if (!Array.isArray(x)) {
+    return Array(x);
+  }
+  return x;
+};
+
+
 /**
  * Recursively freeze an object.
  * @param {Object} o 
@@ -41,24 +57,35 @@ const freezeDeep = (o) => {
     }
   });
   return o;
-}
+};
 
 
 /**
- * Pick out useful axios response fields.
+ * Pick out useful got response fields.
  * @param {*} res 
  * @returns 
  */
-const axiosResponseLogData = (res) => {
+const gotResponseLogData = (res) => {
   const data = common.pick(res, [
-    'status',
-    'statusText',
+    'statusCode',
+    'statusMessage',
     'headers',
-    'elapsedTimeMs',
-    'data',
+    'body',
+    'error',
   ]);
-  if (data.data) {
-    data.data = logTruncate(data.data, 100);
+  if (typeof res.body === 'string') {
+    data.body = logTruncate(data.body, 100);
+  } else if (res.body instanceof Buffer) {
+    data.body = `<Buffer ${res.body.byteLength} bytes>`;
+  }
+  if (res?.timings?.phases?.total) {
+    data.elapsedTimeMs = res.timings.phases.total;
+  }
+  if (res?.redirectUrls?.length) {
+    data.redirectUrls = res.redirectUrls;
+  }
+  if (res?.retryCount) {
+    data.retryCount = res.retryCount;
   }
   return data;
 };
@@ -95,7 +122,7 @@ const attemptRetrySeconds = (attempt, retryBackoffSeconds = [60, 120, 360, 1440,
   let seconds = retryBackoffSeconds[attempt];
   seconds += Math.floor(Math.random() * seconds * jitter);
   return seconds;
-}
+};
 
 
 /**
@@ -106,7 +133,7 @@ const attemptRetrySeconds = (attempt, retryBackoffSeconds = [60, 120, 360, 1440,
 const arrayChunk = (array, per = 1) => {
   const nChunks = Math.ceil(array.length / per);
   return Array.from(Array(nChunks), (_, i) => array.slice(i * per, (i + 1) * per));
-}
+};
 
 
 /**
@@ -119,7 +146,7 @@ const stackSafePush = (dst, src) => {
   arrayChunk(src, jsEngineMaxArguments).forEach((items) => {
     Array.prototype.push.apply(dst, items);
   });
-}
+};
 
 
 /**
@@ -139,7 +166,8 @@ module.exports = {
   ...common,
   arrayChunk,
   attemptRetrySeconds,
-  axiosResponseLogData,
+  gotResponseLogData,
+  ensureArray,
   freezeDeep,
   logTruncate,
   randomBytesAsync,