From d10a7be08c679cdb69d7986c6f3d260f2b41de90 Mon Sep 17 00:00:00 2001 From: Giovanni Abbatepaolo <30571828+bbtgnn@users.noreply.github.com> Date: Wed, 6 Dec 2023 10:21:43 +0100 Subject: [PATCH] feat: add cli option for public folder --- src/cli.ts | 12 ++++++++++++ src/index.ts | 23 +++++++++++++---------- src/types.ts | 2 ++ 3 files changed, 27 insertions(+), 10 deletions(-) diff --git a/src/cli.ts b/src/cli.ts index d2ad5d2..ae2f3a5 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -32,6 +32,18 @@ program } }) ) + .addOption( + new Option('--public-directory ', 'specify the static files directory') + .env('PUBLIC_DIR') + .argParser((d) => { + try { + if (statSync(d).isDirectory()) return d; + } catch (e) { + L.error(`${bad} ${d} is not a valid directory`); + process.exit(0); + } + }) + ) .addOption( new Option( '-p, --port ', diff --git a/src/index.ts b/src/index.ts index f8fb188..51b127c 100644 --- a/src/index.ts +++ b/src/index.ts @@ -63,16 +63,19 @@ Dir.ready(async () => { generateRoutes(app); - app.get('/*', (res, req) => { - let file = path.join('public', req.getUrl()); - if (fs.existsSync(file)) { - const contentType = mime.getType(file) || 'application/octet-stream'; - res.writeHeader('Content-Type', contentType); - res.end(fs.readFileSync(file)); - } else { - res.writeStatus('404 Not Found').end('Not found'); - } - }); + const { publicDirectory } = config; + if (publicDirectory) { + app.get('/*', (res, req) => { + let file = path.join(publicDirectory, req.getUrl()); + if (fs.existsSync(file)) { + const contentType = mime.getType(file) || 'application/octet-stream'; + res.writeHeader('Content-Type', contentType); + res.end(fs.readFileSync(file)); + } else { + res.writeStatus('404 Not Found').end('Not found'); + } + }); + } app.listen(config.port, (socket) => { const port = us_socket_local_port(socket); diff --git a/src/types.ts b/src/types.ts index 031272b..52ac964 100644 --- a/src/types.ts +++ b/src/types.ts @@ -18,6 +18,8 @@ export interface Config { openapiPath: string; template: string; logger: Logger; + publicDirectory: string | undefined; + staticFilesPath: string; } export interface Endpoints {