X-Git-Url: http://git.squeep.com/?a=blobdiff_plain;f=lib%2Fcommon.js;h=c1b8703d58d435a127a80fcfaec70b73358a2a2c;hb=57cb2f2fc75ae447dfcc750bb62dcc8bb487cd15;hp=cfdf9db7e5c47feda5e05b52624a17a25949d853;hpb=1c4bb7e3bbdc1121ceba373c5be4459521197155;p=squeep-indieauth-helper diff --git a/lib/common.js b/lib/common.js index cfdf9db..c1b8703 100644 --- a/lib/common.js +++ b/lib/common.js @@ -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 {*} res - * @returns + * 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 = ``; + } + data.elapsedTimeMs = res?.timings?.phases?.total; + if (res?.redirectUrls?.length) { + data.redirectUrls = res.redirectUrls; + } + if (res?.retryCount) { + data.retryCount = res.retryCount; } return data; }; @@ -64,9 +73,44 @@ const pick = (obj, props) => { }; +/** + * Return a set containing non-shared items between two sets. + * @param {Set} a + * @param {Set} b + * @returns {Set} + */ +const setSymmetricDifference = (a, b) => { + const d = new Set(a); + for (const x of b) { + if (d.has(x)) { + d.delete(x); + } else { + d.add(x); + } + } + return d; +}; + + +/** + * URL objects have weird names. + * @param {String} component + * @returns {String} + */ +const properURLComponentName = (component) => { + // eslint-disable-next-line security/detect-object-injection + return { + hash: 'fragment', + protocol: 'scheme', + }[component] || component; +} + + module.exports = { fileScope, - axiosResponseLogData, + gotResponseLogData, logTruncate, pick, + setSymmetricDifference, + properURLComponentName, }; \ No newline at end of file