switch from axios to got package for client requests
[squeep-indieauth-helper] / lib / common.js
1 'use strict';
2
3 const path = require('path');
4 const { name: packageName, version: packageVersion } = require('../package');
5
6 const libraryIdentifier = `${packageName}@${packageVersion}`;
7
8 /**
9 * Return a function which combines a part of the filename with a scope, for use in logging.
10 * @param {string} filename
11 */
12 const fileScope = (filename) => {
13 const shortFilename = path.basename(filename, '.js');
14 const fScope = (shortFilename === 'index') ? path.basename(path.dirname(filename)) : shortFilename;
15 return (scope) => [libraryIdentifier, fScope, scope].join(':');
16 }
17
18
19 /**
20 * Pick out useful got response fields.
21 * @param {GotResponse} res
22 * @returns {Object}
23 */
24 const gotResponseLogData = (res) => {
25 const data = pick(res, [
26 'statusCode',
27 'statusMessage',
28 'headers',
29 'body',
30 ]);
31 if (typeof res.body === 'string') {
32 data.body = logTruncate(data.body, 100);
33 } else if (res.body instanceof Buffer) {
34 data.body = `<Buffer ${res.body.byteLength} bytes>`;
35 }
36 data.elapsedTimeMs = res?.timings?.phases?.total;
37 if (res?.redirectUrls?.length) {
38 data.redirectUrls = res.redirectUrls;
39 }
40 if (res?.retryCount) {
41 data.retryCount = res.retryCount;
42 }
43 return data;
44 };
45
46
47 /**
48 * Limit length of string to keep logs sane
49 * @param {String} str
50 * @param {Number} len
51 * @returns {String}
52 */
53 const logTruncate = (str, len) => {
54 if (typeof str !== 'string' || str.toString().length <= len) {
55 return str;
56 }
57 return str.toString().slice(0, len) + `... (${str.toString().length} bytes)`;
58 };
59
60
61 /**
62 * Return a new object with selected props.
63 * @param {Object} obj
64 * @param {String[]} props
65 */
66 const pick = (obj, props) => {
67 return props.reduce((acc, prop) => {
68 if (prop in obj) {
69 acc[prop] = obj[prop]; // eslint-disable-line security/detect-object-injection
70 }
71 return acc;
72 }, {});
73 };
74
75
76 /**
77 * Return a set containing non-shared items between two sets.
78 * @param {Set} a
79 * @param {Set} b
80 * @returns {Set}
81 */
82 const setSymmetricDifference = (a, b) => {
83 const d = new Set(a);
84 for (const x of b) {
85 if (d.has(x)) {
86 d.delete(x);
87 } else {
88 d.add(x);
89 }
90 }
91 return d;
92 };
93
94
95 /**
96 * URL objects have weird names.
97 * @param {String} component
98 * @returns {String}
99 */
100 const properURLComponentName = (component) => {
101 // eslint-disable-next-line security/detect-object-injection
102 return {
103 hash: 'fragment',
104 protocol: 'scheme',
105 }[component] || component;
106 }
107
108
109 module.exports = {
110 fileScope,
111 gotResponseLogData,
112 logTruncate,
113 pick,
114 setSymmetricDifference,
115 properURLComponentName,
116 };