Skip to content

Commit

Permalink
refactor: extract util
Browse files Browse the repository at this point in the history
  • Loading branch information
Kikobeats committed Apr 29, 2024
1 parent bb6c685 commit 6ceb302
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 38 deletions.
9 changes: 1 addition & 8 deletions src/error.js
Original file line number Diff line number Diff line change
@@ -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) {
Expand Down
10 changes: 2 additions & 8 deletions src/stats.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
*/
Expand Down
29 changes: 7 additions & 22 deletions src/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 => {
Expand All @@ -52,8 +37,8 @@ const isPlainObject = value => {
}

module.exports = {
assert,
assertMetadata,
formatYYYMMDDDate,
isPlainObject,
pick,
uid
}

0 comments on commit 6ceb302

Please sign in to comment.