Skip to content

Commit

Permalink
refactor: extract assert helper
Browse files Browse the repository at this point in the history
  • Loading branch information
Kikobeats committed Jan 14, 2024
1 parent 34aeb29 commit 3b3dfc6
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 33 deletions.
25 changes: 11 additions & 14 deletions src/keys.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { pick, uid, validateKey } from './util.js'
import { pick, uid, validateKey, assert } from './util.js'

export const KEY_PREFIX = 'key_'
const KEY_FIELDS = ['name', 'description', 'enabled', 'value', 'plan']
Expand All @@ -19,8 +19,7 @@ export default ({ serialize, deserialize, plans, redis } = {}) => {
* @returns {Object} The created key.
*/
const create = async (opts = {}) => {
if (!opts.name) throw TypeError('The argument `name` is required.')

assert(opts.name, 'The argument `name` is required.')
const key = pick(opts, KEY_FIELDS.concat(KEY_FIELDS_OBJECT))
key.id = await uid({ redis, prefix: KEY_PREFIX, size: 5 })
key.createdAt = key.updatedAt = Date.now()
Expand All @@ -45,8 +44,8 @@ export default ({ serialize, deserialize, plans, redis } = {}) => {
{ throwError = false, validate = true } = {}
) => {
const key = await redis.get(getKey(keyId, { validate }))
if (key === null && throwError) {
throw new TypeError(`The key \`${keyId}\` does not exist.`)
if (throwError) {
assert(key !== null, `The key \`${keyId}\` does not exist.`)
}
return deserialize(key)
}
Expand All @@ -60,22 +59,20 @@ export default ({ serialize, deserialize, plans, redis } = {}) => {
*/
const del = async keyId => {
const key = await retrieve(keyId, { verify: true })

if (key !== null && typeof key.plan === 'string') {
const plan = await plans.retrieve(key.plan, {
throwError: true,
validate: false
})
if (plan !== null) {
throw new TypeError(
`The key \`${keyId}\` is associated with the plan \`${getKey.plan}\``
)
}
assert(
plan === null,
`The key \`${keyId}\` is associated with the plan \`${getKey.plan}\``
)
}

const isDeleted = (await redis.del(getKey(keyId, { verify: true }))) === 1
if (!isDeleted) throw new TypeError(`The key \`${keyId}\` does not exist.`)
return isDeleted
return (
assert(isDeleted, `The key \`${keyId}\` does not exist.`) || isDeleted
)
}

/**
Expand Down
35 changes: 17 additions & 18 deletions src/plans.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { pick, uid, validateKey } from './util.js'
import { pick, uid, validateKey, assert } from './util.js'

export const PLAN_PREFIX = 'plan_'
const PLAN_QUOTA_PERIODS = ['day', 'week', 'month']
Expand All @@ -23,17 +23,17 @@ export default ({ serialize, deserialize, redis } = {}) => {
* @returns {Object|null} The plan object, null if it doesn't exist.
*/
const create = async (opts = {}) => {
if (!opts.name) throw TypeError('The argument `name` is required.')
if (!PLAN_QUOTA_PERIODS.includes(opts.quota?.period)) {
throw TypeError(
`The argument \`quota.period\` must be ${PLAN_QUOTA_PERIODS.map(
period => `\`${period}\``
).join(' or ')}.`
)
}
if (!opts.quota?.limit) {
throw TypeError('The argument `quota.limit` must be a positive number.')
}
assert(opts.name, 'The argument `name` is required.')
assert(
PLAN_QUOTA_PERIODS.includes(opts.quota?.period),
`The argument \`quota.period\` must be ${PLAN_QUOTA_PERIODS.map(
period => `\`${period}\``
).join(' or ')}.`
)
assert(
opts.quota.limit,
'The argument `quota.limit` must be a positive number.'
)
const plan = pick(opts, PLAN_FIELDS.concat(PLAN_FIELDS_OBJECT))
plan.id = await uid({ redis, prefix: PLAN_PREFIX, size: 5 })
plan.createdAt = plan.updatedAt = Date.now()
Expand All @@ -55,8 +55,8 @@ export default ({ serialize, deserialize, redis } = {}) => {
{ throwError = false, validate = true } = {}
) => {
const plan = await redis.get(getKey(planId, { validate }))
if (plan === null && throwError) {
throw new TypeError(`The plan \`${planId}\` does not exist.`)
if (throwError) {
assert(plan !== null, `The plan \`${planId}\` does not exist.`)
}
return deserialize(plan)
}
Expand All @@ -72,10 +72,9 @@ export default ({ serialize, deserialize, redis } = {}) => {
const del = async planId => {
const isDeleted =
(await redis.del(getKey(planId, { validate: true }))) === 1
if (!isDeleted) {
throw new TypeError(`The plan \`${planId}\` does not exist.`)
}
return isDeleted
return (
assert(isDeleted, `The plan \`${planId}\` does not exist.`) || isDeleted
)
}

/**
Expand Down
10 changes: 9 additions & 1 deletion src/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,18 @@ export const pick = (obj, keys) => {
return result
}

export const assert = (value, message) => {
// TODO: strict true/false check
if (!value) throw new TypeError(message)
return value
}

export const validateKey =
({ prefix }) =>
(id, { validate = true } = {}) => {
if (!validate) return id
if (!String(id).startsWith(prefix)) { throw new TypeError(`The id \`${id}\` must to start with \`${prefix}\`.`) }
if (!String(id).startsWith(prefix)) {
throw new TypeError(`The id \`${id}\` must to start with \`${prefix}\`.`)
}
return id
}

0 comments on commit 3b3dfc6

Please sign in to comment.