Skip to content

Commit

Permalink
build: tweaks
Browse files Browse the repository at this point in the history
  • Loading branch information
Kikobeats committed Apr 28, 2024
1 parent ec2181a commit 7b62c0b
Show file tree
Hide file tree
Showing 6 changed files with 72 additions and 36 deletions.
1 change: 0 additions & 1 deletion .npmrc
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
audit=false
enable-pre-post-scripts=true
fund=false
loglevel=error
package-lock=false
Expand Down
13 changes: 0 additions & 13 deletions bin/help.txt

This file was deleted.

65 changes: 48 additions & 17 deletions bin/index.js
100644 → 100755
Original file line number Diff line number Diff line change
@@ -1,25 +1,56 @@
#!/usr/bin/env node
'use strict'

const { styleText } = require('util')
const openkey = require('openkey')
const createRepl = require('repl')
const Redis = require('ioredis')
const path = require('path')
const mri = require('mri')
const os = require('os')

const { _, ...flags } = mri(process.argv.slice(2), {
/* https://github.com/lukeed/mri#usage< */
default: {
token: process.env.GH_TOKEN || process.env.GITHUB_TOKEN
const redis = new Redis()

const commands = Object.assign(
{
version: () => require('../package.json').version,
exit: () => process.exit()
},
openkey({ redis })
)

const replEval = async input => {
const [command, subcommand, ...args] = input.slice(0, -1).split(' ')
const { _, ...opts } = mri(args)
const cmd = commands[command]

if (cmd) {
return subcommand ? cmd[subcommand](opts) : cmd(opts)
} else if (command === 'help' || command === '') {
return Object.keys(commands).join(' ')
}
})
}

if (flags.help) {
console.log(require('fs').readFileSync('./help.txt', 'utf8'))
process.exit(0)
const completer = line => {
const completions = Object.keys(commands)
const lineParts = line.split(' ')
const hits = completions.filter(c => c.startsWith(lineParts[lineParts.length - 1]))
return [hits.length ? hits : completions, line]
}

Promise.resolve(require('openkey')(flags))
.then(() => {
process.exit(0)
})
.catch(error => {
console.error(error)
process.exit(1)
})
const repl = createRepl.start({
prompt: '\x1b[1mopenkey\x1b[0m> ',
eval: (input, context, filename, callback) => {
replEval(input, context, filename)
.then(result => {
if (result) console.log(result)
})
.catch(error => {
console.error(styleText('red', error.message))
})
.finally(callback)
},
completer
})

repl.setupHistory(path.join(os.homedir(), '.openkey_repl_history'), () => {})
Object.getOwnPropertyNames(repl.context).forEach(mod => delete repl.context[mod])
14 changes: 11 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "openkey",
"description": "authentication & rate limit for HTTP backed in Redis.",
"homepage": "https://github.com/microlinkhq/openkey",
"homepage": "https://openkey.js.org",
"version": "0.0.0",
"exports": {
".": "./src/index.js",
Expand Down Expand Up @@ -31,7 +31,10 @@
},
"keywords": [],
"dependencies": {
"mri": "~1.2.0"
"http-body": "~1.0.11",
"mri": "~1.2.0",
"ms": "~2.1.3",
"send-http": "~1.0.6"
},
"devDependencies": {
"@commitlint/cli": "latest",
Expand Down Expand Up @@ -77,7 +80,12 @@
"commitlint": {
"extends": [
"@commitlint/config-conventional"
]
],
"rules": {
"body-max-length": [
0
]
}
},
"nano-staged": {
"*.js": [
Expand Down
5 changes: 3 additions & 2 deletions src/plans.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,13 @@ module.exports = ({ serialize, deserialize, redis, keys, prefix } = {}) => {
const metadata = assertMetadata(opts.metadata)
if (metadata) plan.metadata = metadata
plan.createdAt = plan.updatedAt = Date.now()
await redis.set(prefixKey(opts.id), serialize(plan), 'NX')
const isCreated = (await redis.set(prefixKey(opts.id), serialize(plan), 'NX')) === 'OK'
if (!isCreated) throw new TypeError(`The plan \`${opts.id}\` already exists.`)
return Object.assign({ id: opts.id }, plan)
}

/**
* Retrieve a plan by id
* Retrieve a plan by id.
*
* @param {string} id - The id of the plan.
* @param {Object} [options] - The options for retrieving a plan.
Expand Down
10 changes: 10 additions & 0 deletions test/plans.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,16 @@ test('.create # `id` is required', async t => {
}
})

test('.create # the `id` already exist', async t => {
const id = randomUUID()
const props = { id, limit: 1, period: '1s', metadata: { tier: undefined } }
const plan = await plans.create(props)
t.is(typeof plan, 'object')
const error = await t.throwsAsync(plans.create(props))
t.is(error.message, `The plan \`${id}\` already exists.`)
t.is(error.name, 'TypeError')
})

test('.create # `id` cannot contain whitespaces', async t => {
const error = await t.throwsAsync(plans.create({ id: 'free tier' }))
t.is(error.message, 'The argument `id` cannot contain whitespace.')
Expand Down

0 comments on commit 7b62c0b

Please sign in to comment.