From 6ceb302bac28d7ce03165854edb978aee4a72694 Mon Sep 17 00:00:00 2001 From: Kiko Beats Date: Mon, 29 Apr 2024 10:24:52 +0200 Subject: [PATCH] refactor: extract util --- src/error.js | 9 +-------- src/stats.js | 10 ++-------- src/util.js | 29 +++++++---------------------- 3 files changed, 10 insertions(+), 38 deletions(-) diff --git a/src/error.js b/src/error.js index 82db93f..6117228 100644 --- a/src/error.js +++ b/src/error.js @@ -1,13 +1,6 @@ 'use strict' -const isPlainObject = value => { - if (!value || typeof value !== 'object' || value.toString() !== '[object Object]') { - return false - } - - const prototype = Object.getPrototypeOf(value) - return prototype === null || prototype === Object.prototype -} +const { isPlainObject } = require('./util') class OpenKeyError extends Error { constructor (props) { diff --git a/src/stats.js b/src/stats.js index ef0db9e..11b9402 100644 --- a/src/stats.js +++ b/src/stats.js @@ -3,17 +3,11 @@ const { promisify } = require('util') const stream = require('stream') -const { Transform } = stream +const { formatYYYMMDDDate } = require('./util') +const { Transform } = stream const pipeline = promisify(stream.pipeline) -const formatYYYMMDDDate = (now = new Date()) => { - const year = now.getFullYear() - const month = String(now.getMonth() + 1).padStart(2, '0') - const day = String(now.getDate()).padStart(2, '0') - return `${year}-${month}-${day}` -} - /** * 90 days in milliseconds */ diff --git a/src/util.js b/src/util.js index a33fead..ed22daa 100644 --- a/src/util.js +++ b/src/util.js @@ -20,26 +20,11 @@ const pick = (obj, keys) => { return result } -/** - * Assert a condition, or throw an error if the condition is falsy. - * @param {*} value - The value to assert. - * @param {string} message - The error message. - */ -const assert = (value, message) => - value || - (() => { - throw new TypeError(message()) - })() - -const assertMetadata = metadata => { - if (metadata) { - assert(isPlainObject(metadata), () => 'The metadata must be a flat object.') - Object.keys(metadata).forEach(key => { - assert(!isPlainObject(metadata[key]), () => `The metadata field '${key}' can't be an object.`) - if (metadata[key] === undefined) delete metadata[key] - }) - return Object.keys(metadata).length ? metadata : undefined - } +const formatYYYMMDDDate = (now = new Date()) => { + const year = now.getFullYear() + const month = String(now.getMonth() + 1).padStart(2, '0') + const day = String(now.getDate()).padStart(2, '0') + return `${year}-${month}-${day}` } const isPlainObject = value => { @@ -52,8 +37,8 @@ const isPlainObject = value => { } module.exports = { - assert, - assertMetadata, + formatYYYMMDDDate, + isPlainObject, pick, uid }