use separate base64url module, update dependencies and devDependencies
[squeep-indieauth-helper] / lib / common.js
1 'use strict';
2
3 const path = require('path');
4
5 /**
6 * Return a function which combines a part of the filename with a scope, for use in logging.
7 * @param {string} filename
8 */
9 const fileScope = (filename) => {
10 let fScope = path.basename(filename, '.js');
11 if (fScope === 'index') {
12 fScope = path.basename(path.dirname(filename));
13 }
14 return (scope) => `${fScope}:${scope}`;
15 }
16
17
18 /**
19 * Pick out useful axios response fields.
20 * @param {*} res
21 * @returns
22 */
23 const axiosResponseLogData = (res) => {
24 const data = pick(res, [
25 'status',
26 'statusText',
27 'headers',
28 'elapsedTimeMs',
29 'data',
30 ]);
31 if (data.data) {
32 data.data = logTruncate(data.data, 100);
33 }
34 return data;
35 };
36
37
38 /**
39 * Limit length of string to keep logs sane
40 * @param {String} str
41 * @param {Number} len
42 * @returns {String}
43 */
44 const logTruncate = (str, len) => {
45 if (typeof str !== 'string' || str.toString().length <= len) {
46 return str;
47 }
48 return str.toString().slice(0, len) + `... (${str.toString().length} bytes)`;
49 };
50
51
52 /**
53 * Return a new object with selected props.
54 * @param {Object} obj
55 * @param {String[]} props
56 */
57 const pick = (obj, props) => {
58 return props.reduce((acc, prop) => {
59 if (prop in obj) {
60 acc[prop] = obj[prop]; // eslint-disable-line security/detect-object-injection
61 }
62 return acc;
63 }, {});
64 };
65
66
67 module.exports = {
68 fileScope,
69 axiosResponseLogData,
70 logTruncate,
71 pick,
72 };