Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(cli): add --delay/-d option #1513

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 6 additions & 0 deletions src/app.ts
Expand Up @@ -16,6 +16,7 @@ const isProduction = process.env['NODE_ENV'] === 'production'
export type AppOptions = {
logger?: boolean
static?: string[]
delay?: number
}

const eta = new Eta({
Expand All @@ -42,6 +43,11 @@ export function createApp(db: Low<Data>, options: AppOptions = {}) {
// Body parser
app.use(json())

// Delay middleware - optional
app.use((_req, _res, next) => {
setTimeout(next, options.delay || 0);
});

app.get('/', (_req, res) =>
res.send(eta.render('index.html', { data: db.data })),
)
Expand Down
11 changes: 9 additions & 2 deletions src/bin.ts
Expand Up @@ -22,6 +22,7 @@ Options:
-p, --port <port> Port (default: 3000)
-h, --host <host> Host (default: localhost)
-s, --static <dir> Static files directory (multiple allowed)
-d, --delay Delay response in milliseconds (default: 0)
--help Show this message
--version Show version number
`)
Expand All @@ -33,6 +34,7 @@ function args(): {
port: number
host: string
static: string[]
delay: number
} {
try {
const { values, positionals } = parseArgs({
Expand Down Expand Up @@ -64,6 +66,10 @@ function args(): {
type: 'boolean',
short: 'w',
},
delay: {
type: 'string',
short: 'd',
},
},
allowPositionals: true,
})
Expand Down Expand Up @@ -100,6 +106,7 @@ function args(): {
port: parseInt(values.port as string),
host: values.host as string,
static: values.static as string[],
delay: parseInt(values.delay as string)
}
} catch (e) {
if ((e as NodeJS.ErrnoException).code === 'ERR_PARSE_ARGS_UNKNOWN_OPTION') {
Expand All @@ -112,7 +119,7 @@ function args(): {
}
}

const { file, port, host, static: staticArr } = args()
const { file, port, host, static: staticArr, delay } = args()

if (!existsSync(file)) {
console.log(chalk.red(`File ${file} not found`))
Expand Down Expand Up @@ -140,7 +147,7 @@ const db = new Low<Data>(observer, {})
await db.read()

// Create app
const app = createApp(db, { logger: false, static: staticArr })
const app = createApp(db, { logger: false, static: staticArr, delay })

function logRoutes(data: Data) {
console.log(chalk.bold('Endpoints:'))
Expand Down