Skip to content

Commit

Permalink
feat: add cli option for public folder
Browse files Browse the repository at this point in the history
  • Loading branch information
bbtgnn committed Dec 6, 2023
1 parent ba00a18 commit d10a7be
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 10 deletions.
12 changes: 12 additions & 0 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,18 @@ program
}
})
)
.addOption(
new Option('--public-directory <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 <number>',
Expand Down
23 changes: 13 additions & 10 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
2 changes: 2 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ export interface Config {
openapiPath: string;
template: string;
logger: Logger;
publicDirectory: string | undefined;
staticFilesPath: string;
}

export interface Endpoints {
Expand Down

0 comments on commit d10a7be

Please sign in to comment.