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

fix: add handle for local files #1810

Merged
merged 1 commit into from
Mar 21, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 32 additions & 4 deletions cli/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { ServerStyleSheet } from 'styled-components';

import { compile } from 'handlebars';
import { createServer, IncomingMessage, ServerResponse } from 'http';
import { dirname, join, resolve } from 'path';
import { dirname, join, resolve, extname as getExtName } from 'path';

import * as zlib from 'zlib';

Expand Down Expand Up @@ -39,6 +39,24 @@ interface Options {
redocOptions?: any;
}

export const mimeTypes = {
'.html': 'text/html',
'.js': 'text/javascript',
'.css': 'text/css',
'.json': 'application/json',
'.png': 'image/png',
'.jpg': 'image/jpg',
'.gif': 'image/gif',
'.svg': 'image/svg+xml',
'.wav': 'audio/wav',
'.mp4': 'video/mp4',
'.woff': 'application/font-woff',
'.ttf': 'application/font-ttf',
'.eot': 'application/vnd.ms-fontobject',
'.otf': 'application/font-otf',
'.wasm': 'application/wasm',
};

const BUNDLES_DIR = dirname(require.resolve('redoc'));

/* tslint:disable-next-line */
Expand Down Expand Up @@ -191,9 +209,19 @@ async function serve(port: number, pathToSpec: string, options: Options = {}) {
'Content-Type': 'application/json',
});
} else {
response.writeHead(404);
response.write('Not found');
response.end();
try {
const filePath = join(dirname(pathToSpec), request.url || '');
const extname = String(getExtName(filePath)).toLowerCase() as keyof typeof mimeTypes;

const contentType = mimeTypes[extname] || 'application/octet-stream';
respondWithGzip(createReadStream(filePath), request, response, {
'Content-Type': contentType,
});
} catch (e) {
response.writeHead(404);
response.write('Not found');
response.end();
}
}

console.timeEnd('GET ' + request.url);
Expand Down