switch from axios to got package for client requests
[squeep-indieauth-helper] / lib / common.js
index f199b4947ed1ba537a29350c617322cf64678512..c1b8703d58d435a127a80fcfaec70b73358a2a2c 100644 (file)
@@ -1,35 +1,44 @@
 'use strict';
 
 const path = require('path');
+const { name: packageName, version: packageVersion } = require('../package');
+
+const libraryIdentifier = `${packageName}@${packageVersion}`;
 
 /**
  * Return a function which combines a part of the filename with a scope, for use in logging.
  * @param {string} filename
  */
 const fileScope = (filename) => {
-  let fScope = path.basename(filename, '.js');
-  if (fScope === 'index') {
-    fScope = path.basename(path.dirname(filename));
-  }
-  return (scope) => `${fScope}:${scope}`;
+  const shortFilename = path.basename(filename, '.js');
+  const fScope = (shortFilename === 'index') ? path.basename(path.dirname(filename)) : shortFilename;
+  return (scope) => [libraryIdentifier, fScope, scope].join(':');
 }
 
 
 /**
- * Pick out useful axios response fields.
- * @param {AxiosResponse} res
+ * Pick out useful got response fields.
+ * @param {GotResponse} res
  * @returns {Object}
  */
-const axiosResponseLogData = (res) => {
+const gotResponseLogData = (res) => {
   const data = pick(res, [
-    'status',
-    'statusText',
+    'statusCode',
+    'statusMessage',
     'headers',
-    'elapsedTimeMs',
-    'data',
+    'body',
   ]);
-  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>`;
+  }
+  data.elapsedTimeMs = res?.timings?.phases?.total;
+  if (res?.redirectUrls?.length) {
+    data.redirectUrls = res.redirectUrls;
+  }
+  if (res?.retryCount) {
+    data.retryCount = res.retryCount;
   }
   return data;
 };
@@ -97,23 +106,11 @@ const properURLComponentName = (component) => {
 }
 
 
-/**
- * Encodes single-level object as form data string.
- * @param {Object} data
- */
-const formData = (data) => {
-  const formData = new URLSearchParams();
-  Object.entries(data).forEach(([name, value]) => formData.set(name, value));
-  return formData.toString();
-};
-
-
 module.exports = {
   fileScope,
-  axiosResponseLogData,
+  gotResponseLogData,
   logTruncate,
   pick,
   setSymmetricDifference,
   properURLComponentName,
-  formData,
 };
\ No newline at end of file