WIP
[webmention-receiver] / src / common.js
1 'use strict';
2
3 const { common } = require('@squeep/api-dingus');
4
5
6 /**
7 * Return an array containing x if x is not already an array.
8 * @param {*} x
9 */
10 const ensureArray = (x) => {
11 if (x === undefined) {
12 return [];
13 }
14 if (!Array.isArray(x)) {
15 return Array(x);
16 }
17 return x;
18 };
19
20
21 /**
22 * Recursively freeze an object.
23 * @param {Object} o
24 * @returns {Object}
25 */
26 const freezeDeep = (o) => {
27 Object.freeze(o);
28 Object.getOwnPropertyNames(o).forEach((prop) => {
29 if (Object.hasOwnProperty.call(o, prop)
30 && ['object', 'function'].includes(typeof o[prop])
31 && !Object.isFrozen(o[prop])) {
32 return freezeDeep(o[prop]);
33 }
34 });
35 return o;
36 }
37
38
39 /**
40 * Limit length of string to keep logs sane
41 * @param {String} str
42 * @param {Number} len
43 * @returns {String}
44 */
45 const logTruncate = (str, len) => {
46 if (typeof str !== 'string' || str.toString().length <= len) {
47 return str;
48 }
49 return str.toString().slice(0, len) + `... (${str.toString().length} bytes)`;
50 };
51
52
53 module.exports = {
54 ...common,
55 ensureArray,
56 freezeDeep,
57 logTruncate,
58 };