initial commit
[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 * Convert Base64 to Base64URL.
20 * @param {String} input
21 * @returns {String}
22 */
23 const base64ToBase64URL = (input) => {
24 return input
25 .replace(/=/g, '')
26 .replace(/\+/g, '-')
27 .replace(/\//g, '_');
28 };
29
30
31 /**
32 * Pick out useful axios response fields.
33 * @param {*} res
34 * @returns
35 */
36 const axiosResponseLogData = (res) => {
37 const data = pick(res, [
38 'status',
39 'statusText',
40 'headers',
41 'elapsedTimeMs',
42 'data',
43 ]);
44 if (data.data) {
45 data.data = logTruncate(data.data, 100);
46 }
47 return data;
48 };
49
50
51 /**
52 * Limit length of string to keep logs sane
53 * @param {String} str
54 * @param {Number} len
55 * @returns {String}
56 */
57 const logTruncate = (str, len) => {
58 if (typeof str !== 'string' || str.toString().length <= len) {
59 return str;
60 }
61 return str.toString().slice(0, len) + `... (${str.toString().length} bytes)`;
62 };
63
64
65 /**
66 * Return a new object with selected props.
67 * @param {Object} obj
68 * @param {String[]} props
69 */
70 const pick = (obj, props) => {
71 return props.reduce((acc, prop) => {
72 if (prop in obj) {
73 acc[prop] = obj[prop]; // eslint-disable-line security/detect-object-injection
74 }
75 return acc;
76 }, {});
77 };
78
79
80 module.exports = {
81 fileScope,
82 base64ToBase64URL,
83 axiosResponseLogData,
84 logTruncate,
85 pick,
86 };